Import Geant4 11.0.0 source tree

This commit is contained in:
Gabriele Cosmo
2021-12-10 14:46:44 +01:00
committed by Ben Morgan
parent 6399a014b6
commit 80e2389dd8
3932 changed files with 202519 additions and 246221 deletions
+2 -2
View File
@@ -1,7 +1,7 @@
# - Build for G4tools as an "external"
# It can be built as a standard module, but we don't declare the headers
# so that their nested structure can be retained on install
geant4_add_module(G4tools SOURCES csz_inflate.cc)
geant4_add_module(G4tools SOURCES dummy.cc)
geant4_add_category(G4tools MODULES G4tools)
@@ -19,4 +19,4 @@ install(FILES tools.license DESTINATION ${CMAKE_INSTALL_DATADIR})
#
if(GEANT4_USE_FREETYPE)
install(DIRECTORY fonts/ DESTINATION ${CMAKE_INSTALL_DATADIR}/fonts)
endif()
endif()
+38
View File
@@ -2,6 +2,44 @@
# - It is NOT a substitute for good git commit messages!
# - All entries must be in reverse time order (most recent data on top)!
9 November 2021 I. Hrivnacova (g4tools-V10-07-11)
- Restored files for MPI
25 October 2021, G. Barrand (g4tools-V10-07-10)
- tools/tokenize: to help parsing some Geant4 commands "new value".
It permits to get arguments within double quotes to handle, for example, file path that
may contains spaces or a color given as "r g b".
- tools/sg/event_dispatcher,bcbk,ecbk,cbks: classes to have a mechanism in G4/G4ToolsSGSceneHandler
so that tools::sg::plots be properly resized when doing a mouse G4Viewer resize.
- tools/sg/plotter_some_styles: have the plotting setup of ROOT_default, hippodraw, style done in C++
to avoid the usage of expat for these defaults styles.
- tools/sg/light_off: a node to switch off light in a sub scene graph.
- tools/Qt/sg_viewer: in dstor, reset the "interactors" to null in the glarea.
21 October 2021 G. Barrand (g4tools-V10-07-09)
- tools/hdf5/ntuple: add code to write/read a column of vectors of strings.
- tools/waxml/ntuple: add code to write a column of vectors of strings.
19 October 2021 I. Hrivnacova (g4tools-V10-07-08)
- Added rroot/rall and rroot/THistogram needed for
tools::rroot::find_dir (used in Root analysis reader)
13 October 2021 Guy Barrand (g4tools-V10-07-07)
- sg/base_freetype, text_freetype: modifs to be able to handle embedded fonts.
- font/lato_regular_ttf: embedded lato_regular.ttf font.
- font/roboto_bold_ttf: embedded roboto_bold.ttf font.
- sg/text_hershey_marker, text_freetype_marker: modifs to avoid 'squashing' of text.
- sg/render_action, GL_viewer, atb_vertices: handle transparency by using a two pass rendering method.
- sg/gl2ps_actions/2format: avoid a warning if returning false.
- have 5.6.0 in tools/version.
08th October 2021, G. Barrand (g4tools-V10-07-06)
- remove the files not used by other Geant4 categories (up so far analysis and visualization).
- remove the test directory. It will be maintained in github/gbarrand/g4tools.
- remove the not used src/csz_inflate.cc file but have a dummy.cc for Geant4/cmake.
- CMakeLists.txt: refer to src/dummy.cc (instead of src/csz_inflate.cc) when declaring the g4tools module.
- have 5.5.0 in tools/version.
25th May 2021, B. Morgan (g4tools-V10-07-05)
- Move fonts from analysis category to tools to assist cross-category use
+23
View File
@@ -1,3 +1,26 @@
5.6.0:
- tools/tokenize: to help parsing some Geant4 commands "new value".
- tools/sg/event_dispatcher,bcbk,ecbk,cbks: classes to have a mechanism in G4/G4ToolsSGSceneHandler
so that tools::sg::plots be properly resized when doing a mouse G4Viewer resize.
- tools/sg/plotter_some_styles: have the plotting setup of ROOT_default, hippodraw, style done in C++
to avoid the usage of expat for these defaults styles.
- tools/sg/light_off: a node to switch off light in a sub scene graph.
- tools/Qt/sg_viewer: in dstor, reset the "interactor" to null in the glarea.
- tools/waxml/ntuple: add code to write a column of vectors of strings.
- tools/hdf5/ntuple: add code to write/read a column of vectors of strings.
- add back: tools/rroot/rall, THistogram.
- sg//base_freetype, text_freetype: modifs to be able to handle embedded fonts.
- font/lato_regular_ttf: embedded lato_regular.ttf font.
- font/roboto_bold_ttf: embedded roboto_bold.ttf font.
- sg/text_hershey_marker, text_freetype_marker: modifs to avoid 'squashing' of text.
- sg/render_action, GL_viewer, atb_vertices: handle transparency by using a two pass rendering method.
- sg/gl2ps_actions/2format: avoid a warning if returning false.
- have 5.6.0 in tools/version.
5.5.0:
- in geant4 repository remove the files not used by other Geant4 categories.
- in geant4 repository remove the test directory.
- in geant4 repository remove the not used src/csz_inflate.cc file but have a dummy.cc for Geant4/cmake.
- tools/zb/polygon: in scan() : initialize ET,AET,SLLBlock, before calling
CreateETandAET, to quiet g++-11 -Wmaybe-uninitialized warnings.
-215
View File
@@ -1,215 +0,0 @@
// Copyright (C) 2010, Guy Barrand. All rights reserved.
// See the file tools.license for terms.
#ifndef tools_Cocoa_session_hm
#define tools_Cocoa_session_hm
#include <Cocoa/Cocoa.h>
namespace tools {
namespace Cocoa {
class isession {
public:
virtual ~isession(){}
public:
virtual void terminate() = 0;
};
}}
#if MAC_OS_X_VERSION_MAX_ALLOWED <= 1050
@interface tools_Cocoa_session_app_delegate : NSObject {
#else
@interface tools_Cocoa_session_app_delegate : NSObject<NSApplicationDelegate> {
#endif
NSApplication* m_app;
tools::Cocoa::isession* m_session;
}
- (id)init:(NSApplication*)a_app;
- (void)dealloc;
- (void)applicationDidFinishLaunching:(NSNotification*)a_notification;
- (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication*)a_app;
- (void)set_session:(tools::Cocoa::isession*)a_session;
@end
@implementation tools_Cocoa_session_app_delegate
- (id)init:(NSApplication*)a_app {
if(self = [super init]) {}
m_app = a_app;
m_session = 0;
return self;
}
- (void)dealloc {[super dealloc];}
- (void)applicationDidFinishLaunching:(NSNotification*)a_notification {
[m_app activateIgnoringOtherApps:YES];
}
- (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication*)a_app {
if(m_session) m_session->terminate();
return NSTerminateNow;
}
- (void)set_session:(tools::Cocoa::isession*)a_session {
m_session = a_session;
}
@end
#include <ostream>
namespace tools {
namespace Cocoa {
class session : public virtual isession {
typedef isession parent;
public:
virtual void terminate() {}
public:
session(std::ostream& a_out)
:m_out(a_out),m_pool(0),m_app(0),m_to_exit(false)
{
m_pool = [[NSAutoreleasePool alloc] init];
m_app = [NSApplication sharedApplication];
tools_Cocoa_session_app_delegate* app_del = [[tools_Cocoa_session_app_delegate alloc] init:m_app];
[m_app setDelegate:app_del];
[app_del set_session:this];
[m_app setActivationPolicy:NSApplicationActivationPolicyRegular]; //so that change of NSCursor works.
//[m_app activateIgnoringOtherApps:YES]; //done in the app_delegate, so that menu works at startup.
{id menubar = [[NSMenu new] autorelease];
id appMenuItem = [[NSMenuItem new] autorelease];
[menubar addItem:appMenuItem];
id appMenu = [[NSMenu new] autorelease];
id appName = [[NSProcessInfo processInfo] processName];
id quitTitle = [@"Quit " stringByAppendingString:appName];
id quitMenuItem = [[[NSMenuItem alloc] initWithTitle:quitTitle action:@selector(terminate:) keyEquivalent:@"q"] autorelease];
[appMenu addItem:quitMenuItem];
[appMenuItem setSubmenu:appMenu];
[m_app setMainMenu:menubar];}
}
virtual ~session() {
[m_pool release];
}
protected:
session(const session& a_from):parent(a_from),m_out(a_from.m_out),m_pool(0),m_app(0),m_to_exit(false) {}
session& operator=(const session&){return *this;}
public:
std::ostream& out() const {return m_out;}
bool is_valid() const {return true;}
bool steer() {
if(!m_app) return false;
m_to_exit = false;
NSDate* date = [NSDate distantFuture]; //it will permit to block on the below.
while(!m_to_exit) {
NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
#if MAC_OS_X_VERSION_MAX_ALLOWED <= 1060 //macarts.
NSEvent* event = [m_app nextEventMatchingMask:NSAnyEventMask
#else
NSEvent* event = [m_app nextEventMatchingMask:NSEventMaskAny
#endif
untilDate:date inMode:NSDefaultRunLoopMode dequeue:YES];
if(event) {
[m_app sendEvent:event];
[m_app updateWindows];
}
[pool release];
}
return true;
}
bool sync() {
if(!m_app) return false;
NSDate* date = [NSDate distantPast]; //not blocking.
//NSDate* date = [NSDate distantFuture]; //blocking.
while(true) {
NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
#if MAC_OS_X_VERSION_MAX_ALLOWED <= 1060 //macarts.
NSEvent* event = [m_app nextEventMatchingMask:NSAnyEventMask
#else
NSEvent* event = [m_app nextEventMatchingMask:NSEventMaskAny
#endif
untilDate:date inMode:NSDefaultRunLoopMode dequeue:YES];
if(event) {
[m_app sendEvent:event];
[m_app updateWindows];
}
[pool release];
if(!event) break;
}
return true;
}
public:
NSWindow* create_window(const char* a_title,int a_x,int a_y,unsigned int a_width,unsigned int a_height) {
if(!m_app) return 0L;
NSScreen* screen = 0;
{unsigned int monitor = 0;
NSArray* scrs = [NSScreen screens];
int number = [scrs count];
if(int(monitor)<number) {
screen = (NSScreen*)[scrs objectAtIndex:monitor];
}}
NSRect screen_rect = [screen frame];
// origin = bottom, left.
NSRect rect;
rect.origin.x = a_x;
rect.origin.y = screen_rect.size.height-(a_y+a_height),
rect.size.width = a_width;
rect.size.height = a_height;
//if(args.is_arg("-no_decos")) {
// rect.origin.y -= 23; //size of APPLE menubar.
//}
#if MAC_OS_X_VERSION_MAX_ALLOWED <= 1060 //macarts.
unsigned int mask = NSTitledWindowMask;
mask |= NSResizableWindowMask;
mask |= NSClosableWindowMask;
mask |= NSMiniaturizableWindowMask;
#else
unsigned int mask = NSWindowStyleMaskTitled;
mask |= NSWindowStyleMaskResizable;
mask |= NSWindowStyleMaskClosable;
mask |= NSWindowStyleMaskMiniaturizable;
#endif
//if(args.is_arg("-no_decos")) mask = 0;
NSWindow* window = [[NSWindow alloc] initWithContentRect:rect styleMask:mask backing:NSBackingStoreBuffered
defer:NO /*we are the owner.*/ screen:screen];
NSString* title = [NSString stringWithUTF8String:a_title];
[window setTitle:title];
[window setShowsResizeIndicator:YES];
[window setAcceptsMouseMovedEvents:YES];
return window;
}
void delete_window(NSWindow* a_window) const {
if(!m_app) return;
if([a_window isReleasedWhenClosed]==YES) {
[a_window close];
} else {
[a_window close];
[a_window release];
}
}
void show_window(NSWindow* a_window){
if(!m_app) return;
[a_window makeKeyAndOrderFront:m_app];
[m_app finishLaunching];
}
public: //not in SWIG.
void set_to_exit() {m_to_exit = true;}
bool to_exit() const {return m_to_exit;}
protected:
std::ostream& m_out;
NSAutoreleasePool* m_pool;
NSApplication* m_app;
bool m_to_exit;
};
}}
#endif
@@ -1,163 +0,0 @@
// Copyright (C) 2010, Guy Barrand. All rights reserved.
// See the file tools.license for terms.
#ifndef tools_Cocoa_sg_viewer_hm
#define tools_Cocoa_sg_viewer_hm
#include "../sg/GL_viewer"
#include "session.hm"
@interface tools_Cocoa_sg_viewer_GLView : NSOpenGLView {
tools::sg::GL_viewer* m_viewer;
}
- (id)init:(NSRect)rect viewer:(tools::sg::GL_viewer*)a_viewer;
- (void)dealloc;
- (void)drawRect:(NSRect)a_rect;
@end
@implementation tools_Cocoa_sg_viewer_GLView
- (id)init:(NSRect)a_rect viewer:(tools::sg::GL_viewer*)a_viewer {
NSOpenGLPixelFormatAttribute att[32];
int i = 0;
att[i++] = NSOpenGLPFADoubleBuffer;
att[i++] = NSOpenGLPFAAccelerated;
att[i++] = NSOpenGLPFAAccumSize;
att[i++] = (NSOpenGLPixelFormatAttribute)32;
att[i++] = NSOpenGLPFAColorSize;
att[i++] = (NSOpenGLPixelFormatAttribute)32;
att[i++] = NSOpenGLPFADepthSize;
att[i++] = (NSOpenGLPixelFormatAttribute)32;
// Antialiasing :
att[i++] = NSOpenGLPFASampleBuffers;
att[i++] = 1;
att[i++] = NSOpenGLPFASamples;
att[i++] = 2;
att[i++] = NSOpenGLPFANoRecovery;
att[i] = (NSOpenGLPixelFormatAttribute)0;
NSOpenGLPixelFormat *pixelFormat = [[NSOpenGLPixelFormat alloc] initWithAttributes:att];
if(self = [super initWithFrame:a_rect pixelFormat:pixelFormat]) {
// flush buffer only during the vertical retrace of the monitor
const GLint vals[1] = {1};
#if MAC_OS_X_VERSION_MAX_ALLOWED < 1014
[[self openGLContext] setValues:vals forParameter:NSOpenGLCPSwapInterval];
#else
[[self openGLContext] setValues:vals forParameter:NSOpenGLContextParameterSwapInterval];
#endif
}
[pixelFormat release];
m_viewer = a_viewer;
return self;
}
- (void)dealloc {[super dealloc];}
- (void)drawRect:(NSRect)a_rect {
if(!m_viewer) return;
#if MAC_OS_X_VERSION_MAX_ALLOWED < 101500
int w = a_rect.size.width;
int h = a_rect.size.height;
#else
NSRect backing_rect = [self convertRectToBacking:a_rect];
int w = (int)(backing_rect.size.width);
int h = (int)(backing_rect.size.height);
#endif
m_viewer->set_size(w,h);
[[self openGLContext] makeCurrentContext];
m_viewer->render();
[[self openGLContext] flushBuffer];
}
@end
#if MAC_OS_X_VERSION_MAX_ALLOWED <= 1050
@interface tools_Cocoa_sg_viewer_win_delegate : NSObject {
#else
@interface tools_Cocoa_sg_viewer_win_delegate : NSObject<NSWindowDelegate> {
#endif
tools::Cocoa::session* m_session;
}
- (id)init:(tools::Cocoa::session*)a_session;
- (void)dealloc;
- (void)windowWillClose:(NSNotification*)a_not;
@end
@implementation tools_Cocoa_sg_viewer_win_delegate
- (id)init:(tools::Cocoa::session*)a_session {
if(self = [super init]) {}
m_session = a_session;
return self;
}
- (void)dealloc {[super dealloc];}
- (void)windowWillClose:(NSNotification*)a_not {
m_session->set_to_exit();
}
@end
namespace tools {
namespace Cocoa {
class sg_viewer : public sg::GL_viewer {
TOOLS_HEADER(sg_viewer,tools::Cocoa::sg_viewer,sg::GL_viewer)
public:
sg_viewer(session& a_session,
int a_x = 0,int a_y = 0,
unsigned int a_width = 500,unsigned int a_height = 500,
const std::string& a_win_title = "")
:parent(a_session.out(),a_width,a_height)
,m_session(a_session)
,m_win(0),m_GLView(0)
{
m_win = m_session.create_window(a_win_title.c_str(),a_x,a_y,a_width,a_height);
if(!m_win) return; //throw
tools_Cocoa_sg_viewer_win_delegate* _win_delegate = [[tools_Cocoa_sg_viewer_win_delegate alloc] init:&a_session];
[m_win setDelegate:_win_delegate];
NSRect rect;
rect = [m_win frame];
rect = [m_win contentRectForFrameRect:rect]; //window content true size.
m_GLView = [[tools_Cocoa_sg_viewer_GLView alloc] init:rect viewer:this];
[m_win setContentView:m_GLView];
[m_GLView release];
}
virtual ~sg_viewer() {
if(m_win) {
m_session.delete_window(m_win);
//m_session.sync();
}
}
protected:
sg_viewer(const sg_viewer& a_from)
:parent(a_from)
,m_session(a_from.m_session)
,m_win(0),m_GLView(0)
{}
sg_viewer& operator=(const sg_viewer& a_from) {
parent::operator=(a_from);
return *this;
}
public:
bool has_window() const {return m_win?true:false;}
bool show() {
if(!m_win) return false;
m_session.show_window(m_win);
return true;
}
void win_render() {
[[m_GLView openGLContext] makeCurrentContext];
render();
[[m_GLView openGLContext] flushBuffer];
}
protected:
session& m_session;
NSWindow* m_win;
tools_Cocoa_sg_viewer_GLView* m_GLView;
};
}}
#endif
-54
View File
@@ -1,54 +0,0 @@
// Copyright (C) 2010, Guy Barrand. All rights reserved.
// See the file tools.license for terms.
#ifndef tools_Qt_plots_glarea
#define tools_Qt_plots_glarea
#include <QtOpenGL/qgl.h>
#include "../sg/GL_plots_viewer"
namespace tools {
namespace Qt {
class plots_glarea : public QGLWidget {
typedef QGLWidget parent;
public:
virtual void initialieGL() {}
virtual void resizeGL(int a_w,int a_h){
//::printf("debug : resize : %d %d\n",a_w,a_h);
#if QT_VERSION < 0x050000
#else
m_width = a_w;
m_height = a_h;
#endif
}
//virtual void paintGL();
virtual void paintGL() {
#if QT_VERSION < 0x050000
//::printf("debug : tools::Qt::plots_glarea::paintGL %d %d\n",width(),height());
m_viewer.set_size(width(),height());
#else
//::printf("debug : tools::Qt::plots_glarea::paintGL %d %d\n",m_width,m_height);
m_viewer.set_size(m_width,m_height);
#endif
m_viewer.render();
}
public:
plots_glarea(QWidget* a_parent,tools::sg::GL_plots_viewer& a_viewer):parent(a_parent),m_viewer(a_viewer){}
virtual ~plots_glarea(){}
protected:
tools::sg::GL_plots_viewer& m_viewer;
#if QT_VERSION < 0x050000
#else
protected:
int m_width;
int m_height;
#endif
};
}}
#endif
+1 -2
View File
@@ -11,10 +11,8 @@
#include <QtCore/qglobal.h> //For QT_VERSION.
#if QT_VERSION < 0x050000
#include <QtGui/qpushbutton.h>
#include <QtGui/qboxlayout.h>
#else
#include <QtWidgets/qpushbutton.h>
#include <QtWidgets/qboxlayout.h>
#endif
@@ -47,6 +45,7 @@ public:
m_shell->setLayout(layout);
}
virtual ~sg_viewer() {
if(m_glarea) m_glarea->set_device_interactor(0);
if(m_shell && m_own_shell) {
m_session.delete_window(m_shell);
//m_session.sync();
-810
View File
@@ -1,810 +0,0 @@
// Copyright (C) 2010, Guy Barrand. All rights reserved.
// See the file tools.license for terms.
#ifndef tools_Windows_WinTk
#define tools_Windows_WinTk
#include "../Windows/tools" //and not "tools", because this fancy VisualC++ will not find the file!
#include <tools/touplow>
#include <tools/words>
#ifdef TOOLS_MEM
#include <tools/mem>
#endif
#include <vector>
namespace tools {
namespace WinTk {
class Component;
class CallbackData {
public:
CallbackData():x(0),y(0),wparam(0),lparam(0){}
public:
std::string value;
int x;
int y;
WPARAM wparam;
LPARAM lparam;
};
typedef void (*Callback)(Component&,CallbackData&,void*);
class Component {
typedef std::vector< std::pair<Callback,void*> > Callbacks;
typedef std::pair<std::string,Callbacks> NamedCallbacks;
#ifdef TOOLS_MEM
TOOLS_SCLASS(tools::WinTk::Component)
#endif
public:
Component(const std::string& aType):fType(aType),fWindow(0),fParent(0){
#ifdef TOOLS_MEM
tools::mem::increment(s_class().c_str());
#endif
}
Component(const std::string& aType,Component& aParent):fType(aType),fWindow(0),fParent(&aParent) {
#ifdef TOOLS_MEM
tools::mem::increment(s_class().c_str());
#endif
}
virtual ~Component() {
#ifdef TOOLS_MEM
tools::mem::decrement(s_class().c_str());
#endif
}
protected:
Component(Component&) {
#ifdef TOOLS_MEM
tools::mem::increment(s_class().c_str());
#endif
}
Component& operator=(Component&) {return *this;}
public:
std::string name() const {return fName;}
void setName(const std::string& aName) {fName = aName;}
const std::string& type() const {return fType;}
HWND nativeWindow() {return fWindow;}
Component* parent() const {return fParent;}
virtual void show() {
//if(!fWindow) return;
//::ShowWindow(fWindow,SW_SHOWDEFAULT);
}
void hide() {
if(!fWindow) return;
::ShowWindow(fWindow,SW_HIDE);
}
virtual bool size(unsigned int& aWidth,unsigned int& aHeight) {
aWidth = 0;
aHeight = 0;
if(!fWindow) return false;
RECT rect;
::GetClientRect(fWindow,&rect);
aWidth = rect.right-rect.left;
aHeight = rect.bottom-rect.top;
return true;
}
virtual bool position(int& aX,int& aY) {
aX = 0;
aY = 0;
if(!fWindow) return false;
RECT rect;
::GetClientRect(fWindow,&rect);
aX = rect.left;
aY = rect.top;
return true;
}
Component* findFather(const std::string& aType) {
if(aType==type()) return this;
Component* parent = fParent;
while(parent) {
if(aType==parent->type()) return parent;
parent = parent->fParent;
}
return 0;
}
bool setBackground(double aR,double aG,double aB){
if(!fWindow) return false;
int r = int(aR*255.0);
if((r<0)||(r>255)) return false;
int g = int(aG*255.0);
if((g<0)||(g>255)) return false;
int b = int(aB*255.0);
if((b<0)||(b>255)) return false;
/*
//COLORREF cr = RGB(r,g,b);
HBRUSH brush = ::CreateSolidBrush(RGB(r,g,b));
::printf("debug : WinTk::Component::setBackground : brush %lu\n",brush);
HBRUSH prev = (HBRUSH)::GetClassLongPtr(fWindow,GCLP_HBRBACKGROUND);
::printf("debug : WinTk::Component::setBackground : prev brush %lu\n",prev);
{WNDCLASSEX wc;
::GetClassInfoEx(::GetModuleHandle(NULL),WC_STATIC,&wc);
::printf("debug : prev brush xxx %lu\n",wc.hbrBackground);}
ULONG_PTR stat =
::SetClassLongPtr(fWindow,GCLP_HBRBACKGROUND,(LONG_PTR)brush);
if(prev && !stat) {
::printf("debug : WinTk::Component::setBackground : SetClassLongPtr failed.\n");
return false;
}
{ULONG_PTR stat =
::SetClassLongPtr(fWindow,GCLP_HBRBACKGROUND,(LONG_PTR)brush);
::printf("debug : WinTk::Component::setBackground : SetClassLongPtr failed.yyy %lu.\n",stat);}
{WNDCLASSEX wc;
::GetClassInfoEx(::GetModuleHandle(NULL),WC_STATIC,&wc);
::printf("debug : prev brush yyy %lu\n",wc.hbrBackground);}
if(!::InvalidateRect(fWindow,NULL,TRUE)) {
::printf("debug : WinTk::Component::setBackground : InvalidateRect failed.\n");
return false;
}
//::DeleteObject(brush);
return true;
*/
return false;
}
public:
void addCallback(const std::string& aName,Callback aFunction,void* aTag) {
NamedCallbacks* cbks = 0;
std::vector<NamedCallbacks>::iterator it;
for(it=fCallbacks.begin();it!=fCallbacks.end();++it) {
if(aName==(*it).first) {
cbks = &(*it);
break;
}
}
if(!cbks) {
fCallbacks.push_back(std::pair<std::string,Callbacks>(aName,Callbacks()));
cbks = &(fCallbacks.back());
}
cbks->second.push_back(std::pair<Callback,void*>(aFunction,aTag));
}
void removeCallback(const std::string& aName,Callback aFunction,void* aTag) {
NamedCallbacks* cbks = 0;
std::vector<NamedCallbacks>::iterator it;
for(it=fCallbacks.begin();it!=fCallbacks.end();++it) {
if(aName==(*it).first) {
cbks = &(*it);
break;
}
}
if(cbks) {
Callbacks::iterator it;
for(it=cbks->second.begin();it!=cbks->second.end();++it) {
if( (aFunction==(*it).first) && (aTag==(*it).second) ) {
cbks->second.erase(it);
return;
}
}
}
}
bool executeCallbacks(const std::string& aName,CallbackData& aData) {
std::vector<NamedCallbacks>::const_iterator it;
for(it=fCallbacks.begin();it!=fCallbacks.end();++it) {
if(aName==(*it).first) {
const Callbacks& cbks = (*it).second;
Callbacks::const_iterator it2;
for(it2=cbks.begin();it2!=cbks.end();++it2) {
Callback cbk = (*it2).first;
if(cbk) {
HWND back_fWindow = fWindow;
cbk(*this,aData,(*it2).second);
// The callback may have destroyed the Component and
// the native HWND. The below checks that.
// In a proc, it is better to not use the HWND
// (or the Component) after calling executeCallbacks.
if(back_fWindow && !::GetWindowLongPtr(back_fWindow,GWLP_USERDATA)) {
//::printf("WinTk::Component::executeCallbacks : WARNING : A callback destroyed the native HWND window !\n");
return false;
}
}
}
return true;
}
}
return false;
}
bool hasCallbacks(const std::string& aName) const {
std::vector<NamedCallbacks>::const_iterator it;
for(it=fCallbacks.begin();it!=fCallbacks.end();++it) {
if(aName==(*it).first) return true;
}
return false;
}
protected:
static void wm__destroy(HWND aWindow) {
Component* This = (Component*)::GetWindowLongPtr(aWindow,GWLP_USERDATA);
if(This) { //How to be sure that we have a Component* ???
if(This->fWindow!=aWindow) {
::printf("WinTk::Component::wm_destroy : HWND mismatch !\n");
}
if(This->hasCallbacks("WM_DESTROY")) {
CallbackData data;
This->executeCallbacks("WM_DESTROY",data);
}
This->fWindow = 0;
}
::SetWindowLongPtr(aWindow,GWLP_USERDATA,LONG_PTR(NULL));
}
protected:
// WM_PARENTNOTIFY is sent within the CreateWindow of the child.
// When received by the parent, the parent Post (not Send) to itself
// a WM_TK_CHILDCREATED in order to be notify of the child creation
// out of any CreateWindow.
#define WM_TK_CHILDCREATED ((WM_USER)+888)
#define WM_TK_CHILDDELETED ((WM_USER)+889)
#define TK_KEY 127 // To be sure that it is a message of our own.
static LRESULT CALLBACK containerProc(HWND aWindow,UINT aMessage,WPARAM aWParam,LPARAM aLParam) {
//////////////////////////////////////////////////////////////////////////////
// Some child send notification message to their parent (instead of sending
// the message to themselves !). This procedure is used by containers
// to forward these messages to the child.
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!//
switch(aMessage) {
case WM_PARENTNOTIFY:{
if(aWParam==WM_CREATE) {
::PostMessage(aWindow,WM_TK_CHILDCREATED,TK_KEY,0);
return 0;
} else if(aWParam==WM_DESTROY) {
::PostMessage(aWindow,WM_TK_CHILDDELETED,TK_KEY,0);
return 0;
}
}break;
case WM_TK_CHILDCREATED:{
if(aWParam==TK_KEY) {
RECT rect;
::GetClientRect(aWindow,&rect);
LPARAM size = MAKELPARAM(rect.right-rect.left,rect.bottom-rect.top);
::SendMessage(aWindow,WM_SIZE,(WPARAM)0,size);
return 0;
}
}break;
case WM_TK_CHILDDELETED:{
if(aWParam==TK_KEY) {
}
}break;
case WM_NOTIFY:{ //Coming from a child (combobox, scrollbar, toolbar).
NMHDR* nmhdr = (NMHDR*)aLParam;
HWND from_win = nmhdr->hwndFrom;
if(from_win!=aWindow) {
::SendMessage(from_win,aMessage,aWParam,aLParam);
}
}return 0;
case WM_COMMAND:
case WM_VSCROLL:
case WM_HSCROLL:{
::SendMessage((HWND)aLParam,aMessage,aWParam,(LPARAM)0);
}return 0;
}
return TRUE; //Not handled.
}
#undef WM_TK_CHILDCREATED
#undef WM_TK_CHILDDELETED
#undef TK_KEY
protected:
void destroy() {
if(hasCallbacks("delete")) {
CallbackData data;
executeCallbacks("delete",data);
}
if(fWindow) {
::SetWindowLongPtr(fWindow,GWLP_USERDATA,LONG_PTR(NULL));
::DestroyWindow(fWindow);
fWindow = 0;
}
}
void rubberDrawLine(POINT& aBegin,POINT& aEnd) {
if(!fWindow) return;
HPEN pen = ::CreatePen(PS_SOLID,5,RGB(0,0,0));
HDC hdc = ::GetWindowDC(fWindow);
HPEN oldPen = SelectPen(hdc,pen);
int oldROP = ::SetROP2(hdc,R2_NOT);
POINT pt;
::MoveToEx(hdc,aBegin.x,aBegin.y,&pt);
::LineTo(hdc,aEnd.x,aEnd.y);
::SetROP2(hdc,oldROP);
SelectPen(hdc,oldPen);
::ReleaseDC(fWindow,hdc);
::DeletePen(pen);
}
void rubberDrawRect(POINT& aBegin,POINT& aEnd) {
if(!fWindow) return;
HPEN pen = ::CreatePen(PS_SOLID,0,RGB(0,0,0));
HDC hdc = ::GetWindowDC(fWindow);
HPEN oldPen = SelectPen(hdc,pen);
int oldROP = ::SetROP2(hdc,R2_NOT);
POINT pt;
::MoveToEx(hdc,aBegin.x,aBegin.y,&pt);
::LineTo(hdc,aBegin.x,aEnd.y);
::LineTo(hdc,aEnd.x,aEnd.y);
::LineTo(hdc,aEnd.x,aBegin.y);
::LineTo(hdc,aBegin.x,aBegin.y);
::SetROP2(hdc,oldROP);
SelectPen(hdc,oldPen);
::ReleaseDC(fWindow,hdc);
::DeletePen(pen);
}
private:
std::string fType;
protected:
HWND fWindow;
Component* fParent;
std::vector<NamedCallbacks> fCallbacks;
std::string fName;
};
class Shell;
typedef void(*SetFocusCallback)(Shell*,void*);
class Shell : public Component {
public:
Shell(unsigned int aMask)
:Component("Shell")
,fFocusWindow(0)
,fSetFocusCallback(0)
,fSetFocusTag(0)
,fAcceleratorTable(0)
{
static char sWindowClassName[] = "WinTk::Shell";
static bool done = false;
if(!done) {
WNDCLASS wc;
wc.style = CS_HREDRAW | CS_VREDRAW;
wc.lpfnWndProc = (WNDPROC)Shell::proc;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hInstance = ::GetModuleHandle(NULL);
wc.hIcon = LoadIcon(NULL,IDI_APPLICATION);
wc.hCursor = LoadCursor(NULL,IDC_ARROW);
wc.hbrBackground = GetSysColorBrush(COLOR_BTNFACE);
wc.lpszMenuName = sWindowClassName;
wc.lpszClassName = sWindowClassName;
::RegisterClass(&wc);
done = true;
}
fWindow = ::CreateWindow(sWindowClassName,
NULL,
aMask, //WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT,CW_USEDEFAULT,
400,400,
NULL,NULL,
::GetModuleHandle(NULL),
NULL);
if(!fWindow) return;
::SetWindowLongPtr(fWindow,GWLP_USERDATA,LONG_PTR(this));
}
virtual ~Shell() {
if(fAcceleratorTable) {
::DestroyAcceleratorTable(fAcceleratorTable);
fAcceleratorTable = 0;
}
destroy();
}
protected:
Shell(Shell& a_from):Component(a_from) {}
Shell& operator=(Shell&) {return *this;}
public:
virtual void show() {
if(!fWindow) return;
::SetForegroundWindow(fWindow);
::ShowWindow(fWindow,SW_SHOWDEFAULT);
::UpdateWindow(fWindow);
::DrawMenuBar(fWindow);
}
void setTitle(const std::string& aString) {
if(!fWindow) return;
::SetWindowText(fWindow,aString.c_str());
}
void setGeometry(int aX,int aY,unsigned int aWidth,unsigned int aHeight) {
//////////////////////////////////////////////////////////////////////////////
// Given width, height is the desired client area.
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!//
if(!fWindow) return;
int hborder = ::GetSystemMetrics(SM_CYCAPTION);
if(::GetWindowLongPtr(fWindow,GWLP_ID)) // Has a menubar.
hborder += ::GetSystemMetrics(SM_CYMENU);
::MoveWindow(fWindow,aX,aY,aWidth,hborder + aHeight,TRUE);
}
void setSize(unsigned int aWidth,unsigned int aHeight) {
//////////////////////////////////////////////////////////////////////////////
// Given width, height is the desired client area.
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!//
if(!fWindow) return;
int hborder = ::GetSystemMetrics(SM_CYCAPTION);
RECT rect;
::GetWindowRect(fWindow,&rect);
::MoveWindow(fWindow,rect.left,rect.top,aWidth,hborder + aHeight,TRUE);
}
void setFocusWindow(HWND aWindow) {fFocusWindow = aWindow;}
HWND focusWindow() {return fFocusWindow;}
void setSetFocusCallback(SetFocusCallback aCallback,void* aTag) {
fSetFocusCallback = aCallback;
fSetFocusTag = aTag;
}
void callSetFocusCallback() {
if(!fSetFocusCallback) return;
fSetFocusCallback(this,fSetFocusTag);
}
HACCEL nativeAcceleratorTable() {return fAcceleratorTable;}
bool addAccelerator(const std::string& aString,int aID) {
//printf("debug : accel : %s %d\n",aString.c_str(),aID);
// aString should be of the form : "a" or "Ctrl+a".
ACCEL acc;
//acc.fVirt : FALT, FCONTROL, FNOINVERT, FSHIFT, FVIRTKEY
{acc.cmd = aID;
std::vector<std::string> words;
std::string s(aString);
tools::touppercase(s);
tools::words(s,"+",false,words);
if(words.size()==1) {
acc.fVirt = FVIRTKEY;
if(!string_to_VK(words[0],acc.key)) return false;
} else if((words.size()==2)&&(words[1].size())) {
if(words[0]=="CTRL") {
acc.fVirt = FCONTROL;
} else if(words[0]=="ALT") {
acc.fVirt = FALT;
} else if(words[0]=="SHIFT") {
acc.fVirt = FSHIFT;
} else {
return false;
}
acc.fVirt |= FVIRTKEY;
if(!string_to_VK(words[1],acc.key)) return false;
} else {
return false;
}}
if(!fAcceleratorTable) {
fAcceleratorTable = ::CreateAcceleratorTable(&acc,1);
} else {
int n = ::CopyAcceleratorTable(fAcceleratorTable,NULL,0);
ACCEL* tbl = new ACCEL[n+1];
::CopyAcceleratorTable(fAcceleratorTable,tbl,n);
ACCEL& tacc = tbl[n];
tacc.fVirt = acc.fVirt;
tacc.key = acc.key;
tacc.cmd = acc.cmd;
::DestroyAcceleratorTable(fAcceleratorTable);
fAcceleratorTable = ::CreateAcceleratorTable(tbl,n+1);
delete [] tbl;
}
return true;
}
private:
static bool string_to_VK(const std::string& aString,WORD& a_VK) {
//VK_xxx are defined in WinUser.h
if(aString.size()==1) { a_VK = aString[0];return true;} //WM_W is 'W'
#define S_VK(aWhat) \
if(!::strcmp(aString.c_str(),#aWhat)) { a_VK = VK_##aWhat;return true;}
S_VK(BACK)
S_VK(TAB)
S_VK(CLEAR)
S_VK(RETURN)
S_VK(ESCAPE)
S_VK(SPACE)
S_VK(UP)
S_VK(DOWN)
S_VK(LEFT)
S_VK(RIGHT)
S_VK(F1)
S_VK(F2)
S_VK(F3)
S_VK(F4)
S_VK(F5)
S_VK(F6)
S_VK(F7)
S_VK(F8)
S_VK(F9)
S_VK(F10)
S_VK(F11)
S_VK(F12)
S_VK(F13)
S_VK(F14)
S_VK(F15)
S_VK(F16)
S_VK(F17)
S_VK(F18)
S_VK(F19)
S_VK(F20)
S_VK(F21)
S_VK(F22)
S_VK(F23)
S_VK(F24)
//FIXME : handle other keys ? NUMPAD[0-9]
#undef S_VK
return false;
}
static LRESULT CALLBACK proc(HWND aWindow,UINT aMessage,WPARAM aWParam,LPARAM aLParam) {
switch (aMessage) {
// Same logic as containerProc :
case WM_NOTIFY:{ //Coming from a child (combobox, scrollbar, toolbar).
NMHDR* nmhdr = (NMHDR*)aLParam;
HWND from_win = nmhdr->hwndFrom;
if(from_win!=aWindow) {
::SendMessage(from_win,aMessage,aWParam,aLParam);
}
}return 0;
// Else :
case WM_SIZE:{ // Assume one child window ! FIXME : have a message if not.
int width = LOWORD(aLParam);
int height = HIWORD(aLParam);
HWND hwnd = GetFirstChild(aWindow);
if(hwnd) {
//FIXME : have to treat the case of TOOLBAR not being the first.
if(GetClassName(hwnd)==std::string(TOOLBARCLASSNAME)) {
HWND next = GetNextSibling(hwnd);
// Share area between toolbar and second child :
RECT rect;
::GetWindowRect(hwnd,&rect);
int htb = rect.bottom-rect.top;
SetGeometry(next,0,htb,width,height-htb);
} else {
SetGeometry(hwnd,0,0,width,height);
}
}
}return 0;
case WM_SETFOCUS:{
Shell* This = (Shell*)::GetWindowLongPtr(aWindow,GWLP_USERDATA);
if(This) {
This->callSetFocusCallback();
HWND win = This->focusWindow();
if(win) ::SetFocus(win);
}
}return 0;
case WM_INITMENUPOPUP:{ //0x0117
//aWParam is the HMENU (from CreatePopupMenu)
//aLParam is the MenuItemCount
Shell* This = (Shell*)::GetWindowLongPtr(aWindow,GWLP_USERDATA);
if(This) {
CallbackData data;
data.wparam = aWParam;
This->executeCallbacks("cascading",data);
}
} return 0;
case WM_COMMAND:{ //Coming from a menu item, a toolbar !
if(aLParam) {
// From a toolbar ; send it back to it :
::SendMessage((HWND)aLParam,aMessage,aWParam,0);
} else {
//if(HIWORD(aWParam)==1) { //From an accelerator.
//}
// From a menu item :
Shell* This = (Shell*)::GetWindowLongPtr(aWindow,GWLP_USERDATA);
if(This) {
CallbackData data;
data.wparam = LOWORD(aWParam);
This->executeCallbacks("activate",data);
}
}
}return 0;
case WM_CLOSE:{
Shell* This = (Shell*)::GetWindowLongPtr(aWindow,GWLP_USERDATA);
if(This) {
if(This->hasCallbacks("close")) {
CallbackData data;
This->executeCallbacks("close",data);
}
}
}break; //NOTE : can't be return 0.
case WM_DESTROY:wm__destroy(aWindow);return 0;
}
return (DefWindowProc(aWindow,aMessage,aWParam,aLParam));
}
private:
HWND fFocusWindow;
SetFocusCallback fSetFocusCallback;
void* fSetFocusTag;
HACCEL fAcceleratorTable;
};
class OpenGLArea : public Component {
public:
OpenGLArea(Component& aParent)
:Component("OpenGLArea",aParent)
,fContext(0)
,fHDC(0)
{
if(!fParent || !fParent->nativeWindow()) return;
HWND parent = fParent->nativeWindow();
static char sOpenGLAreaClassName[] = "WinTk::OpenGLArea";
static bool done = false;
if(!done) {
WNDCLASS wc;
wc.style = CS_HREDRAW | CS_VREDRAW;
wc.lpfnWndProc = (WNDPROC)OpenGLArea::proc;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hInstance = GetWindowInstance(parent),
wc.hIcon = LoadIcon(NULL,IDI_APPLICATION);
wc.hCursor = LoadCursor(NULL,IDC_ARROW);
wc.hbrBackground = GetSysColorBrush(COLOR_BTNFACE);
wc.lpszMenuName = sOpenGLAreaClassName;
wc.lpszClassName = sOpenGLAreaClassName;
::RegisterClass(&wc);
done = true;
}
// The WS_BORDER is needed. Else probleme of size at startup.
RECT rect;
::GetClientRect(parent,&rect);
fWindow = ::CreateWindow(sOpenGLAreaClassName,
NULL,
WS_CHILD | WS_VISIBLE,
0,0,
rect.right-rect.left,
rect.bottom-rect.top,
parent,NULL,
GetWindowInstance(parent),
NULL);
if(!fWindow) return;
::SetWindowLongPtr(fWindow,GWLP_USERDATA,LONG_PTR(this));
// initialize OpenGL rendering :
fHDC = ::GetDC(fWindow);
if( fHDC && SetWindowPixelFormat(fHDC) ) {
fContext = ::wglCreateContext(fHDC);
}
}
virtual ~OpenGLArea() {
if(wglGetCurrentContext()!=NULL) wglMakeCurrent(NULL,NULL);
if(fContext) {
wglDeleteContext(fContext);
fContext = 0;
}
destroy();
}
protected:
OpenGLArea(OpenGLArea& a_from):Component(a_from) {}
OpenGLArea& operator=(OpenGLArea&) {return *this;}
public:
bool write_gl2ps(const std::string&,const std::string&);
private:
static LRESULT CALLBACK proc(HWND aWindow,UINT aMessage,WPARAM aWParam,LPARAM aLParam) {
switch (aMessage) {
case WM_PAINT:{
PAINTSTRUCT ps;
HDC hDC = BeginPaint(aWindow,&ps);
OpenGLArea* This = (OpenGLArea*)::GetWindowLongPtr(aWindow,GWLP_USERDATA);
if(This) {
HDC hdc = This->fHDC;
HGLRC context = This->fContext;
if(hdc && context) {
::wglMakeCurrent(hdc,context);
// User OpenGL paint code :
CallbackData data;
data.wparam = aWParam;
data.lparam = aLParam;
This->executeCallbacks("paint",data);
::SwapBuffers(hdc);
}
}
EndPaint(aWindow,&ps);
}return 0;
case WM_LBUTTONDOWN:{
OpenGLArea* This = (OpenGLArea*)::GetWindowLongPtr(aWindow,GWLP_USERDATA);
if(This) {
CallbackData data;
data.wparam = aWParam;
data.lparam = aLParam;
data.value = "ButtonPress";
data.x = LOWORD(aLParam);
data.y = HIWORD(aLParam);
This->executeCallbacks("event",data);
}
}return 0;
case WM_LBUTTONUP:{
OpenGLArea* This = (OpenGLArea*)::GetWindowLongPtr(aWindow,GWLP_USERDATA);
if(This) {
CallbackData data;
data.wparam = aWParam;
data.lparam = aLParam;
data.value = "ButtonRelease";
data.x = LOWORD(aLParam);
data.y = HIWORD(aLParam);
This->executeCallbacks("event",data);
}
} return 0;
case WM_MOUSEMOVE:{
unsigned int state = aWParam;
if((state & MK_LBUTTON)==MK_LBUTTON) {
OpenGLArea* This = (OpenGLArea*)::GetWindowLongPtr(aWindow,GWLP_USERDATA);
if(This) {
CallbackData data;
data.wparam = aWParam;
data.lparam = aLParam;
data.value = "MotionNotify";
data.x = LOWORD(aLParam);
data.y = HIWORD(aLParam);
This->executeCallbacks("event",data);
}
}
}return 0;
case WM_DESTROY:wm__destroy(aWindow);return 0;
}
return (DefWindowProc(aWindow,aMessage,aWParam,aLParam));
}
static bool SetWindowPixelFormat(HDC aHdc) {
PIXELFORMATDESCRIPTOR pfd;
pfd.nSize = sizeof(PIXELFORMATDESCRIPTOR);
pfd.nVersion = 1;
pfd.dwFlags =
PFD_DRAW_TO_WINDOW |
PFD_SUPPORT_OPENGL |
PFD_DOUBLEBUFFER |
PFD_STEREO_DONTCARE;
pfd.iPixelType = PFD_TYPE_RGBA;
pfd.cColorBits = 32;
pfd.cRedBits = 8;
pfd.cRedShift = 16;
pfd.cGreenBits = 8;
pfd.cGreenShift = 8;
pfd.cBlueBits = 8;
pfd.cBlueShift = 0;
pfd.cAlphaBits = 0;
pfd.cAlphaShift = 0;
pfd.cAccumBits = 64;
pfd.cAccumRedBits = 16;
pfd.cAccumGreenBits = 16;
pfd.cAccumBlueBits = 16;
pfd.cAccumAlphaBits = 0;
pfd.cDepthBits = 32;
pfd.cStencilBits = 8;
pfd.cAuxBuffers = 0;
pfd.iLayerType = PFD_MAIN_PLANE;
pfd.bReserved = 0;
pfd.dwLayerMask = 0;
pfd.dwVisibleMask = 0;
pfd.dwDamageMask = 0;
int pixelIndex = ::ChoosePixelFormat(aHdc,&pfd);
if (pixelIndex==0) {
// Let's choose a default index.
pixelIndex = 1;
if (::DescribePixelFormat(aHdc,
pixelIndex,
sizeof(PIXELFORMATDESCRIPTOR),
&pfd)==0) {
return false;
}
}
if (::SetPixelFormat(aHdc,pixelIndex,&pfd)==FALSE) return false;
return true;
}
private:
HGLRC fContext;
HDC fHDC;
};
}}
#endif
-601
View File
@@ -1,601 +0,0 @@
// Copyright (C) 2010, Guy Barrand. All rights reserved.
// See the file tools.license for terms.
#ifndef tools_Windows_tools
#define tools_Windows_tools
#include <windows.h>
#include <windowsx.h>
#include <string>
namespace tools {
namespace WinTk {
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
inline bool GetClassName(HWND aWindow,std::string& a_value) {
if(!aWindow) {a_value.clear();return false;}
char className[256];
::GetClassName(aWindow,className,128);
a_value = std::string(className);
return true;
}
inline HWND GetChildByClassName(HWND aWindow,const std::string& aClassName) {
// A CBS_SIMPLE has two children of class ComboLBox and Edit.
// At creation, a CBS_DROPDOWN has one child of class Edit.
if(!aWindow) return NULL;
HWND child = GetFirstChild(aWindow);
std::string ss;
while(child) {
GetClassName(child,ss);
if(ss==aClassName) return child;
child = GetNextSibling(child);
}
return NULL;
}
inline void SetGeometry(HWND aWindow,int aX,int aY,unsigned int aWidth,unsigned int aHeight) {
if(!aWindow) return;
std::string className;
GetClassName(aWindow,className);
if(className=="ComboBox") {
// For a Combo the height is the visible part + the height of the list !
// (A combo may have no edit control).
::MoveWindow(aWindow,aX,aY,aWidth,200,TRUE);
} else {
::MoveWindow(aWindow,aX,aY,aWidth,aHeight,TRUE);
}
}
inline void GetSize(HWND aWindow,int& aWidth,int& aHeight) {
RECT rect;
::GetWindowRect(aWindow,&rect);
aWidth = rect.right-rect.left;
aHeight = rect.bottom-rect.top;
}
inline unsigned int GetNumberOfChildren(HWND aWindow) {
unsigned int number = 0;
HWND child = GetFirstChild(aWindow);
while(child) {
number++;
child = GetNextSibling(child);
}
return number;
}
inline HWND GetLastChild(HWND aWindow) {
HWND child = GetFirstChild(aWindow);
while(child) {
HWND next = GetNextSibling(child);
if(!next) return child;
child = next;
}
return 0;
}
inline void GetText(HWND aWindow,std::string& a_value) {
int l = ::GetWindowTextLength(aWindow);
a_value.resize(l);
::GetWindowText(aWindow,(char*)a_value.c_str(),l+1);
}
/*
inline void PrintChildren(HWND aWindow) {
// A CBS_SIMPLE has two children of class ComboLBox and Edit.
// At creation, a CBS_DROPDOWN has one child of class Edit.
if(!aWindow) return;
HWND child = GetFirstChild(aWindow);
while(child) {
//printf("debug : window : %ld, child : %ld class \"%s\"\n",
// aWindow,child,ClassName(child).c_str());
child = GetNextSibling(child);
}
}
*/
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
inline bool IsStyle(HWND aWindow,LONG aStyle) {
LONG_PTR style = ::GetWindowLongPtr(aWindow,GWL_STYLE);
return ( ((style & aStyle ) == aStyle) ? true : false);
}
inline void ChangeStyle(HWND aWindow,LONG aStyle,bool aValue) {
LONG_PTR style = ::GetWindowLongPtr(aWindow,GWL_STYLE);
if(aValue) { //Enable style.
style = style | aStyle;
} else { //Disbale style.
style = style & ~aStyle;
}
::SetWindowLongPtr(aWindow,GWL_STYLE,style);
}
inline bool IsShell(HWND aWindow) {
if(IsStyle(aWindow,WS_OVERLAPPEDWINDOW)) return true;
if(IsStyle(aWindow,WS_POPUP)) return true;
return false;
}
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
inline HWND GetShell(HWND aWindow) {
HWND window = aWindow;
if(IsShell(window)) return window;
while(true) {
HWND parent = GetParent(window);
if(!parent) return window;
if(IsShell(parent)) return parent;
window = parent;
}
return 0;
}
inline bool Show(HWND aWindow) {
HWND shell = GetShell(aWindow);
if(!shell) return false;
::SetForegroundWindow(shell);
::ShowWindow(shell,SW_SHOWDEFAULT);
::UpdateWindow(shell);
::DrawMenuBar(shell);
return true;
}
inline bool Hide(HWND aWindow) {
HWND shell = GetShell(aWindow);
if(!shell) return false;
::ShowWindow(shell,SW_HIDE);
return true;
}
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
inline bool IsTabStop(HWND aWindow) {
LONG_PTR style = ::GetWindowLongPtr(aWindow,GWL_STYLE);
return ((style & WS_TABSTOP ) == WS_TABSTOP ? true : false);
}
inline HWND GetTabStopInTree(HWND aWindow,bool aForward) {
if(IsTabStop(aWindow)) return aWindow;
HWND child = aForward ? GetFirstChild(aWindow) : GetLastChild(aWindow);
while(child) {
HWND tabStop = GetTabStopInTree(child,aForward);
if(tabStop) return tabStop;
child = aForward ? GetNextSibling(child) : GetPrevSibling(child);
}
return NULL;
}
inline HWND GetTabStopInSibling(HWND aWindow,bool aForward) {
if(!aWindow) return NULL;
HWND child = aForward ? GetNextSibling(aWindow) : GetPrevSibling(aWindow);
while(child) {
HWND tabStop = GetTabStopInTree(child,aForward);
if(tabStop) return tabStop;
child = aForward ? GetNextSibling(child) : GetPrevSibling(child);
}
return NULL;
}
inline HWND GetTabStop(HWND aDialog,HWND aWindow,bool aForward = true) {
if(!aWindow) return NULL;
HWND window = aWindow;
while(window && (window!=aDialog) ) {
HWND tabStop = GetTabStopInSibling(window,aForward);
if(tabStop) return tabStop;
window = GetParent(window);
}
return GetTabStopInTree(aDialog,aForward);
}
inline HBITMAP CreateDIB(HDC aDC,int aWidth,int aHeight,int aBPP /*16||24||32*/,void** aBits) {
if((aBPP!=24) && (aBPP!=32)) return 0;
BITMAPINFO format;
BITMAPINFOHEADER* header = (BITMAPINFOHEADER*)&format;
header->biSize = sizeof(BITMAPINFOHEADER);
header->biWidth = aWidth;
header->biHeight = -aHeight;
header->biPlanes = 1;
header->biBitCount = aBPP;
header->biCompression = BI_RGB;
header->biSizeImage = 0;
header->biXPelsPerMeter = 0;
header->biYPelsPerMeter = 0;
header->biClrUsed = 0;
header->biClrImportant = 0;
UINT flag = DIB_RGB_COLORS;
HBITMAP bitmap = ::CreateDIBSection(aDC,&format,flag,(void**)aBits,NULL,0);
if(!(*aBits)) return 0;
return bitmap;
}
}}
#include <commctrl.h>
namespace tools {
namespace WinTk {
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
inline bool TreeGetItemLabel(HWND aWindow,HTREEITEM aItem,std::string& a_value) {
TCHAR text[256];
TV_ITEM item;
item.hItem = aItem;
item.mask = TVIF_TEXT;
item.pszText = text;
item.cchTextMax = 256;
if(!TreeView_GetItem(aWindow,&item)) {a_value.clear();return false;}
a_value = std::string(text);
return true;
}
inline bool TreeIsItemBranch(HWND aWindow,HTREEITEM aItem) {
TV_ITEM item;
item.hItem = aItem;
item.mask = TVIF_CHILDREN;
if(!TreeView_GetItem(aWindow,&item)) return 0;
return item.cChildren?true:false;
}
inline bool TreeIsItemExpanded(HWND aWindow,HTREEITEM aItem) {
TV_ITEM item;
item.hItem = aItem;
item.mask = TVIS_EXPANDED;
if(!TreeView_GetItem(aWindow,&item)) return 0;
return ((item.state & TVIS_EXPANDED)== TVIS_EXPANDED) ? true : false;
}
inline void TreeGetItemPath(HWND aWindow,HTREEITEM aItem,std::string& a_value) {
HTREEITEM item = aItem;
a_value.clear();
std::string ss;
while(item && (item!=TVI_ROOT)) {
TreeGetItemLabel(aWindow,item,ss);
std::string opath = a_value;
a_value = "\n";
a_value += ss;
a_value += opath;
item = TreeView_GetParent(aWindow,item);
}
// Remove the leading \n
if(a_value.size()) a_value = a_value.substr(1,a_value.size()-1);
}
inline void TreeGetItemXML(HWND aWindow,HTREEITEM aItem,std::string& a_value) {
//return a XML string representing this tree
std::string spaceItem = "";
std::string spaceRoot = "";
std::string ss;
a_value.clear();
do {
a_value += spaceRoot + "<treeItem>";
a_value += spaceItem + "<label>";
TreeGetItemLabel(aWindow,aItem,ss);
a_value.append(ss);
a_value += "</label>";
a_value += spaceItem + "<opened>";
if (TreeIsItemExpanded(aWindow,aItem)) a_value.append("true");
else a_value.append("false");
a_value += "</opened>";
if (TreeView_GetChild(aWindow,aItem)) {
TreeGetItemXML(aWindow,TreeView_GetChild(aWindow,aItem),ss);
a_value += ss;
}
a_value += spaceRoot + "</treeItem>";
aItem = TreeView_GetNextSibling(aWindow,aItem);
}
while (aItem);
}
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
inline int smanip_axtoi(const std::string& a_string) {
// convert from ASCII hex to int
// Exa : "FF" -> 256.
int x = 0;
size_t n = a_string.size();
// convert n nibbles
for (size_t i = 0; i < n; i++) {
char c = a_string[i];
// numbers 0 - 9
if ((c > 0x2F) && (c < 0x3A))
x += ((c - 0x30) << ((n - i - 1) * 4));
// capital letters A - F
if ((c > 0x40) && (c < 0x47))
x += ((c - 0x41 + 0x0A) << ((n - i - 1) * 4));
// lower case letters a - f
if ((c > 0x60) && (c < 0x67))
x += ((c - 0x61 + 0x0A) << ((n - i - 1) * 4));
}
return x;
}
}}
#include <tools/svalues>
namespace tools {
namespace WinTk {
inline HBITMAP ConvertXpmToDIB(HDC aDC,const std::vector<std::string>& aXPM,int& aWidth,int& aHeight) {
// Convert from xpm to DIB (demands hex colors).
// From CoinWin/widgets/SoWinBitmapButton.cpp.
aWidth = 0;
aHeight = 0;
if(!aXPM.size()) return 0;
std::vector<int> vals;
tools::values<int>(aXPM[0]," ",false,vals);
if(vals.size()!=4) return 0;
int width = vals[0];
int height = vals[1];
int numcol = vals[2];
int numchars = vals[3];
if(width<=0) return 0;
if(height<=0) return 0;
if(numcol<=0) return 0;
if(numchars<=0) return 0;
// Check consistency :
if((height+numcol)!=aXPM.size()-1) return 0;
size_t lcolor = 0;
int i;
for (i = 0; i < numcol; i++) {
std::string::size_type pos = aXPM[i+1].rfind("c #");
if(pos==std::string::npos) continue; // May be "c None"
lcolor = aXPM[i+1].size()-(pos+3);
break;
}
//printf("debug : xpm : numcol %d (%d)\n",numcol,lcolor);
if( (lcolor!=6) && (lcolor!=12) ) return 0;
// create color lookup table
char* charlookuptable = new char[numcol * numchars];
//long* colorlookuptable = new long[numcol];
int* rlookuptable = new int[numcol];
int* glookuptable = new int[numcol];
int* blookuptable = new int[numcol];
bool done = true;
// get colors
for (i = 0; i < numcol; i++) {
const std::string& line = aXPM[i+1];
// Check consistency :
if((int)line.size()<numchars) {
done = false;
break;
}
for (int j = 0; j < numchars; j ++) {
charlookuptable[(i * numchars) + j] = line[j];
}
// Find color by value :
std::string::size_type pos = line.find("c #",numchars);
if(pos!=std::string::npos) {
size_t lc = line.size()-(pos+3);
if(lc!=lcolor) {
done = false;
//printf("debug : xpm : error in \"%s\" %d %d\n",
//line.c_str(),lc,lcolor);
break;
}
if(lcolor==6) {
rlookuptable[i] = smanip_axtoi(line.substr(pos+3+0,2));
glookuptable[i] = smanip_axtoi(line.substr(pos+3+2,2));
blookuptable[i] = smanip_axtoi(line.substr(pos+3+4,2));
} else { //lcolor 12
rlookuptable[i] = smanip_axtoi(line.substr(pos+3+0,2));
glookuptable[i] = smanip_axtoi(line.substr(pos+3+4,2));
blookuptable[i] = smanip_axtoi(line.substr(pos+3+8,2));
}
//printf("debug : xpm : color %d : (%x,%x,%x)\n",
// i,rlookuptable[i],glookuptable[i],blookuptable[i]);
} else { // Could be "c None"
rlookuptable[i] = -1;
glookuptable[i] = -1;
blookuptable[i] = -1;
}
}
//printf("debug : xpm : read color %d\n",done);
//WARNING : pixelsize 3 does not work with button in a toolbar.
// unsigned char pixelsize = 3;
unsigned char pixelsize = 4;
if(!done) pixelsize = 0; // Will induce a clean exit.
// create bitmap
void* dest;
HBITMAP hbmp = CreateDIB(aDC,width,height,pixelsize * 8,&dest);
if(hbmp) {
int noneColor = ::GetSysColor(COLOR_3DFACE);
done = true;
// put pixels
for (i = 0; i < height; i++) {
const std::string& line = aXPM[i + 1 + numcol];
// Check consistency :
if((int)line.size()!=(numchars*width)) {
done = false;
break;
}
int y = i * width * pixelsize;
for (int j = 0; j < width; j++) {
int x = j * pixelsize;
// for every color
for (int k = 0; k < numcol; k++) {
bool found = true;
for (int l = 0; l < numchars; l++) {
if (charlookuptable[(k * numchars) + l]
!= line[(j * numchars) + l]) {
found = false;
break;
}
}
if(found) {
unsigned char r,g,b;
if (rlookuptable[k] == -1) {
r = (noneColor & 0x00FF0000)>>16;
g = (noneColor & 0x0000FF00)>>8;
b = noneColor & 0x000000FF;
} else {
r = rlookuptable[k];
g = glookuptable[k];
b = blookuptable[k];
}
if(pixelsize==4) {
((unsigned char*)dest)[y + x + 0] = b;
((unsigned char*)dest)[y + x + 1] = g;
((unsigned char*)dest)[y + x + 2] = r;
((unsigned char*)dest)[y + x + 3] = 0;
} else {
((unsigned char*)dest)[y + x + 0] = b;
((unsigned char*)dest)[y + x + 1] = g;
((unsigned char*)dest)[y + x + 2] = r;
}
// next pixel
break;
}
}
}
}
if(!done) {
//printf("debug : xpm : can'tread pixels.\n");
::DeleteObject(hbmp);
hbmp = 0;
}
}
// cleanup
delete [] charlookuptable;
delete [] rlookuptable;
delete [] glookuptable;
delete [] blookuptable;
if(hbmp) {
aWidth = width;
aHeight = height;
}
return hbmp;
}
}}
#include <tools/file>
namespace tools {
namespace WinTk {
inline HBITMAP Read_Xpm(HDC aDC,const std::string& aFileName,int& aWidth,int& aHeight) {
aWidth = 0;
aHeight = 0;
std::vector<std::string> text;
//std::string name;
//tools::file_name(aFileName,name);
if(!tools::file::read(aFileName,text)) return 0;
std::vector<std::string> xpm;
{for(size_t index=0;index<text.size();index++) {
if(text[index][0]!='"') continue;
std::string::size_type l = text[index].size();
std::string line = text[index].substr(1,l-1);
std::string::size_type pos = line.find("\"");
if(pos==std::string::npos) return 0;
xpm.push_back(line.substr(0,pos));
}}
if(!xpm.size()) return 0;
return ConvertXpmToDIB(aDC,xpm,aWidth,aHeight);
}
inline std::string TreeGetItemLabel(HWND aWindow,HTREEITEM aItem) {
std::string ss;
TreeGetItemLabel(aWindow,aItem,ss);
return ss;
}
inline std::string TreeGetItemPath(HWND aWindow,HTREEITEM aItem) {
std::string ss;
TreeGetItemPath(aWindow,aItem,ss);
return ss;
}
inline std::string TreeGetItemXML(HWND aWindow,HTREEITEM aItem) {
std::string ss;
TreeGetItemXML(aWindow,aItem,ss);
return ss;
}
inline std::string GetText(HWND aWindow) {
std::string ss;
GetText(aWindow,ss);
return ss;
}
inline std::string GetClassName(HWND aWindow) {
std::string ss;
GetClassName(aWindow,ss);
return ss;
}
}}
#include <tools/file_name>
namespace tools {
namespace WinTk {
inline HBITMAP ReadXpm(HDC aDC,const std::string& aFileName,int& aWidth,int& aHeight) {
std::string name;
tools::file_name(aFileName,name);
return Read_Xpm(aDC,name,aWidth,aHeight);
}
}}
#endif
-531
View File
@@ -1,531 +0,0 @@
/*
#define DEBUG
*/
/*this*/
#include "OpenGLAreaP.h"
#include <X11/StringDefs.h>
#include <GL/glx.h>
#include <stdio.h>
#include <stdlib.h>
#ifdef __cplusplus
extern "C"{
#endif
static void InitializeClass(void);
static void InitializeWidget(Widget, Widget,ArgList,Cardinal*);
static void RealizeWidget(Widget, XtValueMask*, XSetWindowAttributes*);
static void DestroyWidget(Widget);
static void ChangeWidgetSize(Widget);
static void DrawWidget(Widget, XEvent*, Region);
static Boolean SetValues(Widget,Widget,Widget,ArgList,Cardinal *);
static void EventHandler(Widget,XtPointer,XEvent*,Boolean*);
static int MakeCurrent(Widget);
static void XWidgetInstallColormap(Widget);
static void XWidgetUninstallColormap(Widget);
static Widget XWidgetGetShell(Widget);
#ifdef __cplusplus
}
#endif
#define athis ((OpenGLAreaWidget)This)->openGLArea
#define acur ((OpenGLAreaWidget)a_current)->openGLArea
#define CWarn printf
#define CWarnF printf
static XtResource resources [] = {
{XoNdoubleBufferOn,"DoubleBufferOn",XtRBoolean,sizeof(Boolean),
XtOffset(OpenGLAreaWidget,openGLArea.doubleBufferOn),XtRImmediate,(XtPointer)True},
{XoNpaintCallback,XtCCallback,XtRCallback,sizeof(XtCallbackList),
XtOffset(OpenGLAreaWidget,openGLArea.paintCallback),XtRImmediate,(XtPointer)NULL},
{XoNeventCallback,XtCCallback,XtRCallback,sizeof(XtCallbackList),
XtOffset(OpenGLAreaWidget,openGLArea.eventCallback),XtRImmediate,(XtPointer)NULL}
};
OpenGLAreaClassRec openGLAreaClassRec = {
/* Core Class Part */
{
(WidgetClass) &compositeClassRec, /* pointer to superclass ClassRec */
"OpenGLArea", /* widget resource class name */
sizeof(OpenGLAreaRec), /* size in bytes of widget record */
InitializeClass, /* class_initialize */
NULL, /* dynamic initialization */
FALSE, /* has class been initialized? */
InitializeWidget, /* initialize */
NULL, /* notify that initialize called */
RealizeWidget, /* XCreateWindow for widget */
NULL, /* widget semantics name to proc mapWidget*/
0, /* number of entries in actions */
resources, /* resources for subclass fields */
XtNumber(resources), /* number of entries in resources */
NULLQUARK, /* resource class quarkified */
TRUE, /* compress MotionNotify for widget */
TRUE, /* compress Expose events for widget*/
TRUE, /* compress enter and leave events */
TRUE, /* select for VisibilityNotify */
DestroyWidget, /* free data for subclass pointers */
ChangeWidgetSize, /* geom manager changed widget size */
DrawWidget, /* rediplay window */
SetValues, /* set subclass resource values */
NULL, /* notify that SetValues called */
XtInheritSetValuesAlmost, /* SetValues got "Almost" geo reply*/
NULL, /* notify that get_values called */
XtInheritAcceptFocus, /* assign input focus to widget */
XtVersion, /* version of intrinsics used */
NULL, /* list of callback offsets */
XtInheritTranslations, /* translations */
XtInheritQueryGeometry, /* return preferred geometry */
XtInheritDisplayAccelerator, /* display your accelerator */
NULL /* pointer to extension record */
},
/* Composite Class Part */
{
XtInheritGeometryManager, /* geometry manager for children */
XtInheritChangeManaged, /* change managed state of child */
XtInheritInsertChild, /* physically add child to parent */
XtInheritDeleteChild, /* physically remove child */
NULL /* pointer to extension record */
},
/* OpenGLArea */
{
NULL
}
};
WidgetClass openGLAreaWidgetClass = (WidgetClass) &openGLAreaClassRec;
static void InitializeClass(void) {}
static void InitializeWidget(Widget a_request,Widget This,ArgList a_args,Cardinal* a_argn) {
if(a_request->core.width<=0) This->core.width = 100;
if(a_request->core.height<=0) This->core.height = 100;
#ifdef DEBUG
printf ("debug : OpenGLArea : InitializeWidget : %s\n",XtName(This));
#endif
athis.visual = CopyFromParent;
athis.installColormap = False;
athis.glContext = NULL;
{Display* display;
Screen* screen;
int iscreen;
XVisualInfo* vinfo;
display = XtDisplay(This);
screen = XtScreen(This);
iscreen = XScreenNumberOfScreen(screen);
{int error,event;
if(glXQueryExtension(display,&error,&event)==0) {
CWarn ("X server does not have OpenGL extensions.\n");
}}
if(athis.doubleBufferOn==True) {
int atbs[] = {
GLX_RGBA,
GLX_RED_SIZE, 1,
GLX_GREEN_SIZE, 1,
GLX_BLUE_SIZE, 1,
GLX_ALPHA_SIZE, 1,
GLX_DEPTH_SIZE, 1,
GLX_DOUBLEBUFFER,
None
};
vinfo = glXChooseVisual (display,iscreen,atbs);
if(vinfo==NULL) { /*GLX_ALPHA_SIZE : problem with Xming. Try without it.*/
int atbs[] = {
GLX_RGBA,
GLX_RED_SIZE, 1,
GLX_GREEN_SIZE, 1,
GLX_BLUE_SIZE, 1,
GLX_DEPTH_SIZE, 1,
GLX_DOUBLEBUFFER,
None
};
vinfo = glXChooseVisual (display,iscreen,atbs);
}
} else {
int atbs[] = {
GLX_RGBA,
GLX_RED_SIZE, 1,
GLX_GREEN_SIZE, 1,
GLX_BLUE_SIZE, 1,
GLX_ALPHA_SIZE, 1,
GLX_DEPTH_SIZE, 1,
None
};
vinfo = glXChooseVisual (display,iscreen,atbs);
if(vinfo==NULL) { /*GLX_ALPHA_SIZE : problem with Xming. Try without it.*/
int atbs[] = {
GLX_RGBA,
GLX_RED_SIZE, 1,
GLX_GREEN_SIZE, 1,
GLX_BLUE_SIZE, 1,
GLX_DEPTH_SIZE, 1,
None
};
vinfo = glXChooseVisual (display,iscreen,atbs);
}
}
if(vinfo==NULL) {
CWarn ("Can't choose a visual.\n");
} else {
This->core.depth = vinfo->depth;
athis.visual = vinfo->visual;
if( (vinfo->depth ==DefaultDepth (display,iscreen)) &&
(vinfo->visual==DefaultVisual(display,iscreen)) ) {
This->core.colormap = XDefaultColormap (display,iscreen);
athis.installColormap = False;
} else {
This->core.colormap =
XCreateColormap (display,XRootWindow(display,iscreen),vinfo->visual, AllocNone);
athis.installColormap = True;
}
if(This->core.colormap==0L) {
CWarn ("Can't get/create a X colormap.\n");
}
athis.glContext = glXCreateContext (display,vinfo,NULL,GL_FALSE);
if(athis.glContext==NULL) {
CWarn ("Can't create a GLX context.\n");
}
XFree(vinfo);
}}
XtAddEventHandler(This,ButtonPressMask|ButtonReleaseMask|ButtonMotionMask,0,EventHandler,NULL);
#ifdef DEBUG
printf("debug : OpenGLArea : InitializeWidget : end\n");
#endif
/*avoid C++ warnings*/
a_request = NULL;
a_args = NULL;
a_argn = 0;
}
static void RealizeWidget(Widget This,XtValueMask* a_mask,XSetWindowAttributes* a_watbs) {
#ifdef DEBUG
printf("debug : OpenGLArea : RealizeWidget : %s\n",XtName(This));
#endif
/*Have to create window ourselves due to OpenGL that compells it's visual.*/
/*In principle colormap is correctly set in a_watbs.*/
XtCreateWindow(This,(unsigned int)InputOutput,athis.visual,*a_mask,a_watbs);
/* Call the Realize procedure (XtInheritRealize) */
if(openGLAreaWidgetClass->core_class.superclass->core_class.realize!=NULL)
(openGLAreaWidgetClass->core_class.superclass->core_class.realize)(This, a_mask, a_watbs);
/*If window is delete, all seems ok.*/
if(athis.installColormap==True) XWidgetInstallColormap(This);
/*MakeCurrent(This);*/
#ifdef DEBUG
printf("debug : OpenGLArea : RealizeWidget : end\n");
#endif
}
static void DestroyWidget(Widget This) {
if(athis.installColormap==True) {
XWidgetUninstallColormap (This);
athis.installColormap = False;
XFreeColormap(XtDisplay(This),This->core.colormap);
}
if(athis.glContext!=NULL) {
glXMakeCurrent(XtDisplay(This),None,NULL);
glXDestroyContext(XtDisplay(This),athis.glContext);
athis.glContext = NULL;
}
}
#define IFMOD(a_field) if(athis.a_field != acur.a_field)
static Boolean SetValues(Widget a_current,Widget a_request,Widget This,ArgList a_args,Cardinal* a_argn) {
IFMOD(doubleBufferOn) {
/* Can't change buffering here if X window is created.
With OpenGL, buffering fix parameter of the X window.
Buffering must be choosen before the execution of the
Realize method that create the window. */
if(XtIsRealized(This) && (athis.installColormap==True)) {
CWarn("Can't change buffering after \"realization\" of the widget.\n");
athis.doubleBufferOn = acur.doubleBufferOn;
}
}
/*avoid C++ warnings*/
a_request = NULL;
a_args = NULL;
a_argn = 0;
return False;
}
static void ChangeWidgetSize(Widget This) {
#ifdef DEBUG
printf("debug : OpenGLArea : ChangeWidgetSize : %s\n",XtName(This));
#endif
/* Call the Resize procedure (XtInheritResize) */
if(openGLAreaWidgetClass->core_class.superclass->core_class.resize!=NULL)
(openGLAreaWidgetClass->core_class.superclass->core_class.resize)(This);
#ifdef DEBUG
printf("debug : OpenGLArea : ChangeWidgetSize : end\n");
#endif
}
static void DrawWidget(Widget This,XEvent* a_event,Region a_region) {
#ifdef DEBUG
printf("debug : OpenGLArea : DrawWidget : %s\n",XtName(This));
#endif
if(openGLAreaWidgetClass->core_class.superclass->core_class.expose!=NULL)
(openGLAreaWidgetClass->core_class.superclass->core_class.expose)(This,a_event,a_region);
if(MakeCurrent(This)==1) {
#ifdef DEBUG
printf("debug : OpenGLArea : DrawWidget : %s : MakeCurrent ok : call paintCallback...\n",XtName(This));
#endif
XoAnyCallbackStruct value;
value.reason = XoCR_PAINT;
value.event = a_event;
XtCallCallbacks(This,XoNpaintCallback,(XtPointer)&value);
glXSwapBuffers(XtDisplay(This),XtWindow(This));
glXMakeCurrent(XtDisplay(This),None,NULL);
}
#ifdef DEBUG
printf("debug : OpenGLArea : DrawWidget : end\n");
#endif
/*avoid C++ warnings*/
a_event = NULL;
a_region = NULL;
}
/*------------------------------------------------------------------------*/
/*------------------------------------------------------------------------*/
/*------------------------------------------------------------------------*/
void OpenGLAreaPaint(Widget This) {
if(!XtIsRealized(This)) return;
if(MakeCurrent(This)==1) {
XoAnyCallbackStruct value;
value.reason = XoCR_PAINT;
value.event = 0;
XtCallCallbacks(This,XoNpaintCallback,(XtPointer)&value);
glXSwapBuffers(XtDisplay(This),XtWindow(This));
glXMakeCurrent(XtDisplay(This),None,NULL);
}
}
#ifdef TOOLS_XT_OPENGLAREA_HAS_GL2PS
#include <tools/c_gl2ps.h>
int OpenGLAreaWrite_gl2ps(Widget This,const char* aFileName,const char* opts) {
FILE* file;
int options;
int sort;
inlib_GLint vp[4];
int bufsize = 0;
static inlib_gl2ps_gl_funcs_t s_OpenGL_funcs = {
glIsEnabled,
glBegin,
glEnd,
glGetFloatv,
glVertex3f,
glGetBooleanv,
glGetIntegerv,
glRenderMode,
glFeedbackBuffer,
glPassThrough
};
file = fopen(aFileName,"w");
if(!file) return 1;
inlib_c_gl2ps_set_gl_funcs(&s_OpenGL_funcs);
options = TOOLS_GL2PS_OCCLUSION_CULL
| TOOLS_GL2PS_BEST_ROOT
| TOOLS_GL2PS_SILENT
| TOOLS_GL2PS_DRAW_BACKGROUND;
sort = TOOLS_GL2PS_BSP_SORT;
//sort = TOOLS_GL2PS_SIMPLE_SORT;
vp[0] = 0;
vp[1] = 0;
vp[2] = This->core.width;
vp[3] = This->core.height;
inlib_c_gl2psBeginPage("title","exlib_Xt_OpenGLArea",
vp,TOOLS_GL2PS_EPS,sort,options,
TOOLS_GL_RGBA,0, NULL,0,0,0,bufsize,
file,aFileName);
{XoAnyCallbackStruct value;
value.reason = XoCR_PAINT;
value.event = 0;
XtCallCallbacks(This,XoNpaintCallback,(XtPointer)&value);}
inlib_c_gl2psEndPage();
inlib_c_gl2ps_reset_gl_funcs();
fclose(file);
return 0;
}
#else
#ifdef __cplusplus
int OpenGLAreaWrite_gl2ps(Widget,const char*,const char*) {return 1;}
#else
int OpenGLAreaWrite_gl2ps(Widget w,const char* f,const char* o) {return 1;}
#endif
#endif
/*------------------------------------------------------------------------*/
/*------------------------------------------------------------------------*/
/*------------------------------------------------------------------------*/
/*------------------------------------------------------------------------*/
static int MakeCurrent(Widget This) {
if(This==NULL) return 0;
if(!XtIsRealized(This)) return 0;
if(athis.glContext==NULL) return 0;
return (int)glXMakeCurrent(XtDisplay(This),XtWindow(This),athis.glContext);
}
static void EventHandler(Widget This,XtPointer a_tag,XEvent* a_event ,Boolean* a_continue) {
XoAnyCallbackStruct value;
value.reason = XoCR_EVENT;
value.event = a_event;
XtCallCallbacks(This,XoNeventCallback,(XtPointer)&value);
a_tag = NULL;
a_continue = NULL;
}
/*------------------------------------------------------------------------*/
/*------------------------------------------------------------------------*/
/*------------------------------------------------------------------------*/
static void XWidgetInstallColormap(Widget This) {
/*
From Mesa/widgets/GLwDrawingArea.c/post_colormap routine.
Could use also XtSetWMColormapWindows.
*/
Display* display;
XWindowAttributes watbs;
Widget shell;
Window* ws = NULL;
int wn = 0,found,count;
Window wshell,wthis;
Colormap cmapthis;
/*.........................................................................*/
if(This==NULL) return;
if( !XtIsWidget(This) || !XtIsRealized(This) ) return;
shell = XWidgetGetShell (This);
if(shell==NULL) return;
display = XtDisplay (This);
wthis = XtWindow (This);
wshell = XtWindow (shell);
XGetWMColormapWindows (display,wshell, &ws, &wn);
/* Check if colormap of this is a colormap of a Window in list.*/
XGetWindowAttributes (display,wthis,&watbs);
cmapthis = watbs.colormap;
found = -1;
for(count=0;count<wn;count++) {
Colormap cmap;
XGetWindowAttributes (display,ws[count],&watbs);
cmap = watbs.colormap;
if(cmap==cmapthis) {
XFree (ws);
return; /*done*/
}
if(ws[count]==wshell) {
found = count;
}
}
/*Have to add window of this in list.*/
if(wn==0) {
if(ws!=NULL) XFree(ws);
ws = (Window*)malloc ( 2 * sizeof(Window));
} else {
ws = (Window*)realloc (ws,(wn + 2) * sizeof(Window));
}
if(ws==NULL) return;
if(found==-1) {
/*Window of shell not in list.*/
ws[wn] = wthis; wn++;
ws[wn] = wshell;wn++;
} else {
ws[found] = wthis;
ws[wn] = wshell; wn++; /*Shell must be last.*/
}
if (XSetWMColormapWindows(display,wshell, ws, wn)==0) {
CWarnF ("XWidgetInstallColormap: can't install colormap of %s in %s.\n",XtName(This),XtName(shell));
}
XFree (ws);
}
static void XWidgetUninstallColormap(Widget This) {
int count;
Widget shell;
Display* display;
Window wthis,wshell;
Window* ws = NULL;
int wn = 0;
Window* nws = NULL;
int nwn = 0;
/*.........................................................................*/
if(This==NULL) return;
if( !XtIsWidget(This) || !XtIsRealized(This) ) return;
shell = XWidgetGetShell (This);
if(shell==NULL) return;
display = XtDisplay (This);
wthis = XtWindow (This);
wshell = XtWindow (shell);
XGetWMColormapWindows (display,wshell, &ws, &wn);
if( (wn==0) || (ws==NULL) ) return;
nws = (Window*)malloc ( wn * sizeof(Window));
if(nws==NULL) {
XFree (ws);
return;
}
nwn = 0;
for(count=0;count<wn;count++) {
if(ws[count]!=wthis) {
nws[nwn] = ws[count];
nwn++;
}
}
if(wn!=nwn) {
if (XSetWMColormapWindows(display,wshell, nws, nwn)==0) {
CWarnF("XWidgetUninstallColormap: can't install colormap of %s in %s.\n",XtName(This),XtName(shell));
}
}
XFree (ws);
XFree (nws);
}
Widget XWidgetGetShell(Widget This) {
Widget widget;
if(This==NULL) return NULL;
widget = This;
while(1) {
if(widget==NULL) return NULL;
if(XtIsShell(widget)) return widget;
widget = XtParent(widget);
}
}
/*
exlib_build_use Xt inlib
*/
-37
View File
@@ -1,37 +0,0 @@
#ifndef tools_Xt_OpenGLArea_h
#define tools_Xt_OpenGLArea_h
#include <X11/Intrinsic.h>
typedef struct _OpenGLAreaClassRec* OpenGLAreaWidgetClass;
typedef struct _OpenGLAreaRec* OpenGLAreaWidget;
typedef struct {
int reason;
XEvent* event;
} XoAnyCallbackStruct;
/* OpenGLArea */
#define XoNdoubleBufferOn "doubleBufferOn"
#define XoNpaintCallback "paintCallback"
#define XoNeventCallback "eventCallback"
#define XoCR_PAINT 1
#define XoCR_EVENT 2
#ifdef __cplusplus
extern "C"{
#endif
extern WidgetClass openGLAreaWidgetClass;
void OpenGLAreaPaint(Widget);
int OpenGLAreaWrite_gl2ps(Widget,const char*,const char*);
#ifdef __cplusplus
}
#endif
#endif
/*
exlib_build_use Xt
*/
-54
View File
@@ -1,54 +0,0 @@
#ifndef tools_Xt_OpenGLAreaP_h
#define tools_Xt_OpenGLAreaP_h
#include "OpenGLArea.h"
#include <X11/IntrinsicP.h>
#include <X11/CoreP.h>
#include <X11/CompositeP.h>
#include <GL/glx.h>
typedef struct
{
void* extension;
} OpenGLAreaClassPart;
typedef struct _OpenGLAreaClassRec
{
CoreClassPart core_class;
CompositeClassPart composite_class;
OpenGLAreaClassPart openGLArea_class;
} OpenGLAreaClassRec;
#ifdef __cplusplus
extern "C"{
#endif
extern OpenGLAreaClassRec openGLAreaClassRec;
#ifdef __cplusplus
}
#endif
typedef struct
{
/*Resources :*/
Boolean doubleBufferOn;
XtCallbackList paintCallback;
XtCallbackList eventCallback;
/**/
Visual* visual;
Boolean installColormap;
GLXContext glContext;
} OpenGLAreaPart;
typedef struct _OpenGLAreaRec
{
CorePart core;
CompositePart composite;
OpenGLAreaPart openGLArea;
} OpenGLAreaRec;
#endif
/*
exlib_build_use Xt
*/
-204
View File
@@ -1,204 +0,0 @@
// Copyright (C) 2010, Guy Barrand. All rights reserved.
// See the file tools.license for terms.
#ifndef tools_Xt_tools
#define tools_Xt_tools
#include <X11/Intrinsic.h>
#include <X11/StringDefs.h>
#include <string>
inline Widget XWidgetGetShell(Widget aWidget){
Widget widget = aWidget;
while(1) {
if(!widget) return 0;
if(XtIsShell(widget)) return widget;
widget = XtParent(widget);
}
}
inline Pixel XWidgetGetPixelResource(Widget aWidget,const std::string& aName){
Pixel pixel = 0L;
Arg args[1];
XtSetArg(args[0],(char*)aName.c_str(),&pixel);
XtGetValues(aWidget,args,1);
return pixel;
}
inline Pixel XWidgetConvertStringToPixel(Widget aWidget,const std::string& aString){
if(aString.empty()) return 0L;
if( (aString=="None") || (aString=="none") )
return XWidgetGetPixelResource(aWidget,std::string(XtNbackground));
XrmValue from,to;
from.size = aString.size()+1;
from.addr = (XPointer)aString.c_str();
XtConvert(aWidget,XtRString,&from,XtRPixel,&to);
if(to.addr==NULL) return 0L;
return (*((Pixel*)to.addr));
}
inline void XWidgetSetString(Widget aWidget,const std::string& aName,const std::string& aValue,bool aFreePrevious = false){
if(aFreePrevious) {
char* s = NULL;
Arg args[1];
XtSetArg(args[0],(char*)aName.c_str(),&s);
XtGetValues(aWidget,args,1);
if(s!=NULL) XtFree(s);
}
Arg args[1];
XtSetArg(args[0],(char*)aName.c_str(),XtNewString(aValue.c_str()));
XtSetValues(aWidget,args,1);
}
inline bool XWidgetGetString(Widget aWidget,const std::string& aName,std::string& a_value){
// XtNgeometry, XtNtitle.
char* s = NULL;
Arg args[1];
XtSetArg(args[0],(char*)aName.c_str(),&s);
XtGetValues(aWidget,args,1);
if(s==NULL) {a_value.clear();return false;}
a_value = std::string(s);
return true;
}
#include <X11/Xatom.h>
inline bool XWidgetSendMessage(Widget aWidget,long a_1,long a_2) {
XClientMessageEvent event;
if(!XtIsRealized(aWidget)) return 0;
event.type = ClientMessage;
event.display = XtDisplay(aWidget);
event.window = XtWindow(aWidget);
event.message_type = XA_INTEGER;
event.format = 8;
event.data.l[0] = a_1;
event.data.l[1] = a_2;
event.data.l[2] = 0L;
event.data.l[3] = 0L;
event.data.l[4] = 0L;
if(XSendEvent(event.display,event.window,False,0L,(XEvent*)&event)==0)
return false;
XFlush(event.display);
return true;
}
#include <X11/IntrinsicP.h>
inline void XClassGetName(WidgetClass aClass,std::string& a_value){
a_value = std::string((char*)aClass->core_class.class_name);
}
inline Boolean XClassIsSubclass(WidgetClass aClass,WidgetClass aParent){
for (WidgetClass wc = aClass; wc != NULL; wc = wc->core_class.superclass)
if (wc == aParent) return True;
return False;
}
inline Position XWidgetGetX(Widget aWidget){return aWidget->core.x;}
inline Position XWidgetGetY(Widget aWidget){return aWidget->core.y;}
inline Dimension XWidgetGetWidth(Widget aWidget){return aWidget->core.width;}
inline Dimension XWidgetGetHeight(Widget aWidget){return aWidget->core.height;}
inline void XWidgetGetClassName(Widget aWidget,std::string& a_value) {
WidgetClass wc = XtClass(aWidget);
a_value = std::string((char*)wc->core_class.class_name);
}
inline void XWidgetCompellResize(Widget aWidget){
if(aWidget->core.widget_class->core_class.resize==NULL) return;
(aWidget->core.widget_class->core_class.resize)(aWidget);
}
#include <X11/CompositeP.h>
inline int XWidgetGetChildrenNumber(Widget aWidget){
if(!XtIsComposite(aWidget)) return 0;
CompositePart* cwp = &(((CompositeWidget)aWidget)->composite);
return cwp->num_children;
}
inline Widget XWidgetGetChild(Widget aWidget,unsigned int aIndex){
if(!XtIsComposite(aWidget)) return 0;
CompositePart* cwp = &(((CompositeWidget)aWidget)->composite);
if(aIndex>=cwp->num_children) return 0;
return cwp->children[aIndex];
}
inline Widget XWidgetGetFirstChild(Widget aWidget){
if(!XtIsComposite(aWidget)) return 0;
CompositePart* cwp = &(((CompositeWidget)aWidget)->composite);
return (cwp->num_children?cwp->children[0]:0);
}
#include <vector>
inline void XWidgetGetChildren(Widget aWidget,std::vector<Widget>& aList){
aList.clear();
if(!XtIsComposite(aWidget)) return;
CompositePart* cwp = &(((CompositeWidget)aWidget)->composite);
for (unsigned int count=0;count<cwp->num_children;count++)
aList.push_back(cwp->children[count]);
}
inline void XWidgetGetPopupChildren(Widget aWidget,std::vector<Widget>& aList){
aList.clear();
if(!XtIsWidget(aWidget)) return;
for(int count=0;count<aWidget->core.num_popups;count++) {
aList.push_back(aWidget->core.popup_list[count]);
}
}
inline Widget XWidgetFindChild(Widget aWidget,const std::string& aName){
if(!XtIsComposite(aWidget)) return 0;
CompositePart* cwp = &(((CompositeWidget)aWidget)->composite);
for (unsigned int count=0;count<cwp->num_children;count++) {
if(aName==std::string(XtName(cwp->children[count])))
return cwp->children[count];
}
return 0;
}
#include <ostream>
inline void XWidgetPrintChildren(Widget aWidget,std::ostream& a_out){
int number = XWidgetGetChildrenNumber(aWidget);
a_out << "XWidgetPrintChildren :"
<< " " << (unsigned long)aWidget
<< " number " << number
<< std::endl;
std::string scls;
for(int index=0;index<number;index++) {
Widget child = XWidgetGetChild(aWidget,index);
XWidgetGetClassName(child,scls);
a_out << " index = " << index
<< ", child = " << (unsigned long)child
<< ", class = " << scls
<< std::endl;
}
}
inline void XWidgetDumpPopupChildren(Widget aWidget,std::ostream& a_out){
a_out << "XWidgetDumpPopupChildren :"
<< " " << std::string(XtName(aWidget))
<< std::endl;
if(!XtIsWidget(aWidget)) return;
a_out << " " << aWidget->core.num_popups << " popup children." << std::endl;
std::string scls;
for (unsigned int count=0;count<aWidget->core.num_popups;count++) {
Widget w = aWidget->core.popup_list[count];
XWidgetGetClassName(w,scls);
a_out << " " << count
<< " child class " << scls
<< " name " << std::string(XtName(w))
<< std::endl;
}
}
inline void XWidgetDumpChildren(Widget aWidget,std::ostream& a_out){
a_out << "XWidgetDumpChildren :"
<< " " << std::string(XtName(aWidget))
<< std::endl;
if(!XtIsComposite(aWidget)) return;
CompositePart* cwp = &(((CompositeWidget)aWidget)->composite);
a_out << " " << cwp->num_children << " children." << std::endl;
std::string scls;
for (unsigned int count=0;count<cwp->num_children;count++) {
Widget w = cwp->children[count];
XWidgetGetClassName(w,scls);
a_out << " " << count
<< " child class " << scls
<< " name " << std::string(XtName(w))
<< std::endl;
}
}
#endif
-191
View File
@@ -1,191 +0,0 @@
// Copyright (C) 2010, Guy Barrand. All rights reserved.
// See the file tools.license for terms.
#ifndef tools_app
#define tools_app
#include "path_env"
#include "sout"
#include "file"
#include "forit"
#include "sys/dir"
namespace tools {
#ifdef __APPLE__
inline bool is_mac_app(const std::string& a_arg0){
if(a_arg0.empty()) return false;
std::string bname = base_name(dir_name(a_arg0));
if(bname=="MacOS") return true;
return false;
}
#else
inline bool is_mac_app(const std::string&){return false;}
#endif
inline bool program_path(const std::string& a_arg0,std::string& a_path) {
if(a_arg0.empty()) {
a_path = "";
return false;
}
std::string path,name,suffix;
path_name_suffix(a_arg0,path,name,suffix);
if(path.empty()) {
std::string PATH;
if(get_env("PATH",PATH)) {
std::string program = a_arg0;
#ifdef _WIN32
if(program.find(".exe")==std::string::npos) program += ".exe";
#endif
std::vector<std::string> paths;
words(PATH,psep(),false,paths);
tools_vforit(std::string,paths,it) {
std::string dir = *it;
if(file::exists(dir+sep()+program)) {
path = dir;
break;
}
}
}
}
if(path.empty()) {
a_path = "";
return false;
}
if(!is_absolute_path(path)) {
std::string pwd;
if(!dir::pwd(pwd)) {
a_path = "";
return false;
}
path = pwd+sep()+path;
}
//printf("debug : path : %s\n",path.c_str());
a_path = path;
return true;
}
inline bool if_mouse_startup(const std::string& a_arg0,const std::string& a_env_HOME_DIR,const std::vector<std::string>& a_home_dirs,std::ostream& a_out){
std::string exe_dir = dir_name(a_arg0);
std::string bname = base_name(exe_dir);
if(bname=="MacOS") {
// cd in a_doc_dir :
if(!dir::cd_home()) {
a_out << "if_mouse_startup : can't go home." << std::endl;
return false;
}
tools_vforcit(std::string,a_home_dirs,it) {
if(!dir::mkcd(*it)) {
a_out << "if_mouse_startup :"
<< " can't mkcd " << sout(*it)
<< std::endl;
return false;
}
}
// set a_env_HOME_DIR from exe_dir :
std::string Contents_dir = dir_name(exe_dir);
if(!put_env(a_env_HOME_DIR,Contents_dir)) {
a_out << "if_mouse_startup :"
<< " can't putenv " << a_env_HOME_DIR
<< " to " << sout(Contents_dir)
<< "."
<< std::endl;
return false;
}
{std::vector<std::string> vals;
vals.push_back(Contents_dir+"/bin");
vals.push_back("."); // for on-the-fly compilation and loading :
if(!env_path_append("DYLD_LIBRARY_PATH",vals)) {
a_out << "if_mouse_startup :"
<< " can't putenv DYLD_LIBRARY_PATH."
//<< " to " << sout(DYLD_LIBRARY_PATH)
<< std::endl;
return false;
}}
// {std::string DYLD_LIBRARY_PATH;
// if(!get_env("DYLD_LIBRARY_PATH",DYLD_LIBRARY_PATH)) {}
// a_out << "debug : DYLD_LIBRARY_PATH = " << sout(DYLD_LIBRARY_PATH) << std::endl;}
if(!is_env("DISPLAY")) {
if(!put_env("DISPLAY",":0.0")) return false;
}
} else if(bname=="bin") {
//Linux, Windows : mouse startup ?
/* FIXME : do we want to treat the case of a terminal startup
whence the user did not <source setup> ???
If so if_mouse_startup should be renamed no_env_startup.
} else if(exe_dir=="") { //for exa when typing "osc-plot".
if(!program_path(a_arg0,exe_dir)) {
a_out << "if_mouse_startup :"
<< " program_path failed for " << sout(bname) << "."
<< std::endl;
return false;
}
a_out << "if_mouse_startup :"
<< " program_path is " << sout(exe_dir) << "."
<< std::endl;
#if defined(__APPLE__) || defined(Linux)
bool is_abs,is_win;
std::string drive;
std::vector<std::string> words;
path_words(exe_dir,words,is_abs,is_win,drive);
std::vector<std::string>::size_type n = words.size();
if( (n>=3) &&
(words[n-1]=="bin") &&
is_version(words[n-2]) &&
(words[n-3].substr(0,4)=="osc_")
){
std::string osc_vers_dir = dir_name(exe_dir);
printf("debug : auto env 000 \"%s\"\n",osc_vers_dir.c_str());
//if(a_env_HOME_DIR.size()) {
if(!put_env(a_env_HOME_DIR,osc_vers_dir)) {
a_out << "arg0_setenv :"
<< " can't putenv " << a_env_HOME_DIR
<< " to " << sout(osc_vers_dir)
<< "."
<< std::endl;
return false;
}
//}
#ifdef __APPLE__
{std::vector<std::string> vals;
vals.push_back(osc_vers_dir+"/bin");
vals.push_back(osc_vers_dir+"/lib");
vals.push_back("."); // for on-the-fly compilation and loading :
if(!env_path_append("DYLD_LIBRARY_PATH",vals)) return false;}
#else
#endif
if(!is_env("DISPLAY")) {
if(!put_env("DISPLAY",":0.0")) return false;
}
}
#endif
*/
}
return true;
}
inline void app_res_dir(const std::string& a_exe_path,std::string& a_res_dir) {
a_res_dir = a_exe_path+sep()+".."+sep()+"res";
}
}
#endif
-31
View File
@@ -1,31 +0,0 @@
// Copyright (C) 2010, Guy Barrand. All rights reserved.
// See the file tools.license for terms.
#ifndef tools_cmp
#define tools_cmp
#include <ostream>
namespace tools {
template <class T>
inline bool cmp(std::ostream& a_out,
const T& a_what,
const T& a_ref,const T& a_error = T()) {
if(a_what>a_ref) {
if((a_what-a_ref)>a_error) {
a_out << a_ref << " expected. Got " << a_what << std::endl;
return false;
}
} else {
if((a_ref-a_what)>a_error) {
a_out << a_ref << " expected. Got " << a_what << std::endl;
return false;
}
}
return true;
}
}
#endif
-74
View File
@@ -1,74 +0,0 @@
// Copyright (C) 2010, Guy Barrand. All rights reserved.
// See the file tools.license for terms.
#ifndef tools_file_name
#define tools_file_name
#include "srep"
#include <cstdlib>
namespace tools {
// OpenPAW, Panoramix :
inline bool rep_env(std::string& a_string) {
char spec_char = '\n';
std::string::size_type dollar;
while((dollar=a_string.find('$'))!=std::string::npos){
std::string::size_type slash = a_string.find('/',dollar+1);
std::string::size_type back_slash = a_string.find('\\',dollar+1);
std::string::size_type pos = std::string::npos;
if(slash!=std::string::npos) {
if(back_slash!=std::string::npos) {
pos = slash<back_slash?slash:back_slash;
} else {
pos = slash;
}
} else {
if(back_slash!=std::string::npos) {
pos = back_slash;
} else {
pos = std::string::npos;
}
}
std::string env;
if(pos==std::string::npos) {
env = a_string.substr(dollar+1,a_string.length()-(dollar+1));
} else {
// abc$xxx/ef
// 0 3 7 9
env = a_string.substr(dollar+1,pos-(dollar+1));
}
char* val = ::getenv(env.c_str());
if(!val) {
// We may have $ in a_string not attached to an env variable.
// For example at LAL, some Windows account name have a leading $
// that is found back in the home directory path. To bypass this
// problem we change temporarily the $ by spec_char and continue
// the loop. We change back all the spec_chars to $ at end.
a_string[dollar] = spec_char;
} else {
std::string value = a_string.substr(0,dollar);
value += val;
if(pos!=std::string::npos) value += a_string.substr(pos,a_string.length()-pos);
a_string = value;
}
}
replace(a_string,spec_char,'$');
return true;
}
inline bool file_name(const std::string& a_path,std::string& a_name) {
//used in osc packages and a tools::xml::parser::load_file() compatible for OnX.
a_name = a_path;
if(!rep_env(a_name)) {a_name.clear();return false;}
#ifdef _WIN32
replace(a_name,"/","\\");
replace(a_name,"\"","");
#endif
return true;
}
}
#endif
+174
View File
@@ -0,0 +1,174 @@
/*COPYRIGHT:
Copyright (c) 2010-2015, Łukasz Dziedzic (dziedzic@typoland.com),
with Reserved Font Name Lato.
This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at:
http://scripts.sil.org/OFL
-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------
PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.
The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).
"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.
"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.
PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:
1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.
5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.
TERMINATION
This license becomes null and void if any of the above conditions are
not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.
*/
/*README:
Lato font family (Desktop version)
==================================
Version 2.015; Latin+Cyrillic+Greek+IPA opensource
Created by: tyPoland Lukasz Dziedzic
Creation year: 2015
Copyright (c) 2010-2015 by tyPoland Lukasz Dziedzic with Reserved Font Name "Lato". Licensed under the SIL Open Font License, Version 1.1.
Lato is a trademark of tyPoland Lukasz Dziedzic.
Source URL: http://www.latofonts.com/
License URL: http://scripts.sil.org/OFL
================
Lato is a sanserif typeface family designed in the Summer 2010 and extended in the Summer 2013 by Warsaw-based designer Lukasz Dziedzic ("Lato" means "Summer" in Polish). It tries to carefully balance some potentially conflicting priorities: it should seem quite "transparent" when used in body text but would display some original traits when used in larger sizes. The classical proportions, particularly visible in the uppercase, give the letterforms familiar harmony and elegance. At the same time, its sleek sanserif look makes evident the fact that Lato was designed in the 2010s, even though it does not follow any current trend. The semi-rounded details of the letters give Lato a feeling of warmth, while the strong structure provides stability and seriousness. In 2013-2014, the family was greatly extended (with the help of Adam Twardoch and Botio Nikoltchev) to cover 3000+ glyphs over nine weights with italics. It now supports 100+ Latin-based languages, 50+ Cyrillic-based languages as well as Greek and IPA phonetics. The Lato fonts are available free of charge under the SIL Open Font License from http://www.latofonts.com/
================
CONTENTS:
This folder contains 18 font files in OpenType TT (.ttf) format. You can install these fonts on your computer and use in any desktop applications (such as Word, InDesign, Illustrator, Photoshop, Keynote or Pages).
================
REVISION LOG:
# Version 2.015 (2015-08-06)
Initial implementation of mark positioning (should work for most glyphs)
Autohinted using ttfautohint 1.3.
# Version 2.010 (2014-09-01)
Improved some contour bugs and diacritics positioning.
Improved outline quality.
Revised OTL features so that they work in browsers (ot-sanitise).
Autohinted using ttfautohint 1.1.
Interpolated the Medium weight differently so it provides more visual difference from Regular.
# Version 2.007 (2014-02-27)
Greatly expanded character set, revised metrics, four additional weights.
# Version 1.104 (2011-11-08)
Merged the distribution again
Autohinted with updated ttfautohint 0.4 (which no longer causes Adobe and iOS problems)
except the Hai and Lig weights which are hinted in FLS 5.1.
# Version 1.102 (2011-10-28)
Added OpenType Layout features
Ssplit between desktop and web versions
Desktop version: all weights autohinted with FontLab Studio
Web version autohinted with ttfautohint 0.4 except the Hai and Lig weights
# Version 1.101 (2011-09-30)
Fixed OS/2 table Unicode and codepage entries
# Version 1.100 (2011-09-12)
Added Polish diacritics to the character set
Weights Hai and Lig autohinted with FontLab Studio
Other weights autohinted with ttfautohint 0.3
# Version 1.011 (2010-12-29)
Added the soft hyphen glyph
# Version 1.010 (2010-12-13)
Initial version released under SIL Open Font License
Western character set
================
*/
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,205 @@
/*LICENSE:
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
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.
*/
+208 -191
View File
@@ -42,6 +42,7 @@ public:
};
public:
template <class T>
class column_ref : public virtual icol {
#ifdef TOOLS_MEM
@@ -266,12 +267,8 @@ public:
TOOLS_CLASS_STRING_VALUE(vector_uint32,vector<tools::uint32>)
TOOLS_CLASS_STRING_VALUE(vector_uint64,vector<tools::uint64>)
//
#define TOOLS_HDF5_NTUPLE_VLEN
//
#define TOOLS_HDF5_NTUPLE_STRING
TOOLS_CLASS_STRING_VALUE(vector_string,vector<std::string>)
#ifdef TOOLS_HDF5_NTUPLE_VLEN
template <class T>
class std_vector_column_ref : public virtual icol {
#ifdef TOOLS_MEM
@@ -351,96 +348,6 @@ public:
std::string m_name;
std::vector<T>& m_ref;
};
#else //!TOOLS_HDF5_NTUPLE_VLEN
template <class T>
class std_vector_column_ref : public column<unsigned int> {
typedef column<unsigned int> parent;
#ifdef TOOLS_MEM
static const std::string& s_class() {
static const std::string s_v("tools::hdf5::ntuple::std_vector_column_ref<"+tools::stype(T())+">");
return s_v;
}
#endif
public:
static tools::cid id_class() {return tools::_cid_std_vector<T>()+10000;}
virtual void* cast(tools::cid a_class) const {
if(void* p = tools::cmp_cast<std_vector_column_ref>(this,a_class)) {return p;}
else return 0;
}
virtual tools::cid id_cls() const {return id_class();}
public: //icol
virtual void reset() {
m_branch.reset_pos();
m_data_pages.reset_pos();
}
virtual bool add() { //write.
if(!m_write) return false;
if(m_ref.size()) {
const T* _data = tools::vec_data(m_ref);
if(!m_data_pages.write_page<T>(m_ref.size(),_data)) return false;
}
if(!parent::fill((unsigned int)m_ref.size())) return false;
if(!parent::add()) return false;
return true;
}
virtual bool fetch_entry() { //read.
if(m_write) return false;
if(!parent::fetch_entry()) return false;
unsigned int sz;
if(!parent::get_entry(sz)) return false;
m_ref.resize(sz,T());
if(sz) {
T* _data = tools::vec_data(m_ref);
if(!m_data_pages.read_page<T>(sz,_data)) {m_ref.clear();return false;}
}
return true;
}
virtual const std::string& name() const {return m_name;}
virtual bool set_basket_size(size_t /*a_size*/) {
//m_branch->set_basket_size(a_size);
return true;
}
public:
std_vector_column_ref(store& a_store,pages& a_pages,bool a_write,
const std::string& a_name,size_t a_basket_size,
std::vector<T>& a_ref)
:parent(a_store,a_pages,a_write,a_name,a_basket_size)
,m_ref(a_ref)
,m_data_pages(a_store.out(),a_store.group(),a_name+"_data",tools::stype(T()),a_write,a_store.compress_level())
{
#ifdef TOOLS_MEM
tools::mem::increment(s_class().c_str());
#endif
if(!m_data_pages.is_valid()) {
m_store.out() << "tools::hdf5::std_vector_column_ref::std_vector_column_ref :"
<< " can't create data pages." << std::endl;
}
}
virtual ~std_vector_column_ref(){
#ifdef TOOLS_MEM
tools::mem::decrement(s_class().c_str());
#endif
}
protected:
std_vector_column_ref(const std_vector_column_ref& a_from)
:icol(a_from)
,parent(a_from)
,m_ref(a_from.m_ref)
,m_data_pages(a_from.m_store.out(),a_from.m_store.group(),a_from.m_name+"_data",
tools::stype(T()),a_from.m_write,a_from.m_store.compress_level())
{}
std_vector_column_ref& operator=(const std_vector_column_ref& a_from){
if(&a_from==this) return *this;
m_name = a_from.m_name;
return *this;
}
public:
//const std::vector<T>& ref() const {return m_ref;}
protected:
std::vector<T>& m_ref;
pages m_data_pages;
};
#endif //TOOLS_HDF5_NTUPLE_VLEN
template <class T>
class std_vector_column : public std_vector_column_ref<T> {
@@ -473,16 +380,11 @@ public:
return *this;
}
public:
//bool get_entry(std::vector<T>& a_v) const {
// a_v = m_tmp;
// return true;
//}
const std::vector<T>& data() const {return m_tmp;}
protected:
std::vector<T> m_tmp;
};
#ifdef TOOLS_HDF5_NTUPLE_STRING
class column_string_ref : public virtual icol {
#ifdef TOOLS_MEM
TOOLS_SCLASS(tools::hdf5::ntuple::column_string_ref)
@@ -553,95 +455,6 @@ public:
std::string m_name;
std::string& m_ref;
};
#else //!TOOLS_HDF5_NTUPLE_STRING
class column_string_ref : public column<unsigned int> {
typedef column<unsigned int> parent;
#ifdef TOOLS_MEM
TOOLS_SCLASS(tools::hdf5::ntuple::column_string_ref)
#endif
public:
static tools::cid id_class() {
static const std::string s_v;
return tools::_cid(s_v)+10000;
}
virtual void* cast(tools::cid a_class) const {
if(void* p = tools::cmp_cast<column_string_ref>(this,a_class)) {return p;}
else return 0;
}
virtual tools::cid id_cls() const {return id_class();}
public: //icol
virtual void reset() {
m_branch.reset_pos();
m_data_pages.reset_pos();
}
virtual bool add() { //write.
if(!m_write) return false;
if(m_ref.size()) {
const char* _data = m_ref.c_str();
if(!m_data_pages.write_page<char>(m_ref.size(),_data)) return false;
}
if(!parent::fill((unsigned int)m_ref.size())) return false;
if(!parent::add()) return false;
return true;
}
virtual bool fetch_entry() { //read.
if(m_write) return false;
if(!parent::fetch_entry()) return false;
unsigned int sz;
if(!parent::get_entry(sz)) return false;
m_ref.resize(sz);
if(sz) {
char* _data = (char*)m_ref.c_str();
if(!m_data_pages.read_page<char>(sz,_data)) {m_ref.clear();return false;}
}
return true;
}
virtual const std::string& name() const {return m_name;}
virtual bool set_basket_size(size_t /*a_size*/) {
//m_branch->set_basket_size(a_size);
return true;
}
public:
column_string_ref(store& a_store,pages& a_pages,bool a_write,
const std::string& a_name,size_t a_basket_size,
std::string& a_ref)
:parent(a_store,a_pages,a_write,a_name,a_basket_size)
,m_ref(a_ref)
,m_data_pages(a_store.out(),a_store.group(),a_name+"_data",tools::stype(char()),a_write,a_store.compress_level())
{
#ifdef TOOLS_MEM
tools::mem::increment(s_class().c_str());
#endif
if(!m_data_pages.is_valid()) {
m_store.out() << "tools::hdf5::column_string_ref::column_string_ref :"
<< " can't create data pages." << std::endl;
}
}
virtual ~column_string_ref(){
#ifdef TOOLS_MEM
tools::mem::decrement(s_class().c_str());
#endif
}
protected:
column_string_ref(const column_string_ref& a_from)
:icol(a_from)
,parent(a_from)
,m_ref(a_from.m_ref)
,m_data_pages(a_from.m_store.out(),a_from.m_store.group(),a_from.m_name+"_data",
tools::stype(char()),a_from.m_write,a_from.m_store.compress_level())
{}
column_string_ref& operator=(const column_string_ref& a_from){
if(&a_from==this) return *this;
m_name = a_from.m_name;
return *this;
}
public:
//const std::string& ref() const {return m_ref;}
protected:
std::string& m_ref;
pages m_data_pages;
};
#endif //TOOLS_HDF5_NTUPLE_STRING
class column_string : public column_string_ref {
typedef column_string_ref parent;
@@ -688,6 +501,143 @@ public:
std::string m_tmp;
};
class std_vector_column_string_ref : public virtual icol {
#ifdef TOOLS_MEM
static const std::string& s_class() {
static const std::string s_v("tools::hdf5::ntuple::std_vector_column_string_ref");
return s_v;
}
#endif
public:
static tools::cid id_class() {return tools::_cid_std_vector<std::string>()+10000;}
virtual void* cast(tools::cid a_class) const {
if(void* p = tools::cmp_cast<std_vector_column_string_ref>(this,a_class)) {return p;}
else return 0;
}
virtual tools::cid id_cls() const {return id_class();}
public: //icol
virtual bool add() { //write.
if(!m_write) return false;
size_t _size = 0;
{tools_vforcit(std::string,m_ref,it) {
_size += (*it).size();
_size++;
}}
char* _data = _size?new char[_size]:0;
{char* pos = _data;
tools_vforcit(std::string,m_ref,it) {
::memcpy(pos,(*it).c_str(),(*it).size());
pos += (*it).size();
*pos = 0;
pos++;
}}
return m_branch.write_vlen<char>(_size,_data);
}
virtual bool fetch_entry() { //read.
if(m_write) return false;
size_t n;
char* _data;
if(!m_branch.read_vlen<char>(n,_data)) {
m_store.out() << "tools::hdf5::ntuple::std_vector_column_string_ref:fetch_entry : read_page() failed." << std::endl;
return false;
}
m_ref.clear();
{char* pos = _data;
char* begin = _data;
for(size_t ichar=0;ichar<n;ichar++,pos++) {
if(*pos==0) {
m_ref.push_back(begin);
begin = pos+1;
}
}}
delete [] _data;
return true;
}
virtual void reset() {m_branch.reset_pos();}
virtual const std::string& name() const {return m_name;}
virtual bool set_basket_size(size_t) {return true;}
public:
std_vector_column_string_ref(store& a_store,pages& a_pages,bool a_write,const std::string& a_name,
size_t /*a_basket_size*/,
std::vector<std::string>& a_ref)
:m_store(a_store)
,m_branch(a_pages)
,m_write(a_write)
,m_name(a_name)
,m_ref(a_ref)
{
#ifdef TOOLS_MEM
tools::mem::increment(s_class().c_str());
#endif
}
virtual ~std_vector_column_string_ref(){
#ifdef TOOLS_MEM
tools::mem::decrement(s_class().c_str());
#endif
}
protected:
std_vector_column_string_ref(const std_vector_column_string_ref& a_from)
:icol(a_from)
,m_store(a_from.m_store)
,m_branch(a_from.m_branch)
,m_write(a_from.m_write)
,m_name(a_from.m_name)
,m_ref(a_from.m_ref)
{}
std_vector_column_string_ref& operator=(const std_vector_column_string_ref& a_from){
if(&a_from==this) return *this;
m_name = a_from.m_name;
return *this;
}
protected:
store& m_store;
pages& m_branch;
bool m_write;
std::string m_name;
std::vector<std::string>& m_ref;
};
class std_vector_column_string : public std_vector_column_string_ref {
typedef std_vector_column_string_ref parent;
#ifdef TOOLS_MEM
static const std::string& s_class() {
static const std::string s_v("tools::hdf5::ntuple::std_vector_column_string");
return s_v;
}
#endif
public:
static tools::cid id_class() {return tools::_cid_std_vector<std::string>();}
virtual void* cast(tools::cid a_class) const {
if(void* p = tools::cmp_cast<std_vector_column_string>(this,a_class)) {return p;}
else return 0;
}
virtual tools::cid id_cls() const {return id_class();}
public:
std_vector_column_string(store& a_store,pages& a_pages,bool a_write,const std::string& a_name,size_t a_basket_size)
:parent(a_store,a_pages,a_write,a_name,a_basket_size,m_tmp)
{}
virtual ~std_vector_column_string(){}
protected:
std_vector_column_string(const std_vector_column_string& a_from)
:icol(a_from)
,parent(a_from)
{}
std_vector_column_string& operator=(const std_vector_column_string& a_from){
parent::operator=(a_from);
return *this;
}
public:
//bool get_entry(std::vector<T>& a_v) const {
// a_v = m_tmp;
// return true;
//}
const std::vector<std::string>& data() const {return m_tmp;}
protected:
std::vector<std::string> m_tmp;
};
public:
ntuple(std::ostream& a_out,hid_t a_group,const std::string& a_name,
unsigned int a_compress,size_t /*a_basket_size*//* = 32000*/)
@@ -713,6 +663,13 @@ public:
m_cols.push_back(col);\
}
#define TOOLS_HDF5_NTUPLE_READ_CREATE_VEC_COL_STRING \
if((*it)->form()==s_vector_string()) {\
std_vector_column_string* col = new std_vector_column_string(*this,*(*it),false,(*it)->name(),0);\
if(!col) {tools::safe_clear<icol>(m_cols);return;}\
m_cols.push_back(col);\
}
TOOLS_HDF5_NTUPLE_READ_CREATE_COL(char)
else TOOLS_HDF5_NTUPLE_READ_CREATE_COL(short)
else TOOLS_HDF5_NTUPLE_READ_CREATE_COL(int)
@@ -748,7 +705,7 @@ public:
else TOOLS_HDF5_NTUPLE_READ_CREATE_VEC_COL(uint32,tools::uint32)
else TOOLS_HDF5_NTUPLE_READ_CREATE_VEC_COL(uint64,tools::uint64)
// else TOOLS_HDF5_NTUPLE_READ_CREATE_VEC_COL(std::string)
else TOOLS_HDF5_NTUPLE_READ_CREATE_VEC_COL_STRING
// else TOOLS_HDF5_NTUPLE_READ_CREATE_VEC_COL(bool) //use byte=uchar.
else {
@@ -821,6 +778,26 @@ public:
}\
}
#define TOOLS_HDF5_NTUPLE_CREATE_VEC_COL_STRING \
if((*it).cls_id()==tools::_cid_std_vector<std::string>()) {\
std::vector<std::string>* vec = (std::vector<std::string>*)(*it).user_obj();\
if(!vec) {\
m_out << "tools::hdf5::ntuple :"\
<< " for std::vector column " << tools::sout((*it).name())\
<< ", the user vector pointer is null."\
<< std::endl;\
tools::safe_clear<icol>(m_cols);\
return;\
}\
if(!create_std_column_string_ref((*it).name(),a_basket_size,*vec)) {\
m_out << "tools::hdf5::ntuple :"\
<< " can't create std::vector column " << tools::sout((*it).name()) << "."\
<< std::endl;\
tools::safe_clear<icol>(m_cols);\
return;\
}\
}
TOOLS_HDF5_NTUPLE_CREATE_COL(char)
else TOOLS_HDF5_NTUPLE_CREATE_COL(short)
else TOOLS_HDF5_NTUPLE_CREATE_COL(int)
@@ -858,6 +835,7 @@ public:
else TOOLS_HDF5_NTUPLE_CREATE_VEC_COL(tools::uint32)
else TOOLS_HDF5_NTUPLE_CREATE_VEC_COL(tools::uint64)
else TOOLS_HDF5_NTUPLE_CREATE_VEC_COL_STRING
// else TOOLS_HDF5_NTUPLE_CREATE_VEC_COL(std::string)
// else TOOLS_HDF5_NTUPLE_CREATE_VEC_COL(bool) //use byte=uchar.
@@ -917,6 +895,21 @@ public:
}\
}
#define TOOLS_HDF5_NTUPLE_READ_BINDING_CREATE_VEC_COL_STRING \
if((*it)->form()==s_vector_string()) {\
std::vector<std::string>* user_var = a_bd.find_variable< std::vector<std::string> >((*it)->name());\
if(user_var) {\
std_vector_column_string_ref* col = \
new std_vector_column_string_ref(*this,*(*it),false,(*it)->name(),0,*user_var);\
if(!col) {tools::safe_clear<icol>(m_cols);return false;}\
m_cols.push_back(col);\
} else {\
std_vector_column_string* col = new std_vector_column_string(*this,*(*it),false,(*it)->name(),0);\
if(!col) {tools::safe_clear<icol>(m_cols);return false;}\
m_cols.push_back(col);\
}\
}
TOOLS_HDF5_NTUPLE_READ_BINDING_CREATE_COL(char)
else TOOLS_HDF5_NTUPLE_READ_BINDING_CREATE_COL(short)
else TOOLS_HDF5_NTUPLE_READ_BINDING_CREATE_COL(int)
@@ -959,7 +952,8 @@ public:
else TOOLS_HDF5_NTUPLE_READ_BINDING_CREATE_VEC_COL(uint32,tools::uint32)
else TOOLS_HDF5_NTUPLE_READ_BINDING_CREATE_VEC_COL(uint64,tools::uint64)
// else TOOLS_HDF5_NTUPLE_READ_BINDING_CREATE_VEC_COL(std::string)
else TOOLS_HDF5_NTUPLE_READ_BINDING_CREATE_VEC_COL_STRING
// else TOOLS_HDF5_NTUPLE_READ_BINDING_CREATE_VEC_COL(bool) //use byte=uchar.
else {
@@ -1025,6 +1019,17 @@ public:
return col;
}
std_vector_column_string_ref* create_std_column_string_ref(const std::string& a_name,size_t a_basket_size,std::vector<std::string>& a_ref) {
//NOTE : to optimize, we do not handle a default std::vector value logic.
if(tools::find_named<icol>(m_cols,a_name)) return 0;
pages* _pages = create_pages(a_name,"vector<std::string>");
if(!_pages) return 0;
std_vector_column_string_ref* col = new std_vector_column_string_ref(*this,*_pages,true,a_name,a_basket_size,a_ref);
if(!col) return 0;
m_cols.push_back(col);
return col;
}
template <class T>
column_ref<T>* find_column_ref(const std::string& a_name) {
icol* col = tools::find_named<icol>(m_cols,a_name);
@@ -1051,6 +1056,17 @@ public:
return tools::id_cast<icol, std_vector_column<T> >(*col);
}
std_vector_column_string_ref* find_std_vector_column_string_ref(const std::string& a_name) {
icol* col = tools::find_named<icol>(m_cols,a_name);
if(!col) return 0;
return tools::id_cast<icol, std_vector_column_string_ref >(*col);
}
std_vector_column_string* find_std_vector_column_string(const std::string& a_name) {
icol* col = tools::find_named<icol>(m_cols,a_name);
if(!col) return 0;
return tools::id_cast<icol, std_vector_column_string >(*col);
}
column_string* find_column_string(const std::string& a_name) {
icol* col = tools::find_named<icol>(m_cols,a_name);
if(!col) return 0;
@@ -1091,4 +1107,5 @@ protected:
}}
#endif
File diff suppressed because it is too large Load Diff
-993
View File
@@ -1,993 +0,0 @@
// Copyright (C) 2010, Guy Barrand. All rights reserved.
// See the file tools.license for terms.
#ifndef tools_hep_polyhedron
#define tools_hep_polyhedron
// see (lengthy) doc and disclaimer at end.
#include "../lina/vec3d"
#include "../lina/rotd"
#ifdef TOOLS_MEM
#include "../mem"
#include "../S_STRING"
#endif
#include <string>
#include <vector>
//#define TOOLS_HEP_PH_OUT_ERR
//#define TOOLS_HEP_PH_OUT_ERR_TRD2
//#define TOOLS_HEP_PH_NOT_OPT
#ifdef TOOLS_HEP_PH_OUT_ERR
#include <iostream>
#endif
#ifdef TOOLS_HEP_PH_OUT_ERR_TRD2
#include <iostream>
#endif
#include <cmath>
namespace tools {
namespace hep {
typedef vec3d HVPoint3D;
typedef HVPoint3D HVNormal3D;
typedef HVPoint3D HVVector3D;
//WARNING : with SbFacet, take care of exlib::geant4::polyhedron
// that attempts to copy the private content of G4Facet.
// (see WARNING here).
class SbFacet {
#ifdef TOOLS_MEM
TOOLS_SCLASS(tools::hep::SbFacet)
#endif
friend class polyhedron;
#ifndef SWIG
friend std::ostream& operator<<(std::ostream&, const SbFacet &facet);
//G.Barrand
friend int operator == (const SbFacet & v1, const SbFacet & v2);
friend int operator != (const SbFacet & v1, const SbFacet & v2);
#endif
private:
typedef struct { int v,f; } edge_t; //G.Barrand
edge_t edge[4];
public:
SbFacet(int v1=0, int f1=0, int v2=0, int f2=0,
int v3=0, int f3=0, int v4=0, int f4=0)
{
#ifdef TOOLS_MEM
mem::increment(s_class().c_str());
#endif
edge[0].v=v1; edge[0].f=f1; edge[1].v=v2; edge[1].f=f2;
edge[2].v=v3; edge[2].f=f3; edge[3].v=v4; edge[3].f=f4; }
virtual ~SbFacet() {
#ifdef TOOLS_MEM
mem::decrement(s_class().c_str());
#endif
}
//public:
protected:
SbFacet(const SbFacet & aFrom) {
#ifdef TOOLS_MEM
mem::increment(s_class().c_str());
#endif
edge[0].v = aFrom.edge[0].v;
edge[0].f = aFrom.edge[0].f;
edge[1].v = aFrom.edge[1].v;
edge[1].f = aFrom.edge[1].f;
edge[2].v = aFrom.edge[2].v;
edge[2].f = aFrom.edge[2].f;
edge[3].v = aFrom.edge[3].v;
edge[3].f = aFrom.edge[3].f;
}
SbFacet& operator=(const SbFacet& aFrom) {
edge[0].v = aFrom.edge[0].v;
edge[0].f = aFrom.edge[0].f;
edge[1].v = aFrom.edge[1].v;
edge[1].f = aFrom.edge[1].f;
edge[2].v = aFrom.edge[2].v;
edge[2].f = aFrom.edge[2].f;
edge[3].v = aFrom.edge[3].v;
edge[3].f = aFrom.edge[3].f;
return *this;
}
public:
bool isEqual(const SbFacet& aFrom) const { //G.Barrand
if(edge[0].v!=aFrom.edge[0].v) return false;
if(edge[0].f!=aFrom.edge[0].f) return false;
if(edge[1].v!=aFrom.edge[1].v) return false;
if(edge[1].f!=aFrom.edge[1].f) return false;
if(edge[2].v!=aFrom.edge[2].v) return false;
if(edge[2].f!=aFrom.edge[2].f) return false;
if(edge[3].v!=aFrom.edge[3].v) return false;
if(edge[3].f!=aFrom.edge[3].f) return false;
return true;
}
void GetEdge(int i,int& v,int& f) const { //G.Barrand
v = edge[i].v;
f = edge[i].f;
}
void set(int v1, int f1, int v2, int f2, //G.Barrand
int v3, int f3, int v4, int f4) {
edge[0].v=v1; edge[0].f=f1; edge[1].v=v2; edge[1].f=f2;
edge[2].v=v3; edge[2].f=f3; edge[3].v=v4; edge[3].f=f4;
}
void Set(int v[8]) //G.Barrand
{ edge[0].v = v[0]; edge[0].f = v[1];
edge[1].v = v[2]; edge[1].f = v[3];
edge[2].v = v[4]; edge[2].f = v[5];
edge[3].v = v[6]; edge[3].f = v[7]; }
};
//G.Barrand :
//int operator == (const SbFacet & v1, const SbFacet & v2);
//int operator != (const SbFacet & v1, const SbFacet & v2);
class polyhedron {
#ifdef TOOLS_MEM
TOOLS_SCLASS(tools::hep::polyhedron)
#endif
#ifndef SWIG
friend std::ostream& operator<<(std::ostream&, const polyhedron &ph);
//G.Barrand
friend int operator == (const polyhedron & v1, const polyhedron & v2);
friend int operator != (const polyhedron & v1, const polyhedron & v2);
#endif
private: //G.Barrand
//std::string* m_name; //have a pointer to optimize memory.
protected:
int nvert, nface;
HVPoint3D* pV;
SbFacet* pF;
private:
int fNumberOfRotationSteps;
protected:
static double _M_PI() {return 3.1415926535897931160E0;}
//static double _M_PI_2() {return 1.5707963267948965580E0;}
// Allocate memory for polyhedron
void AllocateMemory(int Nvert, int Nface);
// Find neighbouring facet
int FindNeighbour(int iFace, int iNode, int iOrder) const;
// Find normal at node
HVNormal3D FindNodeNormal(int iFace, int iNode) const;
// Create polyhedron for prism with quadrilateral base
void CreatePrism();
// Generate facets by revolving an edge around Z-axis
void RotateEdge(int k1, int k2, double r1, double r2,
int v1, int v2, int vEdge,
bool ifWholeCircle, int ns, int &kface);
// Set side facets for the case of incomplete rotation
void SetSideFacets(int ii[4], int vv[4],
int *kk, double *r,
double dphi, int ns, int &kface);
// Create polyhedron for body of revolution around Z-axis
void RotateAroundZ(int nstep, double phi, double dphi,
int np1, int np2,
const double *z, double *r,
int nodeVis, int edgeVis);
// For each edge set reference to neighbouring facet
void SetReferences();
// Invert the order on nodes in facets
void InvertFacets();
public: //public for iv2sg
static int NUMBER_OF_STEPS() {return 24;}
public: //for iv2sg
static void do_not_set_NUMBER_OF_STEPS(int){}
public:
polyhedron(int Nvert=0, int Nface=0)
: /*m_name(0) //G.Barrand
,*/nvert(Nvert),nface(Nface)
,pV(Nvert ? new HVPoint3D[Nvert+1] : 0)
,pF(Nface ? new SbFacet[Nface+1] : 0)
,fNumberOfRotationSteps(NUMBER_OF_STEPS())
{
#ifdef TOOLS_MEM
mem::increment(s_class().c_str());
#endif
}
public:
virtual ~polyhedron() {
//delete m_name; //G.Barrand.
delete [] pV; delete [] pF;
#ifdef TOOLS_MEM
mem::decrement(s_class().c_str());
#endif
}
public:
polyhedron(const polyhedron & from);
polyhedron& operator=(const polyhedron & from);
public:
//G.Barrand : handle a name to help debugging.
/*
void setName(const std::string& aName) {
delete m_name;
m_name = new std::string(aName);
}
const std::string& getName() const {
if(!m_name) return s_empty();
return *m_name;
}
*/
//G.Barrand :end
void Set(int Nvert, HVPoint3D* aV,
int Nface, SbFacet* aF) //G.Barrand
{ delete [] pV; delete [] pF;
nvert = Nvert; nface = Nface; pV = aV; pF = aF;}
void Empty() //G.Barrand
{ nvert = 0; nface = 0; pV = 0;pF = 0;}
// Get number of vertices
int GetNoVertices() const { return nvert; }
// Get number of facets
int GetNoFacets() const { return nface; }
// Transform the polyhedron
polyhedron& Translate(double,double,double);
polyhedron& Transform(const rotd& rot,double,double,double);
polyhedron& Transform(const rotd& rot,const vec3d& trans);
// Get next vertex index of the quadrilateral
//G.Barrand
bool GetNextVertexIndex(int & index, int & edgeFlag) const;
// Get vertex by index
HVPoint3D GetVertex(int index) const;
const HVPoint3D& GetVertexFast(int index) const; //G.Barrand
//G.Barrand : to optimize SoPolyhedron.
HVPoint3D* GetPV() const {return pV;} //G.Barrand
SbFacet* GetPF() const {return pF;} //G.Barrand
// Get next vertex + edge visibility of the quadrilateral
bool GetNextVertex(HVPoint3D & vertex, int & edgeFlag) const;
// Get next vertex + edge visibility + normal of the quadrilateral
bool GetNextVertex(HVPoint3D & vertex, int & edgeFlag,
HVNormal3D & normal) const;
// Get indeces of the next edge with indeces of the faces
bool GetNextEdgeIndeces(int & i1, int & i2, int & edgeFlag,
int & iface1, int & iface2) const;
// Get indeces of the next edge
bool GetNextEdgeIndeces(int & i1, int & i2, int & edgeFlag) const;
// Get next edge
bool GetNextEdge(HVPoint3D &p1, HVPoint3D &p2, int &edgeFlag) const;
// Get next edge
bool GetNextEdge(HVPoint3D &p1, HVPoint3D &p2, int &edgeFlag,
int &iface1, int &iface2) const;
// Get face by index
void GetFacet(int iFace, int &n, int *iNodes,
int *edgeFlags = 0, int *iFaces = 0) const;
// Get face by index
void GetFacet(int iFace, int &n, HVPoint3D *nodes,
int *edgeFlags = 0, HVNormal3D *normals = 0) const;
// Get next face with normals at the nodes
bool GetNextFacet(int &n, HVPoint3D *nodes,
int *edgeFlags=0, HVNormal3D *normals=0) const;
// Get normal of the face given by index
HVNormal3D GetNormal(int iFace) const;
// Get unit normal of the face given by index
HVNormal3D GetUnitNormal(int iFace) const;
// Get normal of the next face
bool GetNextNormal(HVNormal3D &normal) const;
// Get normal of unit length of the next face
bool GetNextUnitNormal(HVNormal3D &normal) const;
// Boolean operations
polyhedron add(const polyhedron &p) const;
polyhedron subtract(const polyhedron &p) const;
polyhedron intersect(const polyhedron &p) const;
// Get area of the surface of the polyhedron
double GetSurfaceArea() const;
// Get volume of the polyhedron
double GetVolume() const;
bool isEqual(const polyhedron &p) const; //G.Barrand
bool isConsistent(const char* = 0) const; //G.Barrand
void dump(std::ostream&) const;
// Get number of steps for whole circle
int GetNumberOfRotationSteps(); //G.Barrand : no more static.
// Set number of steps for whole circle
void SetNumberOfRotationSteps(int n);
// Reset number of steps for whole circle to default value
void ResetNumberOfRotationSteps(); //G.Barrand : have code in .cxx.
public:
//G.Barrand : have the below set_ to optimize exlib/sg/polyhedron setup.
bool set_polyhedron_cons(double Rmn1, double Rmx1,
double Rmn2, double Rmx2, double Dz,
double Phi1, double Dphi,
int nstep = 0); //G.Barrand
bool set_polyhedron_tube(double Rmin, double Rmax, double Dz,
int nstep = 0){
return set_polyhedron_cons(Rmin, Rmax, Rmin, Rmax, Dz, 0, 2*_M_PI(), nstep);
}
double vxy(const double* xy,int i,int j) {return xy[i*2+j];}
bool set_polyhedron_arb8(double Dz,const double* xy);
bool set_polyhedron_trd2(double Dx1, double Dx2,
double Dy1, double Dy2, double Dz);
bool set_polyhedron_box(double Dx, double Dy, double Dz){
return set_polyhedron_trd2(Dx, Dx, Dy, Dy, Dz);
}
bool set_polyhedron_trd1(double Dx1, double Dx2,
double Dy, double Dz){
return set_polyhedron_trd2(Dx1, Dx2, Dy, Dy, Dz);
}
bool set_polyhedron_trap(double Dz, double Theta, double Phi,
double Dy1,
double Dx1, double Dx2, double Alp1,
double Dy2,
double Dx3, double Dx4, double Alp2);
bool set_polyhedron_para(double Dx, double Dy, double Dz,
double Alpha, double Theta,
double Phi){
return set_polyhedron_trap(Dz,Theta,Phi,Dy,Dx,Dx,Alpha,Dy,Dx,Dx,Alpha);
}
bool set_polyhedron_pgon(double phi, double dphi, int npdv, int nz,
const double *z,
const double *rmin,
const double *rmax);
bool set_polyhedron_pcon(double phi, double dphi, int nz,
const double *z,
const double *rmin,
const double *rmax) {
return set_polyhedron_pgon(phi, dphi, 0, nz, z, rmin, rmax);
}
bool set_polyhedron_tubs(double Rmin, double Rmax,
double Dz,
double Phi1, double Dphi,
int nstep) {//G.Barrand
return set_polyhedron_cons(Rmin, Rmax, Rmin, Rmax, Dz, Phi1, Dphi, nstep);
}
bool set_polyhedron_cone(double Rmn1, double Rmx1,
double Rmn2, double Rmx2,
double Dz,
int nstep) {
return set_polyhedron_cons(Rmn1, Rmx1, Rmn2, Rmx2, Dz, 0, 2*_M_PI(), nstep);
}
bool set_polyhedron_torus(double rmin,double rmax,double rtor,
double phi,double dphi,
int nphi, //G.Barrand
int nthe); //G.Barrand
bool set_polyhedron_xtru(int a_npts,int a_nz,
double* a_xs,double* a_ys,double* a_zs,
bool a_acw = true,
bool a_zfb = true);
bool set_polyhedron_sphere(double rmin, double rmax,
double phi, double dphi,
double the, double dthe,
int nphi = 0,
int nthe = 0); //G.Barrand
bool set_polyhedron_hype(double a_st_in,double a_st_out,
double a_rmin,double a_rmax,double a_dz,
int a_nz = 10,int a_nphi = 24);
bool set_polyhedron_eltu(double a_dx,double a_dy,double a_dz,
int a_nz = 10,int a_nphi = 24);
private: //G.Barrand
int _ixy(int,int,int,int,bool,bool);
void _clear(){
//used in set_polyhedronXxx()
delete [] pV;
pV = 0;
delete [] pF;
pF = 0;
nvert = 0;
nface = 0;
}
bool CHECK_INDEX(const char* a_method,int a_index) const;
};
//G.Barrand :
//int operator == (const polyhedron & v1, const polyhedron & v2);
//int operator != (const polyhedron & v1, const polyhedron & v2);
// G.Barrand : introduce iabs to avoid a mess with cmath and some compiler.
inline int Sb_iabs(int a) {
return a < 0 ? -a : a;
}
inline //G.Barrand
bool polyhedron::GetNextVertexIndex(int &index, int &edgeFlag) const
/***********************************************************************
* *
* Name: polyhedron::GetNextVertexIndex Date: 03.09.96 *
* Author: Yasuhide Sawada Revised: *
* *
* Function: *
* *
***********************************************************************/
{
static int iFace = 1;
static int iQVertex = 0;
//G.Barrand : int vIndex = pF[iFace].edge[iQVertex].v;
SbFacet::edge_t* edge = pF[iFace].edge; //G.Barrand : optimize.
int vIndex = edge[iQVertex].v;
edgeFlag = (vIndex > 0) ? 1 : 0;
index = Sb_iabs(vIndex);
if(index>nvert) {
#ifdef TOOLS_HEP_PH_OUT_ERR
std::cerr << "polyhedron::GetNextVertexIndex: pV index problem "
<< index << " exceed " << nvert << std::endl;
#endif
index = 0;
}
//G.Barrand : if (iQVertex >= 3 || pF[iFace].edge[iQVertex+1].v == 0) {
if (iQVertex >= 3 || edge[iQVertex+1].v == 0) {
iQVertex = 0;
if (++iFace > nface) iFace = 1;
return false; // Last Edge
}else{
++iQVertex;
return true; // not Last Edge
}
}
class polyhedron_trd2 : public polyhedron {
public:
polyhedron_trd2(double Dx1, double Dx2,
double Dy1, double Dy2, double Dz);
virtual ~polyhedron_trd2(){}
public:
polyhedron_trd2(const polyhedron_trd2& a_from):polyhedron(a_from){}
polyhedron_trd2& operator=(const polyhedron_trd2& a_from){
polyhedron::operator=(a_from);
return *this;
}
//virtual polyhedron& operator = (const polyhedron& from) {
// return polyhedron::operator = (from);
//}
};
class polyhedron_arb8 : public polyhedron {
public:
polyhedron_arb8(double Dz,const double* xy);
virtual ~polyhedron_arb8(){}
public:
polyhedron_arb8(const polyhedron_arb8& a_from):polyhedron(a_from){}
polyhedron_arb8& operator=(const polyhedron_arb8& a_from){
polyhedron::operator=(a_from);
return *this;
}
//virtual polyhedron& operator = (const polyhedron& from) {
// return polyhedron::operator = (from);
//}
};
class polyhedron_xtru : public polyhedron {
public:
polyhedron_xtru(int a_npts,int a_nz,
double* a_xs,double* a_ys,double* a_zs,
bool a_acw = true,
bool a_zfb = true);
virtual ~polyhedron_xtru(){}
public:
polyhedron_xtru(const polyhedron_xtru& a_from):polyhedron(a_from){}
polyhedron_xtru& operator=(const polyhedron_xtru& a_from){
polyhedron::operator=(a_from);
return *this;
}
};
class polyhedron_hype : public polyhedron {
public:
polyhedron_hype(double a_st_in,double a_st_out,
double a_rmin,double a_rmax,double a_dz,
int a_nz = 10,int a_nphi = 24);
virtual ~polyhedron_hype(){}
public:
polyhedron_hype(const polyhedron_hype& a_from):polyhedron(a_from){}
polyhedron_hype& operator=(const polyhedron_hype& a_from){
polyhedron::operator=(a_from);
return *this;
}
};
class polyhedron_trd1 : public polyhedron_trd2 {
public:
polyhedron_trd1(double Dx1, double Dx2,
double Dy, double Dz);
virtual ~polyhedron_trd1(){}
public:
polyhedron_trd1(const polyhedron_trd1& a_from):polyhedron_trd2(a_from){}
polyhedron_trd1& operator=(const polyhedron_trd1& a_from){
polyhedron_trd2::operator=(a_from);
return *this;
}
//virtual polyhedron& operator = (const polyhedron& from) {
// return polyhedron::operator = (from);
//}
};
class polyhedron_box : public polyhedron_trd2 {
public:
polyhedron_box(double Dx, double Dy, double Dz);
virtual ~polyhedron_box(){}
public:
polyhedron_box(const polyhedron_box& a_from):polyhedron_trd2(a_from){}
polyhedron_box& operator=(const polyhedron_box& a_from){
polyhedron_trd2::operator=(a_from);
return *this;
}
//virtual polyhedron& operator = (const polyhedron& from) {
// return polyhedron::operator = (from);
//}
};
class polyhedron_trap : public polyhedron {
public:
polyhedron_trap(double Dz, double Theta, double Phi,
double Dy1,
double Dx1, double Dx2, double Alp1,
double Dy2,
double Dx3, double Dx4, double Alp2);
virtual ~polyhedron_trap(){}
public:
polyhedron_trap(const polyhedron_trap& a_from):polyhedron(a_from){}
polyhedron_trap& operator=(const polyhedron_trap& a_from){
polyhedron::operator=(a_from);
return *this;
}
//virtual polyhedron& operator = (const polyhedron& from) {
// return polyhedron::operator = (from);
//}
};
class polyhedron_para : public polyhedron_trap {
public:
polyhedron_para(double Dx, double Dy, double Dz,
double Alpha, double Theta, double Phi);
virtual ~polyhedron_para(){}
public:
polyhedron_para(const polyhedron_para& a_from):polyhedron_trap(a_from){}
polyhedron_para& operator=(const polyhedron_para& a_from){
polyhedron_trap::operator=(a_from);
return *this;
}
//virtual polyhedron& operator = (const polyhedron& from) {
// return polyhedron::operator = (from);
//}
};
class polyhedron_cons : public polyhedron {
public:
polyhedron_cons(double Rmn1, double Rmx1,
double Rmn2, double Rmx2, double Dz,
double Phi1, double Dphi,
int nstep = 0); //G.Barrand
virtual ~polyhedron_cons(){}
public:
polyhedron_cons(const polyhedron_cons& a_from):polyhedron(a_from){}
polyhedron_cons& operator=(const polyhedron_cons& a_from){
polyhedron::operator=(a_from);
return *this;
}
//virtual polyhedron& operator = (const polyhedron& from) {
// return polyhedron::operator = (from);
//}
};
class polyhedron_cone : public polyhedron_cons {
public:
polyhedron_cone(double Rmn1, double Rmx1,
double Rmn2, double Rmx2, double Dz,
int nstep = 0); //G.Barrand
virtual ~polyhedron_cone(){}
public:
polyhedron_cone(const polyhedron_cone& a_from):polyhedron_cons(a_from){}
polyhedron_cone& operator=(const polyhedron_cone& a_from){
polyhedron_cons::operator=(a_from);
return *this;
}
//virtual polyhedron& operator = (const polyhedron& from) {
// return polyhedron::operator = (from);
//}
};
class polyhedron_tubs : public polyhedron_cons {
public:
polyhedron_tubs(double Rmin, double Rmax, double Dz,
double Phi1, double Dphi,
int nstep = 0); //G.Barrand
virtual ~polyhedron_tubs(){}
public:
polyhedron_tubs(const polyhedron_tubs& a_from):polyhedron_cons(a_from){}
polyhedron_tubs& operator=(const polyhedron_tubs& a_from){
polyhedron_cons::operator=(a_from);
return *this;
}
//virtual polyhedron& operator = (const polyhedron& from) {
// return polyhedron::operator = (from);
//}
};
class polyhedron_tube : public polyhedron_cons {
public:
polyhedron_tube(double Rmin, double Rmax, double Dz,int nstep = 0); //G.Barrand
virtual ~polyhedron_tube(){}
public:
polyhedron_tube(const polyhedron_tube& a_from):polyhedron_cons(a_from){}
polyhedron_tube& operator=(const polyhedron_tube& a_from){
polyhedron_cons::operator=(a_from);
return *this;
}
//virtual polyhedron& operator = (const polyhedron& from) {
// return polyhedron::operator = (from);
//}
};
class polyhedron_pgon : public polyhedron {
public:
polyhedron_pgon(double phi, double dphi, int npdv, int nz,
const double *z,
const double *rmin,
const double *rmax);
virtual ~polyhedron_pgon(){}
public:
polyhedron_pgon(const polyhedron_pgon& a_from):polyhedron(a_from){}
polyhedron_pgon& operator=(const polyhedron_pgon& a_from){
polyhedron::operator=(a_from);
return *this;
}
//virtual polyhedron& operator = (const polyhedron& from) {
// return polyhedron::operator = (from);
//}
};
class polyhedron_pcon : public polyhedron_pgon {
public:
polyhedron_pcon(double phi, double dphi, int nz,
const double *z,
const double *rmin,
const double *rmax);
virtual ~polyhedron_pcon(){}
public:
polyhedron_pcon(const polyhedron_pcon& a_from):polyhedron_pgon(a_from){}
polyhedron_pcon& operator=(const polyhedron_pcon& a_from){
polyhedron_pgon::operator=(a_from);
return *this;
}
//virtual polyhedron& operator = (const polyhedron& from) {
// return polyhedron::operator = (from);
//}
};
class polyhedron_sphere : public polyhedron {
public:
polyhedron_sphere(double rmin, double rmax,
double phi, double dphi,
double the, double dthe,
int nphi = 0,
int nthe = 0); //G.Barrand
virtual ~polyhedron_sphere(){}
public:
polyhedron_sphere(const polyhedron_sphere& a_from):polyhedron(a_from){}
polyhedron_sphere& operator=(const polyhedron_sphere& a_from){
polyhedron::operator=(a_from);
return *this;
}
//virtual polyhedron& operator = (const polyhedron& from) {
// return polyhedron::operator = (from);
//}
};
class polyhedron_torus : public polyhedron {
public:
polyhedron_torus(double rmin, double rmax, double rtor,
double phi, double dphi,
int nphi = 0,
int nthe = 0); //G.Barrand
virtual ~polyhedron_torus(){}
public:
polyhedron_torus(const polyhedron_torus& a_from):polyhedron(a_from){}
polyhedron_torus& operator=(const polyhedron_torus& a_from){
polyhedron::operator=(a_from);
return *this;
}
//virtual polyhedron& operator = (const polyhedron& from) {
// return polyhedron::operator = (from);
//}
};
//G.Barrand : begin
class polyhedronProcessor {
#ifdef TOOLS_MEM
TOOLS_SCLASS(tools::hep::polyhedronProcessor)
#endif
public:
enum Operation { //Must be the same than BooleanProcessor OP_XXX.
UNION = 0
,INTERSECTION = 1
,SUBTRACTION = 2
};
private:
typedef std::pair<Operation,polyhedron> op_t;
public:
polyhedronProcessor(){
#ifdef TOOLS_MEM
mem::increment(s_class().c_str());
#endif
}
virtual ~polyhedronProcessor(){
#ifdef TOOLS_MEM
mem::decrement(s_class().c_str());
#endif
}
private:
polyhedronProcessor(const polyhedronProcessor&){
#ifdef TOOLS_MEM
mem::increment(s_class().c_str());
#endif
}
polyhedronProcessor& operator=(const polyhedronProcessor&){return *this;}
public:
void push_back(Operation a_op,const polyhedron& a_polyhedron) {
m_ops.push_back(op_t(a_op,a_polyhedron));
}
bool execute(polyhedron&);
void clear() { m_ops.clear();}
bool is_same_op() const {
if(!m_ops.size()) return true;
Operation op = m_ops[0].first;
std::vector<op_t>::const_iterator it;
for(it=m_ops.begin();it!=m_ops.end();++it) {
if((*it).first!=op) return false;
}
return true;
}
//private:
bool execute1(polyhedron&,const std::vector<unsigned int>&);
private:
std::vector<op_t> m_ops;
};
//G.Barrand : end
//inline const std::string& stype(const polyhedron&) {
// static const std::string s_v("tools::hep::polyhedron");
// return s_v;
//}
}}
#include "polyhedron.icc"
namespace tools {
namespace hep {
template <class MATRIX>
inline void tsf_polyhedron(polyhedron& a_ph,const MATRIX& a_matrix) {
typedef typename MATRIX::elem_t T;
int nvert = a_ph.GetNoVertices();
hep::HVPoint3D* pV = a_ph.GetPV();
if (nvert > 0) {
T x,y,z;
for (int i=1; i<=nvert; i++) {
hep::HVPoint3D& p = pV[i];
x = T(p.x());
y = T(p.y());
z = T(p.z());
a_matrix.mul_3(x,y,z);
p.set_value(x,y,z);
}
}
}
}}
#endif
//--------------------------------------------------------------------//
// JFB: //
// polyhedron was HepPolyhedron, retrofitted to Open Inventor //
// infrastructure: //
//--------------------------------------------------------------------//
// ********************************************************************
// * DISCLAIMER *
// * *
// * The following disclaimer summarizes all the specific disclaimers *
// * of contributors to this software. The specific disclaimers,which *
// * govern, are listed with their locations in: *
// * http://cern.ch/geant4/license *
// * *
// * 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. *
// * *
// * This code implementation is the intellectual property of the *
// * GEANT4 collaboration. *
// * By copying, distributing or modifying the Program (or any work *
// * based on the Program) you indicate your acceptance of this *
// * statement, and all its terms. *
// ********************************************************************
//
//
//
//
// Class Description:
// polyhedron is an intermediate class between description of a shape
// and visualization systems. It is intended to provide some service like:
// - polygonization of shapes with triangulization (quadrilaterization)
// of complex polygons;
// - calculation of normals for faces and vertices;
// - finding result of boolean operation on polyhedra;
//
// Public constructors:
//
// polyhedron_box (dx,dy,dz)
// - create polyhedron for Box;
// polyhedron_trd1 (dx1,dx2,dy,dz)
// - create polyhedron for G3 Trd1;
// polyhedron_trd2 (dx1,dx2,dy1,dy2,dz)
// - create polyhedron for G3 Trd2;
// polyhedron_trap (dz,theta,phi, h1,bl1,tl1,alp1, h2,bl2,tl2,alp2)
// - create polyhedron for G3 Trap;
// polyhedron_para (dx,dy,dz,alpha,theta,phi)
// - create polyhedron for G3 Para;
// polyhedron_tube (rmin,rmax,dz,nstep=0)
// - create polyhedron for G3 Tube;
// polyhedron_tubs (rmin,rmax,dz,phi1,dphi,nstep=0)
// - create polyhedron for G3 Tubs;
// polyhedron_cone (rmin1,rmax1,rmin2,rmax2,dz,nstep=0)
// - create polyhedron for G3 Cone;
// polyhedron_cons (rmin1,rmax1,rmin2,rmax2,dz,phi1,dphi,nstep=0)
// - create polyhedron for G3 Cons;
// polyhedron_pgon (phi,dphi,npdv,nz, z(*),rmin(*),rmax(*))
// - create polyhedron for G3 Pgon;
// polyhedron_pcon (phi,dphi,nz, z(*),rmin(*),rmax(*))
// - create polyhedron for G3 Pcon;
// polyhedron_sphere (rmin,rmax,phi,dphi,the,dthe,nstep=0)
// - create polyhedron for Sphere;
// polyhedron_torus (rmin,rmax,rtor,phi,dphi,nstep=0)
// - create polyhedron for Torus;
// Public functions:
//
// GetNoVertices () - returns number of vertices;
// GetNoFacets () - returns number of faces;
// GetNextVertexIndex (index,edgeFlag) - get vertex indeces of the
// quadrilaterals in order;
// returns false when finished each face;
// GetVertex (index) - returns vertex by index;
// GetNextVertex (vertex,edgeFlag) - get vertices with edge visibility
// of the quadrilaterals in order;
// returns false when finished each face;
// GetNextVertex (vertex,edgeFlag,normal) - get vertices with edge
// visibility and normal of the quadrilaterals
// in order; returns false when finished each face;
// GetNextEdgeIndeces (i1,i2,edgeFlag) - get indeces of the next edge;
// returns false for the last edge;
// GetNextEdgeIndeces (i1,i2,edgeFlag,iface1,iface2) - get indeces of
// the next edge with indeces of the faces
// to which the edge belongs;
// returns false for the last edge;
// GetNextEdge (p1,p2,edgeFlag) - get next edge;
// returns false for the last edge;
// GetNextEdge (p1,p2,edgeFlag,iface1,iface2) - get next edge with indeces
// of the faces to which the edge belongs;
// returns false for the last edge;
// GetFacet (index,n,nodes,edgeFlags=0,normals=0) - get face by index;
// GetNextFacet (n,nodes,edgeFlags=0,normals=0) - get next face with normals
// at the nodes; returns false for the last face;
// GetNormal (index) - get normal of face given by index;
// GetUnitNormal (index) - get unit normal of face given by index;
// GetNextNormal (normal) - get normals of each face in order;
// returns false when finished all faces;
// GetNextUnitNormal (normal) - get normals of unit length of each face
// in order; returns false when finished all faces;
// GetSurfaceArea() - get surface area of the polyhedron;
// GetVolume() - get volume of the polyhedron;
// GetNumberOfRotationSteps() - get number of steps for whole circle;
// SetNumberOfRotationSteps (n) - set number of steps for whole circle;
// ResetNumberOfRotationSteps() - reset number of steps for whole circle
// to default value;
// History:
//
// 20.06.96 Evgeni Chernyaev <Evgueni.Tcherniaev@cern.ch> - initial version
//
// 23.07.96 John Allison
// - added GetNoVertices, GetNoFacets, GetNextVertex, GetNextNormal
//
// 30.09.96 E.Chernyaev
// - added GetNextVertexIndex, GetVertex by Yasuhide Sawada
// - added GetNextUnitNormal, GetNextEdgeIndeces, GetNextEdge
// - improvements: angles now expected in radians
// int -> G4int, double -> G4double
// - G4ThreeVector replaced by either G4Point3D or G4Normal3D
//
// 15.12.96 E.Chernyaev
// - private functions G4PolyhedronAlloc, G4PolyhedronPrism renamed
// to AllocateMemory and CreatePrism
// - added private functions GetNumberOfRotationSteps, RotateEdge,
// RotateAroundZ, SetReferences
// - rewritten G4PolyhedronCons;
// - added G4PolyhedronPara, ...Trap, ...Pgon, ...Pcon, ...Sphere, ...Torus,
// so full List of implemented shapes now looks like:
// BOX, TRD1, TRD2, TRAP, TUBE, TUBS, CONE, CONS, PARA, PGON, PCON,
// SPHERE, TORUS
//
// 01.06.97 E.Chernyaev
// - RotateAroundZ modified and SetSideFacets added to allow Rmin=Rmax
// in bodies of revolution
//
// 24.06.97 J.Allison
// - added static private member fNumberOfRotationSteps and static public
// functions void SetNumberOfRotationSteps (G4int n) and
// void ResetNumberOfRotationSteps (). Modified
// GetNumberOfRotationSteps() appropriately. Made all three functions
// inline (at end of this .hh file).
// Usage:
// G4Polyhedron::SetNumberOfRotationSteps
// (fpView -> GetViewParameters ().GetNoOfSides ());
// pPolyhedron = solid.CreatePolyhedron ();
// G4Polyhedron::ResetNumberOfRotationSteps ();
//
// 19.03.00 E.Chernyaev
// - added boolean operations (add, subtract, intersect) on polyhedra;
//
// 25.05.01 E.Chernyaev
// - added GetSurfaceArea() and GetVolume();
//
File diff suppressed because it is too large Load Diff
-116
View File
@@ -1,116 +0,0 @@
// Copyright (C) 2010, Guy Barrand. All rights reserved.
// See the file tools.license for terms.
#ifndef tools_hep_sf_polyhedron
#define tools_hep_sf_polyhedron
#include "../sg/bsf"
#include "polyhedron"
#include "../typedefs"
#include "../io/iwbuf"
#include "../io/irbuf"
#include "../HEADER"
namespace tools {
namespace hep {
class sf_polyhedron : public sg::bsf<polyhedron> {
TOOLS_HEADER(sf_polyhedron,tools::hep::sf_polyhedron,sg::bsf<polyhedron>)
public:
virtual bool write(io::iwbuf& a_buffer) {
//FIXME : write fNumberOfSteps ?
int nvert = m_value.GetNoVertices();
int nface = m_value.GetNoFacets();
double* ds = new double[1+3*nvert+1+8*nface];
uint32 di=0;
{ds[di] = nvert;di++;
HVPoint3D* pV = m_value.GetPV();
for(int index=1;index<=nvert;index++) { //CERN still in FORTRAN...
HVPoint3D& p = pV[index];
ds[di] = p[0];di++;
ds[di] = p[1];di++;
ds[di] = p[2];di++;
}}
{ds[di] = nface;di++;
SbFacet* pF = m_value.GetPF();
int v,f;
for(int index=1;index<=nface;index++) {
SbFacet& fc = pF[index]; //yes, yes +1
for(int i=0;i<4;i++) {
fc.GetEdge(i,v,f);
ds[di] = v;di++;
ds[di] = f;di++;
}
}}
bool status = a_buffer.write_vec(di,ds);
delete [] ds;
return status;
}
virtual bool read(io::irbuf& a_buffer) {
double* ds;
uint32 sz;
if(!a_buffer.read_vec(sz,ds)) return false;
uint32 di=0;
//FIXME : check di vs sz.
int nvert = (int)ds[di];di++;
HVPoint3D* pV = new HVPoint3D[nvert+1];
for(int index=1;index<=nvert;index++) {
HVPoint3D& p = pV[index];
p[0] = ds[di];di++;
p[1] = ds[di];di++;
p[2] = ds[di];di++;
}
int nface = (int)ds[di];di++;
SbFacet* pF = new SbFacet[nface+1];
int v[8];
for(int index=1;index<=nface;index++) {
SbFacet& fc = pF[index];
for(int i=0;i<8;i++) {
v[i] = (int)ds[di];di++;
}
fc.Set(v);
}
m_value.Set(nvert,pV,nface,pF); //it takes ownership of pV,pF.
delete [] ds;
#ifdef TOOLS_MEM
mem::decrement(s_new().c_str());
#endif
return true;
}
virtual bool dump(std::ostream&) {
return true;
}
virtual bool s_value(std::string& a_s) const {a_s.clear();return false;}
virtual bool s2value(const std::string&) {return false;}
public:
sf_polyhedron():parent(){}
sf_polyhedron(const polyhedron& a_value):parent(a_value){}
virtual ~sf_polyhedron(){}
public:
sf_polyhedron(const sf_polyhedron& a_from):parent(a_from){}
sf_polyhedron& operator=(const sf_polyhedron& a_from){
parent::operator=(a_from);
return *this;
}
public:
sf_polyhedron& operator=(const polyhedron& a_value){
parent::operator=(a_value);
return *this;
}
};
}}
#endif
-49
View File
@@ -1,49 +0,0 @@
// Copyright (C) 2010, Guy Barrand. All rights reserved.
// See the file tools.license for terms.
#ifndef tools_histo_histos
#define tools_histo_histos
#include "h1d"
#include "h2d"
#include "h3d"
#include "p1d"
#include "p2d"
#include "../forit"
namespace tools {
namespace histo {
inline void delete_histos(std::vector< std::pair<std::string,void*> >& a_hists) {
typedef std::pair<std::string,void*> class_pointer;
tools_vforit(class_pointer,a_hists,it) {
const std::string& scls = (*it).first;
if(scls==h1d::s_class()) {
h1d* h = (h1d*)(*it).second;
delete h;
} else if(scls==h2d::s_class()) {
h2d* h = (h2d*)(*it).second;
delete h;
} else if(scls==h3d::s_class()) {
h3d* h = (h3d*)(*it).second;
delete h;
} else if(scls==p1d::s_class()) {
p1d* h = (p1d*)(*it).second;
delete h;
} else if(scls==p2d::s_class()) {
p2d* h = (p2d*)(*it).second;
delete h;
}
}
a_hists.clear();
}
}}
#endif
-338
View File
@@ -1,338 +0,0 @@
// Copyright (C) 2010, Guy Barrand. All rights reserved.
// See the file tools.license for terms.
#ifndef tools_histo_htoc
#define tools_histo_htoc
struct caxis_dui { //d=double, ui=unsigned int
typedef double TC;
typedef unsigned int TO;
typedef unsigned int bn_t;
TO m_offset;
bn_t m_number_of_bins;
TC m_minimum_value;
TC m_maximum_value;
unsigned char m_fixed;
TC m_bin_width;
unsigned int m_number_of_edges;
TC* m_edges; //[m_number_of_edges]
};
struct chisto_duiuid {
typedef double TC;
typedef unsigned int TO;
typedef unsigned int TN;
typedef double TW;
typedef unsigned int dim_t;
// General :
char* m_title;
dim_t m_dimension;
// Bins :
TO m_bin_number;
TN* m_bin_entries; //[m_bin_number]
TW* m_bin_Sw; //[m_bin_number]
TW* m_bin_Sw2; //[m_bin_number]
TC** m_bin_Sxw; //[m_bin_number][m_dimension]
TC** m_bin_Sx2w; //[m_bin_number][m_dimension]
// Axes :
caxis_dui** m_axes; //[m_dimension]
// etc :
TC* m_in_range_plane_Sxyw; //(dim,size) (1,0) (2,1) (3,3)
unsigned int m_number_of_annotations;
char** m_annotations; //[m_number_of_annotations]
// fast getters :
TN m_all_entries; //used if reading from a ROOT file.
TN m_in_range_entries;
TW m_in_range_Sw;
TW m_in_range_Sw2;
TC* m_in_range_Sxw; //[m_dimension]
TC* m_in_range_Sx2w; //[m_dimension]
};
struct cprofile_duiuidd {
typedef double TV;
chisto_duiuid m_histo;
unsigned char m_is_profile;
TV* m_bin_Svw; //[m_bin_number]
TV* m_bin_Sv2w; //[m_bin_number]
unsigned char m_cut_v;
TV m_min_v;
TV m_max_v;
};
#include "histo_data"
#include "../cstr"
#include "../cmemT"
#include "../vdata"
#include "../forit"
namespace tools {
namespace histo {
/////////////////////////////////////////////////////////////////////////////
/// hist_data to C struct ///////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
inline caxis_dui* caxis_dui_alloc(const axis<double,unsigned int>& a_axis) {
caxis_dui* a_cp = cmem_alloc<caxis_dui>(1);
if(!a_cp) return NULL;
caxis_dui& a_c = *a_cp;
typedef double TC;
a_c.m_offset = a_axis.m_offset;
a_c.m_number_of_bins = a_axis.m_number_of_bins;
a_c.m_minimum_value = a_axis.m_minimum_value;
a_c.m_maximum_value = a_axis.m_maximum_value;
a_c.m_fixed = a_axis.m_fixed?1:0;
a_c.m_bin_width = a_axis.m_bin_width;
a_c.m_number_of_edges = (unsigned int)a_axis.m_edges.size();
a_c.m_edges = cmem_alloc_copy<TC>(vec_data(a_axis.m_edges),a_axis.m_edges.size());
return a_cp;
}
inline void caxis_dui_free(caxis_dui*& a_cp) {
if(!a_cp) return;
caxis_dui& a_c = *a_cp;
cmem_free(a_c.m_edges);
a_c.m_offset = 0;
a_c.m_number_of_bins = 0;
a_c.m_minimum_value = 0;
a_c.m_maximum_value = 0;
a_c.m_fixed = 1;
a_c.m_bin_width = 0;
a_c.m_number_of_edges = 0;
cmem_free(a_cp);
}
inline void chisto_duiuid_assign(chisto_duiuid& a_c,const histo_data<double,unsigned int,unsigned int,double>& a_hd) {
typedef double TC;
typedef unsigned int TN;
typedef double TW;
a_c.m_title = str_dup(a_hd.m_title.c_str());
a_c.m_dimension = a_hd.m_dimension;
a_c.m_bin_number = a_hd.m_bin_number;
a_c.m_bin_entries = cmem_alloc_copy<TN>(vec_data(a_hd.m_bin_entries),a_hd.m_bin_number);
a_c.m_bin_Sw = cmem_alloc_copy<TW>(vec_data(a_hd.m_bin_Sw),a_hd.m_bin_number);
a_c.m_bin_Sw2 = cmem_alloc_copy<TW>(vec_data(a_hd.m_bin_Sw2),a_hd.m_bin_number);
{a_c.m_bin_Sxw = cmem_alloc<TC*>(a_hd.m_bin_number);
for(unsigned int ibin=0;ibin<a_hd.m_bin_number;ibin++) {
a_c.m_bin_Sxw[ibin] = cmem_alloc_copy<TC>(vec_data(a_hd.m_bin_Sxw[ibin]),a_hd.m_dimension);
}}
{a_c.m_bin_Sx2w = cmem_alloc<TC*>(a_hd.m_bin_number);
for(unsigned int ibin=0;ibin<a_hd.m_bin_number;ibin++) {
a_c.m_bin_Sx2w[ibin] = cmem_alloc_copy<TC>(vec_data(a_hd.m_bin_Sx2w[ibin]),a_hd.m_dimension);
}}
// Axes :
{a_c.m_axes = cmem_alloc<caxis_dui*>(a_hd.m_dimension);
for(unsigned int iaxis=0;iaxis<a_hd.m_dimension;iaxis++) {
a_c.m_axes[iaxis] = caxis_dui_alloc(a_hd.m_axes[iaxis]);
}}
// etc :
a_c.m_in_range_plane_Sxyw = cmem_alloc_copy<TC>(vec_data(a_hd.m_in_range_plane_Sxyw),dim_planes(a_hd.m_dimension));
{a_c.m_number_of_annotations = (unsigned int)a_hd.m_annotations.size();
a_c.m_annotations = cmem_alloc<char*>(2*a_hd.m_annotations.size());
unsigned int index = 0;
tools_mforcit(std::string,std::string,a_hd.m_annotations,it) {
a_c.m_annotations[index] = str_dup((*it).first.c_str());index++;
a_c.m_annotations[index] = str_dup((*it).second.c_str());index++;
}}
// fast getters :
a_c.m_all_entries = a_hd.m_all_entries;
a_c.m_in_range_entries = a_hd.m_in_range_entries;
a_c.m_in_range_Sw = a_hd.m_in_range_Sw;
a_c.m_in_range_Sw2 = a_hd.m_in_range_Sw2;
a_c.m_in_range_Sxw = cmem_alloc_copy<TC>(vec_data(a_hd.m_in_range_Sxw),a_hd.m_dimension);
a_c.m_in_range_Sx2w = cmem_alloc_copy<TC>(vec_data(a_hd.m_in_range_Sx2w),a_hd.m_dimension);
//FIXME : should check all sub pointers.
//if(to_del {cmem_free(a_cp);return NULL;}
}
inline chisto_duiuid* chisto_duiuid_alloc(const histo_data<double,unsigned int,unsigned int,double>& a_hd) {
chisto_duiuid* a_cp = cmem_alloc<chisto_duiuid>(1);
if(!a_cp) return NULL;
chisto_duiuid_assign(*a_cp,a_hd);
return a_cp;
}
inline void chisto_duiuid_clear(chisto_duiuid& a_c) {
str_del(a_c.m_title);
cmem_free(a_c.m_bin_entries);
cmem_free(a_c.m_bin_Sw);
cmem_free(a_c.m_bin_Sw2);
{for(unsigned int ibin=0;ibin<a_c.m_bin_number;ibin++) cmem_free(a_c.m_bin_Sxw[ibin]);
cmem_free(a_c.m_bin_Sxw);}
{for(unsigned int ibin=0;ibin<a_c.m_bin_number;ibin++) cmem_free(a_c.m_bin_Sx2w[ibin]);
cmem_free(a_c.m_bin_Sx2w);}
cmem_free(a_c.m_in_range_plane_Sxyw);
{for(unsigned int iaxis=0;iaxis<a_c.m_dimension;iaxis++) caxis_dui_free(a_c.m_axes[iaxis]);
cmem_free(a_c.m_axes);}
{for(unsigned int i=0;i<(2*a_c.m_number_of_annotations);i++) str_del(a_c.m_annotations[i]);
cmem_free(a_c.m_annotations);}
cmem_free(a_c.m_in_range_Sxw);
cmem_free(a_c.m_in_range_Sx2w);
a_c.m_dimension = 0;
a_c.m_bin_number = 0;
a_c.m_number_of_annotations = 0;
a_c.m_all_entries = 0;
a_c.m_in_range_entries = 0;
a_c.m_in_range_Sw = 0;
a_c.m_in_range_Sw2 = 0;
}
inline void chisto_duiuid_free(chisto_duiuid*& a_cp) {
if(!a_cp) return;
chisto_duiuid_clear(*a_cp);
cmem_free(a_cp);
}
/////////////////////////////////////////////////////////////////////////////
/// C struct to hist_data ///////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
template <class T>
inline void vec_assign(std::vector<T>& a_v,unsigned int a_number,const T* a_c) {
a_v.resize(a_number);
for(unsigned int i=0;i<a_number;i++) a_v[i] = a_c[i];
}
inline void axis_dui_assign(axis<double,unsigned int>& a_axis,const caxis_dui& a_c) {
a_axis.m_offset = a_c.m_offset;
a_axis.m_number_of_bins = a_c.m_number_of_bins;
a_axis.m_minimum_value = a_c.m_minimum_value;
a_axis.m_maximum_value = a_c.m_maximum_value;
a_axis.m_fixed = a_c.m_fixed==1?true:false;
a_axis.m_bin_width = a_c.m_bin_width;
vec_assign(a_axis.m_edges,a_c.m_number_of_edges,a_c.m_edges);
}
inline void histo_data_duiuid_assign(histo_data<double,unsigned int,unsigned int,double>& a_hd,const chisto_duiuid& a_c) {
a_hd.m_title = std::string(a_c.m_title);
a_hd.m_dimension = a_c.m_dimension;
a_hd.m_bin_number = a_c.m_bin_number;
vec_assign(a_hd.m_bin_entries,a_c.m_bin_number,a_c.m_bin_entries);
vec_assign(a_hd.m_bin_Sw,a_c.m_bin_number,a_c.m_bin_Sw);
vec_assign(a_hd.m_bin_Sw2,a_c.m_bin_number,a_c.m_bin_Sw2);
{a_hd.m_bin_Sxw.resize(a_c.m_bin_number);
for(unsigned int ibin=0;ibin<a_c.m_bin_number;ibin++) {
vec_assign(a_hd.m_bin_Sxw[ibin],a_c.m_dimension,a_c.m_bin_Sxw[ibin]);
}}
{a_hd.m_bin_Sx2w.resize(a_c.m_bin_number);
for(unsigned int ibin=0;ibin<a_c.m_bin_number;ibin++) {
vec_assign(a_hd.m_bin_Sx2w[ibin],a_c.m_dimension,a_c.m_bin_Sx2w[ibin]);
}}
{a_hd.m_axes.resize(a_c.m_dimension);
for(unsigned int iaxis=0;iaxis<a_c.m_dimension;iaxis++) {
axis_dui_assign(a_hd.m_axes[iaxis],*(a_c.m_axes[iaxis]));
}}
vec_assign(a_hd.m_in_range_plane_Sxyw,dim_planes(a_c.m_dimension),a_c.m_in_range_plane_Sxyw);
{a_hd.m_annotations.clear();
for(unsigned int i=0;i<a_c.m_number_of_annotations;i++) {
a_hd.m_annotations[a_c.m_annotations[2*i+0]] = a_c.m_annotations[2*i+1];
}}
a_hd.m_all_entries = a_c.m_all_entries;
a_hd.m_in_range_entries = a_c.m_in_range_entries;
a_hd.m_in_range_Sw = a_c.m_in_range_Sw;
a_hd.m_in_range_Sw2 = a_c.m_in_range_Sw2;
vec_assign(a_hd.m_in_range_Sxw,a_c.m_dimension,a_c.m_in_range_Sxw);
vec_assign(a_hd.m_in_range_Sx2w,a_c.m_dimension,a_c.m_in_range_Sx2w);
}
}}
#include "profile_data"
namespace tools {
namespace histo {
/////////////////////////////////////////////////////////////////////////////
/// profile_data to C struct ////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
inline cprofile_duiuidd* cprofile_duiuidd_alloc(const profile_data<double,unsigned int,unsigned int,double,double>& a_pd) {
cprofile_duiuidd* a_cp = cmem_alloc<cprofile_duiuidd>(1);
if(!a_cp) return NULL;
cprofile_duiuidd& a_c = *a_cp;
chisto_duiuid_assign(a_c.m_histo,a_pd);
typedef double TV;
// profile part :
a_c.m_is_profile = a_pd.m_is_profile?1:0;
a_c.m_bin_Svw = cmem_alloc_copy<TV>(vec_data(a_pd.m_bin_Svw),a_pd.m_bin_number);
a_c.m_bin_Sv2w = cmem_alloc_copy<TV>(vec_data(a_pd.m_bin_Sv2w),a_pd.m_bin_number);
a_c.m_cut_v = a_pd.m_cut_v?1:0;
a_c.m_min_v = a_pd.m_min_v;
a_c.m_max_v = a_pd.m_max_v;
return a_cp;
}
inline void cprofile_duiuidd_free(cprofile_duiuidd*& a_cp) {
if(!a_cp) return;
cprofile_duiuidd& a_c = *a_cp;
chisto_duiuid_clear(a_c.m_histo);
cmem_free(a_c.m_bin_Svw);
cmem_free(a_c.m_bin_Sv2w);
a_c.m_is_profile = 1;
a_c.m_cut_v = 0;
a_c.m_min_v = 0;
a_c.m_max_v = 0;
cmem_free(a_cp);
}
/////////////////////////////////////////////////////////////////////////////
/// C struct to profile_data ////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
inline void profile_data_duiuidd_assign(profile_data<double,unsigned int,unsigned int,double,double>& a_pd,const cprofile_duiuidd& a_c) {
histo_data_duiuid_assign(a_pd,a_c.m_histo);
a_pd.m_is_profile = a_c.m_is_profile==1?true:false;
vec_assign(a_pd.m_bin_Svw,a_c.m_histo.m_bin_number,a_c.m_bin_Svw);
vec_assign(a_pd.m_bin_Sv2w,a_c.m_histo.m_bin_number,a_c.m_bin_Sv2w);
a_pd.m_cut_v = a_c.m_cut_v==1?true:false;
a_pd.m_min_v = a_c.m_min_v;
a_pd.m_max_v = a_c.m_max_v;
}
}}
#endif
-509
View File
@@ -1,509 +0,0 @@
// Copyright (C) 2010, Guy Barrand. All rights reserved.
// See the file tools.license for terms.
#ifndef tools_histo_slice
#define tools_histo_slice
#include "axis"
namespace tools {
namespace histo {
/////////////////////////////////////////////////////////////////////////////////
/// h2 -> h1 ////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////
template <class H2,class H1>
inline bool fill_slice_x(const H2& a_from,int aJbeg,int aJend,H1& a_to) {
if(!a_from.dimension()) return false;
typedef typename H2::bn_t bn_t;
bn_t jbeg;
if(!a_from.axis_y().in_range_to_absolute_index(aJbeg,jbeg)) return false;
bn_t jend;
if(!a_from.axis_y().in_range_to_absolute_index(aJend,jend)) return false;
if(jbeg>jend) return false;
if(a_from.axis_x().bins()!=a_to.axis().bins()) return false;
typedef typename H1::hd_t hd_t;
hd_t hdata = a_to.dac();
bn_t aoffset,offset,jbin;
bn_t yoffset = a_from.axis_y().m_offset;
typedef typename H2::num_entries_t TN;
typedef typename H2::weight_t TW;
typedef typename H2::coordinate_t TC;
const std::vector<TN>& af_bin_entries = a_from.bins_entries();
const std::vector<TW>& af_bin_Sw = a_from.bins_sum_w();
const std::vector<TW>& af_bin_Sw2 = a_from.bins_sum_w2();
const std::vector< std::vector<TC> >& af_bin_Sxw = a_from.bins_sum_xw();
const std::vector< std::vector<TC> >& af_bin_Sx2w = a_from.bins_sum_x2w();
// Fill also the outflow.
bn_t abins = hdata.m_axes[0].bins()+2;
for(bn_t aibin=0;aibin<abins;aibin++) {
//offset1D = ibin
aoffset = aibin;
for(jbin=jbeg;jbin<=jend;jbin++) {
//offset2D = ibin + jbin * yoffset
// hdata booked with x then :
offset = aibin + jbin * yoffset;
// Bin :
hdata.m_bin_entries[aoffset] += af_bin_entries[offset];
hdata.m_bin_Sw[aoffset] += af_bin_Sw[offset];
hdata.m_bin_Sw2[aoffset] += af_bin_Sw2[offset];
hdata.m_bin_Sxw[aoffset][0] += af_bin_Sxw[offset][0];
hdata.m_bin_Sx2w[aoffset][0] += af_bin_Sx2w[offset][0];
}
}
hdata.m_in_range_plane_Sxyw.assign(a_to.number_of_planes(),0); //ill-defined.
hdata.update_fast_getters();
a_to.copy_from_data(hdata);
return true;
}
template <class H2,class H1>
inline H1* slice_x(const H2& a_from,int aJbeg,int aJend,const std::string& a_title) {
H1* slice = new H1(a_title,a_from.axis_x().bins(),a_from.axis_x().lower_edge(),a_from.axis_x().upper_edge());
if(!fill_slice_x(a_from,aJbeg,aJend,*slice)) {delete slice;return 0;}
return slice;
}
template <class H2,class H1>
inline H1* projection_x(const H2& a_from,const std::string& a_title) {
return slice_x(a_from,axis_UNDERFLOW_BIN,axis_OVERFLOW_BIN,a_title);
}
template <class H2,class H1>
inline bool fill_slice_y(const H2& a_from,int aIbeg,int aIend,H1& a_to) {
if(!a_from.dimension()) return false;
typedef typename H2::bn_t bn_t;
bn_t ibeg;
if(!a_from.axis_x().in_range_to_absolute_index(aIbeg,ibeg)) return false;
bn_t iend;
if(!a_from.axis_x().in_range_to_absolute_index(aIend,iend)) return false;
if(ibeg>iend) return false;
if(a_from.axis_y().bins()!=a_to.axis().bins()) return false;
typedef typename H1::hd_t hd_t;
hd_t hdata = a_to.dac();
bn_t aibin,aoffset,offset,ibin;
bn_t yoffset = a_from.axis_y().m_offset;
typedef typename H2::num_entries_t TN;
typedef typename H2::weight_t TW;
typedef typename H2::coordinate_t TC;
const std::vector<TN>& af_bin_entries = a_from.bins_entries();
const std::vector<TW>& af_bin_Sw = a_from.bins_sum_w();
const std::vector<TW>& af_bin_Sw2 = a_from.bins_sum_w2();
const std::vector< std::vector<TC> >& af_bin_Sxw = a_from.bins_sum_xw();
const std::vector< std::vector<TC> >& af_bin_Sx2w = a_from.bins_sum_x2w();
// Fill also the outflow.
bn_t abins = hdata.m_axes[0].bins()+2;
for(aibin=0;aibin<abins;aibin++) {
//offset1D = ibin
aoffset = aibin;
for(ibin=ibeg;ibin<=iend;ibin++) {
//offset2D = ibin + jbin * yoffset
// hdata booked with y then :
offset = ibin + aibin * yoffset;
// Bin :
hdata.m_bin_entries[aoffset] += af_bin_entries[offset];
hdata.m_bin_Sw[aoffset] += af_bin_Sw[offset];
hdata.m_bin_Sw2[aoffset] += af_bin_Sw2[offset];
hdata.m_bin_Sxw[aoffset][0] += af_bin_Sxw[offset][1];
hdata.m_bin_Sx2w[aoffset][0] += af_bin_Sx2w[offset][1];
}
}
hdata.m_in_range_plane_Sxyw.assign(a_to.number_of_planes(),0); //ill-defined.
hdata.update_fast_getters();
a_to.copy_from_data(hdata);
return true;
}
template <class H2,class H1>
inline H1* slice_y(const H2& a_from,int aIbeg,int aIend,const std::string& a_title) {
H1* slice = new H1(a_title,a_from.axis_y().bins(),a_from.axis_y().lower_edge(),a_from.axis_y().upper_edge());
if(!fill_slice_y(a_from,aIbeg,aIend,*slice)) {delete slice;return 0;}
return slice;
}
template <class H2,class H1>
inline H1* projection_y(const H2& a_from,const std::string& a_title) {
return slice_y(a_from,axis_UNDERFLOW_BIN,axis_OVERFLOW_BIN,a_title);
}
/////////////////////////////////////////////////////////////////////////////////
/// h2 -> p1 ////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////
template <class H2,class P1>
inline bool fill_profile_x(const H2& a_from,int aJbeg,int aJend,P1& a_to) {
if(!a_from.dimension()) return false;
typedef typename H2::bn_t bn_t;
bn_t jbeg;
if(!a_from.axis_y().in_range_to_absolute_index(aJbeg,jbeg)) return false;
bn_t jend;
if(!a_from.axis_y().in_range_to_absolute_index(aJend,jend)) return false;
if(jbeg>jend) return false;
if(a_from.axis_x().bins()!=a_to.axis().bins()) return false;
typedef typename P1::pd_t pd_t;
pd_t hdata = a_to.get_histo_data();
bn_t aoffset,offset,jbin;
bn_t yoffset = a_from.axis_y().m_offset;
typedef typename H2::num_entries_t TN;
typedef typename H2::weight_t TW;
typedef typename H2::coordinate_t TC;
const std::vector<TN>& af_bin_entries = a_from.bins_entries();
const std::vector<TW>& af_bin_Sw = a_from.bins_sum_w();
const std::vector<TW>& af_bin_Sw2 = a_from.bins_sum_w2();
const std::vector< std::vector<TC> >& af_bin_Sxw = a_from.bins_sum_xw();
const std::vector< std::vector<TC> >& af_bin_Sx2w = a_from.bins_sum_x2w();
// Fill also the outflow.
bn_t abins = hdata.m_axes[0].bins()+2;
for(bn_t aibin=0;aibin<abins;aibin++) {
//offset1D = ibin
aoffset = aibin;
for(jbin=jbeg;jbin<=jend;jbin++) {
//offset2D = ibin + jbin * yoffset
// hdata booked with x then :
offset = aibin + jbin * yoffset;
// Bin :
hdata.m_bin_entries[aoffset] += af_bin_entries[offset];
hdata.m_bin_Sw[aoffset] += af_bin_Sw[offset];
hdata.m_bin_Sw2[aoffset] += af_bin_Sw2[offset];
hdata.m_bin_Sxw[aoffset][0] += af_bin_Sxw[offset][0];
hdata.m_bin_Sx2w[aoffset][0] += af_bin_Sx2w[offset][0];
hdata.m_bin_Svw[aoffset] += af_bin_Sxw[offset][1];
hdata.m_bin_Sv2w[aoffset] += af_bin_Sx2w[offset][1];
}
}
hdata.m_in_range_plane_Sxyw.assign(a_to.number_of_planes(),0); //ill-defined.
hdata.update_fast_getters();
a_to.copy_from_data(hdata);
return true;
}
template <class H2,class P1>
inline bool fill_profile_y(const H2& a_from,int aIbeg,int aIend,P1& a_to) {
if(!a_from.dimension()) return false;
typedef typename H2::bn_t bn_t;
bn_t ibeg;
if(!a_from.axis_x().in_range_to_absolute_index(aIbeg,ibeg)) return false;
bn_t iend;
if(!a_from.axis_x().in_range_to_absolute_index(aIend,iend)) return false;
if(ibeg>iend) return false;
if(a_from.axis_y().bins()!=a_to.axis().bins()) return false;
typedef typename P1::pd_t pd_t;
pd_t hdata = a_to.get_histo_data();
bn_t aibin,aoffset,offset,ibin;
bn_t yoffset = a_from.axis_y().m_offset;
typedef typename H2::num_entries_t TN;
typedef typename H2::weight_t TW;
typedef typename H2::coordinate_t TC;
const std::vector<TN>& af_bin_entries = a_from.bins_entries();
const std::vector<TW>& af_bin_Sw = a_from.bins_sum_w();
const std::vector<TW>& af_bin_Sw2 = a_from.bins_sum_w2();
const std::vector< std::vector<TC> >& af_bin_Sxw = a_from.bins_sum_xw();
const std::vector< std::vector<TC> >& af_bin_Sx2w = a_from.bins_sum_x2w();
// Fill also the outflow.
bn_t abins = hdata.m_axes[0].bins()+2;
for(aibin=0;aibin<abins;aibin++) {
//offset1D = ibin
aoffset = aibin;
for(ibin=ibeg;ibin<=iend;ibin++) {
//offset2D = ibin + jbin * yoffset
// hdata booked with y then :
offset = ibin + aibin * yoffset;
// Bin :
hdata.m_bin_entries[aoffset] += af_bin_entries[offset];
hdata.m_bin_Sw[aoffset] += af_bin_Sw[offset];
hdata.m_bin_Sw2[aoffset] += af_bin_Sw2[offset];
hdata.m_bin_Sxw[aoffset][0] += af_bin_Sxw[offset][1];
hdata.m_bin_Sx2w[aoffset][0] += af_bin_Sx2w[offset][1];
hdata.m_bin_Svw[aoffset] += af_bin_Sxw[offset][0];
hdata.m_bin_Sv2w[aoffset] += af_bin_Sx2w[offset][0];
}
}
hdata.m_in_range_plane_Sxyw.assign(a_to.number_of_planes(),0); //ill-defined.
hdata.update_fast_getters();
a_to.copy_from_data(hdata);
return true;
}
/////////////////////////////////////////////////////////////////////////////////
/// h3 -> h2 ////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////
template <class H3,class H2>
inline bool fill_slice_yz(const H3& a_from,int aIbeg,int aIend,H2& a_to) {
if(!a_from.dimension()) return false;
typedef typename H3::bn_t bn_t;
bn_t ibeg;
if(!a_from.axis_x().in_range_to_absolute_index(aIbeg,ibeg)) return false;
bn_t iend;
if(!a_from.axis_x().in_range_to_absolute_index(aIend,iend)) return false;
if(ibeg>iend) return false;
if(a_from.axis_y().bins()!=a_to.axis_x().bins()) return false;
if(a_from.axis_z().bins()!=a_to.axis_y().bins()) return false;
typedef typename H2::hd_t hd_t;
hd_t hdata = a_to.dac();
bn_t aibin,ajbin,aoffset,offset,ibin;
bn_t ayoffset = hdata.m_axes[1].m_offset;
bn_t yoffset = a_from.axis_y().m_offset;
bn_t zoffset = a_from.axis_z().m_offset;
bn_t axbins = hdata.m_axes[0].bins()+2;
bn_t aybins = hdata.m_axes[1].bins()+2;
typedef typename H3::num_entries_t TN;
typedef typename H3::weight_t TW;
typedef typename H3::coordinate_t TC;
const std::vector<TN>& af_bin_entries = a_from.bins_entries();
const std::vector<TW>& af_bin_Sw = a_from.bins_sum_w();
const std::vector<TW>& af_bin_Sw2 = a_from.bins_sum_w2();
const std::vector< std::vector<TC> >& af_bin_Sxw = a_from.bins_sum_xw();
const std::vector< std::vector<TC> >& af_bin_Sx2w = a_from.bins_sum_x2w();
// Fill also the outflow.
for(aibin=0;aibin<axbins;aibin++) {
for(ajbin=0;ajbin<aybins;ajbin++) {
//offset2D = ibin + jbin * m_axes[1].m_offset
aoffset = aibin + ajbin * ayoffset;
for(ibin=ibeg;ibin<=iend;ibin++) {
//offset3D = ibin + jbin * m_axes[1].m_offset + kbin*m_axes[2].m_offset;
// hdata booked with y-z then :
offset = ibin + aibin * yoffset + ajbin * zoffset;
// Bin :
hdata.m_bin_entries[aoffset] += af_bin_entries[offset];
hdata.m_bin_Sw[aoffset] += af_bin_Sw[offset];
hdata.m_bin_Sw2[aoffset] += af_bin_Sw2[offset];
hdata.m_bin_Sxw[aoffset][0] += af_bin_Sxw[offset][1];
hdata.m_bin_Sxw[aoffset][1] += af_bin_Sxw[offset][2];
hdata.m_bin_Sx2w[aoffset][0] += af_bin_Sx2w[offset][1];
hdata.m_bin_Sx2w[aoffset][1] += af_bin_Sx2w[offset][2];
}
}
}
hdata.m_in_range_plane_Sxyw.assign(a_to.number_of_planes(),0); //ill-defined.
hdata.update_fast_getters();
a_to.copy_from_data(hdata);
return true;
}
template <class H3,class H2>
inline bool fill_slice_xy(const H3& a_from,int aKbeg,int aKend,H2& a_to) {
if(!a_from.dimension()) return false;
typedef typename H3::bn_t bn_t;
bn_t kbeg;
if(!a_from.axis_z().in_range_to_absolute_index(aKbeg,kbeg)) return false;
bn_t kend;
if(!a_from.axis_z().in_range_to_absolute_index(aKend,kend)) return false;
if(kbeg>kend) return false;
if(a_from.axis_x().bins()!=a_to.axis_x().bins()) return false;
if(a_from.axis_y().bins()!=a_to.axis_y().bins()) return false;
typedef typename H2::hd_t hd_t;
hd_t hdata = a_to.dac();
bn_t kbin;
bn_t aibin,ajbin,aoffset,offset;
bn_t ayoffset = hdata.m_axes[1].m_offset;
bn_t yoffset = a_from.axis_y().m_offset;
bn_t zoffset = a_from.axis_z().m_offset;
bn_t axbins = hdata.m_axes[0].bins()+2;
bn_t aybins = hdata.m_axes[1].bins()+2;
typedef typename H3::num_entries_t TN;
typedef typename H3::weight_t TW;
typedef typename H3::coordinate_t TC;
const std::vector<TN>& af_bin_entries = a_from.bins_entries();
const std::vector<TW>& af_bin_Sw = a_from.bins_sum_w();
const std::vector<TW>& af_bin_Sw2 = a_from.bins_sum_w2();
const std::vector< std::vector<TC> >& af_bin_Sxw = a_from.bins_sum_xw();
const std::vector< std::vector<TC> >& af_bin_Sx2w = a_from.bins_sum_x2w();
// Fill also the outflow.
for(aibin=0;aibin<axbins;aibin++) {
for(ajbin=0;ajbin<aybins;ajbin++) {
//offset2D = ibin + jbin * m_axes[1].m_offset
aoffset = aibin + ajbin * ayoffset;
for(kbin=kbeg;kbin<=kend;kbin++) {
//offset3D = ibin + jbin * m_axes[1].m_offset + kbin*m_axes[2].m_offset;
// hdata booked with x-y then :
offset = aibin + ajbin * yoffset + kbin * zoffset;
// Bin :
hdata.m_bin_entries[aoffset] += af_bin_entries[offset];
hdata.m_bin_Sw[aoffset] += af_bin_Sw[offset];
hdata.m_bin_Sw2[aoffset] += af_bin_Sw2[offset];
hdata.m_bin_Sxw[aoffset][0] += af_bin_Sxw[offset][0];
hdata.m_bin_Sxw[aoffset][1] += af_bin_Sxw[offset][1];
hdata.m_bin_Sx2w[aoffset][0] += af_bin_Sx2w[offset][0];
hdata.m_bin_Sx2w[aoffset][1] += af_bin_Sx2w[offset][1];
}
}
}
hdata.m_in_range_plane_Sxyw.assign(a_to.number_of_planes(),0); //ill-defined.
hdata.update_fast_getters();
a_to.copy_from_data(hdata);
return true;
}
template <class H3,class H2>
inline bool fill_slice_xz(const H3& a_from,int aJbeg,int aJend,H2& a_to) {
if(!a_from.dimension()) return false;
typedef typename H3::bn_t bn_t;
bn_t jbeg;
if(!a_from.axis_y().in_range_to_absolute_index(aJbeg,jbeg)) return false;
bn_t jend;
if(!a_from.axis_y().in_range_to_absolute_index(aJend,jend)) return false;
if(jbeg>jend) return false;
if(a_from.axis_x().bins()!=a_to.axis_x().bins()) return false;
if(a_from.axis_z().bins()!=a_to.axis_y().bins()) return false;
typedef typename H2::hd_t hd_t;
hd_t hdata = a_to.dac();
bn_t aibin,ajbin,aoffset,offset,jbin;
bn_t ayoffset = hdata.m_axes[1].m_offset;
bn_t yoffset = a_from.axis_y().m_offset;
bn_t zoffset = a_from.axis_z().m_offset;
bn_t axbins = hdata.m_axes[0].bins()+2;
bn_t aybins = hdata.m_axes[1].bins()+2;
typedef typename H3::num_entries_t TN;
typedef typename H3::weight_t TW;
typedef typename H3::coordinate_t TC;
const std::vector<TN>& af_bin_entries = a_from.bins_entries();
const std::vector<TW>& af_bin_Sw = a_from.bins_sum_w();
const std::vector<TW>& af_bin_Sw2 = a_from.bins_sum_w2();
const std::vector< std::vector<TC> >& af_bin_Sxw = a_from.bins_sum_xw();
const std::vector< std::vector<TC> >& af_bin_Sx2w = a_from.bins_sum_x2w();
// Fill also the outflow.
for(aibin=0;aibin<axbins;aibin++) {
for(ajbin=0;ajbin<aybins;ajbin++) {
//offset2D = ibin + jbin * m_axes[1].m_offset
aoffset = aibin + ajbin * ayoffset;
for(jbin=jbeg;jbin<=jend;jbin++) {
//offset3D = ibin + jbin * m_axes[1].m_offset + kbin*m_axes[2].m_offset;
// hdata booked with x-z then :
offset = aibin + jbin * yoffset + ajbin * zoffset;
// Bin :
hdata.m_bin_entries[aoffset] += af_bin_entries[offset];
hdata.m_bin_Sw[aoffset] += af_bin_Sw[offset];
hdata.m_bin_Sw2[aoffset] += af_bin_Sw2[offset];
hdata.m_bin_Sxw[aoffset][0] += af_bin_Sxw[offset][0];
hdata.m_bin_Sxw[aoffset][1] += af_bin_Sxw[offset][2];
hdata.m_bin_Sx2w[aoffset][0] += af_bin_Sx2w[offset][0];
hdata.m_bin_Sx2w[aoffset][1] += af_bin_Sx2w[offset][2];
}
}
}
hdata.m_in_range_plane_Sxyw.assign(a_to.number_of_planes(),0); //ill-defined.
hdata.update_fast_getters();
a_to.copy_from_data(hdata);
return true;
}
template <class H3,class H2>
inline H2* slice_xy(const H3& a_from,int aKbeg,int aKend,const std::string& a_title) {
H2* slice = new H2(a_title,
a_from.axis_x().bins(),a_from.axis_x().lower_edge(),a_from.axis_x().upper_edge(),
a_from.axis_y().bins(),a_from.axis_y().lower_edge(),a_from.axis_y().upper_edge());
if(!fill_slice_xy(a_from,aKbeg,aKend,*slice)) {delete slice;return 0;}
return slice;
}
template <class H3,class H2>
inline H2* slice_yz(const H3& a_from,int aIbeg,int aIend,const std::string& a_title) {
H2* slice = new H2(a_title,
a_from.axis_y().bins(),a_from.axis_y().lower_edge(),a_from.axis_y().upper_edge(),
a_from.axis_z().bins(),a_from.axis_z().lower_edge(),a_from.axis_z().upper_edge());
if(!fill_slice_yz(a_from,aIbeg,aIend,*slice)) {delete slice;return 0;}
return slice;
}
template <class H3,class H2>
inline H2* slice_xz(const H3& a_from,int aJbeg,int aJend,const std::string& a_title) {
H2* slice = new H2(a_title,
a_from.axis_x().bins(),a_from.axis_x().lower_edge(),a_from.axis_x().upper_edge(),
a_from.axis_z().bins(),a_from.axis_z().lower_edge(),a_from.axis_z().upper_edge());
if(!fill_slice_xz(a_from,aJbeg,aJend,*slice)) {delete slice;return 0;}
return slice;
}
}}
#endif
-121
View File
@@ -1,121 +0,0 @@
// Copyright (C) 2010, Guy Barrand. All rights reserved.
// See the file tools.license for terms.
#ifndef tools_histo_sliced
#define tools_histo_sliced
#include "slice"
#include "h1d"
#include "h2d"
/////////////////////////////////////////////////////////////////////////////////
/// h2 -> h1 ////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////
namespace tools {
namespace histo {
inline h1d* slice_x(const h2d& a_from,int aJbeg,int aJend,const std::string& a_title) {
h1d* slice_x = new h1d(a_title,
a_from.axis_x().bins(),a_from.axis_x().lower_edge(),a_from.axis_x().upper_edge());
if(!fill_slice_x(a_from,aJbeg,aJend,*slice_x)) {delete slice_x;return 0;}
return slice_x;
}
inline h1d* projection_x(const h2d& a_from,const std::string& a_title) {
return slice_x(a_from,axis_UNDERFLOW_BIN,axis_OVERFLOW_BIN,a_title);
}
inline h1d* slice_y(const h2d& a_from,int aIbeg,int aIend,const std::string& a_title) {
h1d* slice_y = new h1d(a_title,
a_from.axis_y().bins(),a_from.axis_y().lower_edge(),a_from.axis_y().upper_edge());
if(!fill_slice_y(a_from,aIbeg,aIend,*slice_y)) {delete slice_y;return 0;}
return slice_y;
}
inline h1d* projection_y(const h2d& a_from,const std::string& a_title) {
return slice_y(a_from,axis_UNDERFLOW_BIN,axis_OVERFLOW_BIN,a_title);
}
}}
/////////////////////////////////////////////////////////////////////////////////
/// h2 -> p1 ////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////
#include "p1d"
namespace tools {
namespace histo {
inline p1d* profile_x(const h2d& a_from,int aJbeg,int aJend,const std::string& a_title) {
p1d* slice_x = new p1d(a_title,
a_from.axis_x().bins(),a_from.axis_x().lower_edge(),a_from.axis_x().upper_edge());
if(!fill_profile_x(a_from,aJbeg,aJend,*slice_x)) {delete slice_x;return 0;}
return slice_x;
}
inline p1d* profile_x(const h2d& a_from,const std::string& a_title) {
return profile_x(a_from,axis_UNDERFLOW_BIN,axis_OVERFLOW_BIN,a_title);
}
inline p1d* profile_y(const h2d& a_from,int aIbeg,int aIend,const std::string& a_title) {
p1d* slice_y = new p1d(a_title,
a_from.axis_y().bins(),a_from.axis_y().lower_edge(),a_from.axis_y().upper_edge());
if(!fill_profile_y(a_from,aIbeg,aIend,*slice_y)) {delete slice_y;return 0;}
return slice_y;
}
inline p1d* profile_y(const h2d& a_from,const std::string& a_title) {
return profile_y(a_from,axis_UNDERFLOW_BIN,axis_OVERFLOW_BIN,a_title);
}
}}
/////////////////////////////////////////////////////////////////////////////////
/// h3 -> h2 ////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////
#include "h3d"
namespace tools {
namespace histo {
inline h2d* slice_xy(const h3d& a_from,int aKbeg,int aKend,const std::string& a_title) {
h2d* slice = new h2d(a_title,
a_from.axis_x().bins(),a_from.axis_x().lower_edge(),a_from.axis_x().upper_edge(),
a_from.axis_y().bins(),a_from.axis_y().lower_edge(),a_from.axis_y().upper_edge());
if(!fill_slice_xy(a_from,aKbeg,aKend,*slice)) {delete slice;return 0;}
return slice;
}
inline h2d* projection_xy(const h3d& a_from,const std::string& a_title) {
return slice_xy(a_from,axis_UNDERFLOW_BIN,axis_OVERFLOW_BIN,a_title);
}
inline h2d* slice_yz(const h3d& a_from,int aIbeg,int aIend,const std::string& a_title) {
h2d* slice = new h2d(a_title,
a_from.axis_y().bins(),a_from.axis_y().lower_edge(),a_from.axis_y().upper_edge(),
a_from.axis_z().bins(),a_from.axis_z().lower_edge(),a_from.axis_z().upper_edge());
if(!fill_slice_yz(a_from,aIbeg,aIend,*slice)) {delete slice;return 0;}
return slice;
}
inline h2d* projection_yz(const h3d& a_from,const std::string& a_title) {
return slice_yz(a_from,axis_UNDERFLOW_BIN,axis_OVERFLOW_BIN,a_title);
}
inline h2d* slice_xz(const h3d& a_from,int aJbeg,int aJend,const std::string& a_title) {
h2d* slice = new h2d(a_title,
a_from.axis_x().bins(),a_from.axis_x().lower_edge(),a_from.axis_x().upper_edge(),
a_from.axis_z().bins(),a_from.axis_z().lower_edge(),a_from.axis_z().upper_edge());
if(!fill_slice_xz(a_from,aJbeg,aJend,*slice)) {delete slice;return 0;}
return slice;
}
inline h2d* projection_xz(const h3d& a_from,const std::string& a_title) {
return slice_xz(a_from,axis_UNDERFLOW_BIN,axis_OVERFLOW_BIN,a_title);
}
}}
#endif
-427
View File
@@ -1,427 +0,0 @@
// Copyright (C) 2010, Guy Barrand. All rights reserved.
// See the file tools.license for terms.
#ifndef tools_image
#define tools_image
#include <vector>
#include <cstring> //memcpy
#include <cstdio> //fopen
#include "forit"
namespace tools {
namespace image {
// give a set of cols*rows same size rgb-image and build
// a big image :
inline unsigned char* concatenate(unsigned char** a_buffers,
unsigned int a_w,unsigned int a_h,
unsigned int a_bpp,
unsigned int a_cols,unsigned int a_rows,
unsigned int a_bw,unsigned int a_bh,
unsigned char a_bc,
unsigned int& a_rw,unsigned int& a_rh){
// assume a_buffers has a_cols*a_rows entries.
// a_buffers[0] is bottom-left
// a_row=0 is bottom.
unsigned int wbw = a_w + 2*a_bw;
unsigned int hbh = a_h + 2*a_bh;
a_rw = wbw * a_cols;
a_rh = hbh * a_rows;
//printf("debug : %d %d\n",a_rw,a_rh);
// on big concatenated image the below may fail :
unsigned char* rb = new unsigned char[a_rh*a_rw*a_bpp];
if(!rb) {a_rw = 0;a_rh = 0;return 0;}
unsigned int wbw3 = wbw*a_bpp;
unsigned int aw3 = a_w*a_bpp;
//copy tiles :
unsigned int index = 0;
for(unsigned int j=0;j<a_rows;j++) {
for(unsigned int i=0;i<a_cols;i++) {
unsigned char* tile = a_buffers[index];
for(unsigned int r=0;r<hbh;r++) {
unsigned char* pos = rb + (j*hbh+r)*a_rw*a_bpp + i*wbw*a_bpp;
::memset(pos,a_bc,wbw3);
}
for(unsigned int r=0;r<a_h;r++) {
unsigned char* pos = rb + (j*hbh+r+a_bh)*a_rw*a_bpp + (i*wbw+a_bw)*a_bpp;
unsigned char* ptile = tile+r*aw3;
for(unsigned int c=0;c<aw3;c++,pos++,ptile++) *pos = *ptile;
}
index++;
}
}
return rb;
}
}}
#include <ostream>
#include <string>
namespace tools {
namespace image {
typedef unsigned char* (*file_reader)(std::ostream&,const std::string&,unsigned int&,unsigned int&,unsigned int&);
inline unsigned char* concatenate(std::ostream& a_out,
const std::vector<std::string>& a_files,
unsigned int a_cols,unsigned int a_rows,
unsigned int a_bw,unsigned int a_bh,
unsigned char a_bc,
file_reader a_file_reader,
unsigned int& a_w,unsigned int& a_h,
unsigned int& a_bpp) {
// a_files[0] is cols=0, rows=0
// a_files[1] is cols=1, rows=0
// a_files[2] is cols=2, rows=0
// ...
// and row=0 is bottom of big image.
unsigned int number = a_cols*a_rows;
if(number!=a_files.size()) {
a_out << "tools::image::concatenate :"
<< " bad number of files. " << number << " expected."
<< std::endl;
a_bpp = a_w = a_h = 0;
return 0;
}
if(a_files.empty()) {
a_out << "tools::image::concatenate :"
<< " list of files is empty."
<< std::endl;
a_bpp = a_w = a_h = 0;
return 0;
}
unsigned int w1 = 0;
unsigned int h1 = 0;
unsigned int bpp1 = 0;
typedef unsigned char* buffer_t;
buffer_t* bs = new buffer_t[number];
{for(unsigned int i=0;i<number;i++) {bs[i] = 0;}}
bool read_failed = false;
unsigned int index = 0;
for(unsigned int j=0;j<a_rows;j++) {
for(unsigned int i=0;i<a_cols;i++) {
const std::string& file = a_files[index];
unsigned int w,h,bpp;
unsigned char* b = a_file_reader(a_out,file,w,h,bpp);
if(!b) {
a_out << "tools::image::concatenate :"
<< " can't read " << file << " expected."
<< std::endl;
read_failed = true;
break;
}
if(!index) {
w1 = w;
h1 = h;
bpp1 = bpp;
} else {
if(w!=w1) {
a_out << "tools::image::concatenate :"
<< " file " << file
<< " does not have same width image as the first file one."
<< " (" << w << "," << w1 << ")."
<< std::endl;
delete [] b;
read_failed = true;
break;
}
if(h!=h1) {
a_out << "tools::image::concatenate :"
<< " file " << file
<< " does not have same height image as the first file one."
<< " (" << h << "," << h1 << ")."
<< std::endl;
delete [] b;
read_failed = true;
break;
}
if(bpp!=bpp1) {
a_out << "tools::image::concatenate :"
<< " file " << file
<< " does not have same bytes per pixel as the first file one."
<< " (" << h << "," << h1 << ")."
<< std::endl;
delete [] b;
read_failed = true;
break;
}
}
bs[index] = b;
index++;
}
if(read_failed) break;
}
if(read_failed) {
{for(unsigned int i=0;i<number;i++) {delete [] bs[i];}}
a_bpp = a_w = a_h = 0;
return 0;
}
unsigned int wa,ha;
unsigned char* ba = image::concatenate(bs,w1,h1,bpp1,a_cols,a_rows,a_bw,a_bh,a_bc,wa,ha);
if(!ba) {
a_out << "tools::image::concatenate :"
<< " failed to concatenate all buffers."
<< std::endl;
{for(unsigned int i=0;i<number;i++) {delete [] bs[i];}}
a_bpp = a_w = a_h = 0;
return 0;
}
{for(unsigned int i=0;i<number;i++) {delete [] bs[i];}}
a_w = wa;
a_h = ha;
a_bpp = bpp1;
return ba;
}
typedef unsigned char* (*reader)(FILE*,unsigned int&,unsigned int&);
typedef bool(*writer)(FILE*,unsigned char*,unsigned int,unsigned int);
inline bool convert(std::ostream& a_out,
const std::string& a_sin,
reader a_reader,
const std::string& a_sout,
writer a_writer){
FILE* fin = ::fopen(a_sin.c_str(),"rb");
if(!fin) {
a_out << "tools::image::convert :"
<< " can't open " << a_sin
<< std::endl;
return false;
}
unsigned int w,h;
unsigned char* b = a_reader(fin,w,h);
if(!b) {
a_out << "tools::image::convert :"
<< " can't read " << a_sin
<< std::endl;
::fclose(fin);
return false;
}
::fclose(fin);
FILE* fout = ::fopen(a_sout.c_str(),"wb");
if(!fout) {
a_out << "tools::image::convert :"
<< " can't open " << a_sout
<< std::endl;
delete [] b;
return false;
}
if(!a_writer(fout,b,w,h)) {
a_out << "tools::image::convert :"
<< " can't write " << a_sout
<< std::endl;
::fclose(fout);
delete [] b;
return false;
}
::fclose(fout);
delete [] b;
return true;
}
}}
#include "image_reader"
#include "sout"
#include "S_STRING"
#ifdef TOOLS_MEM
#include "mem"
#endif
namespace tools {
namespace image {
class iterator {
public:
TOOLS_SCLASS(tools::image::iterator)
public:
virtual ~iterator(){}
public:
virtual unsigned int entries() const = 0;
virtual bool next() = 0;
virtual bool rewind() = 0;
public:
virtual unsigned int index() const = 0;
virtual unsigned char* read_image(unsigned int& a_w,unsigned int& a_h,
unsigned int& a_bpp) = 0;
};
class iterator_reader : public virtual iterator {
public:
TOOLS_SCLASS(tools::image::iterator_reader)
public:
//still virtual :
//virtual unsigned int entries() const = 0;
//virtual bool next() = 0;
//virtual bool rewind() = 0;
//virtual unsigned int index() const = 0;
virtual unsigned char* read_image(unsigned int& a_w,unsigned int& a_h,
unsigned int& a_bpp) {
std::string file;
if(begin_file(file)) {
tools_vforcit(image::ireader*,m_readers,it) {
if((*it)->is(file)) {
unsigned char* buffer = _open(*(*it),file,a_w,a_h,a_bpp);
end_file(file);
return buffer;
}
}
end_file(file);
}
a_w = 0;a_h = 0;a_bpp = 0;
return 0;
}
public:
virtual bool begin_file(std::string&) = 0;
virtual bool end_file(const std::string&) = 0;
public:
iterator_reader(std::ostream& a_out,unsigned int a_limit)
:m_out(a_out)
,m_limit(a_limit)
{
#ifdef TOOLS_MEM
mem::increment(s_class().c_str());
#endif
}
virtual ~iterator_reader(){
_clean();
#ifdef TOOLS_MEM
mem::decrement(s_class().c_str());
#endif
}
public:
iterator_reader(const iterator_reader& a_from)
:iterator(a_from)
,m_out(a_from.m_out)
,m_limit(a_from.m_limit)
{
#ifdef TOOLS_MEM
mem::increment(s_class().c_str());
#endif
_copy(a_from.m_readers);
}
iterator_reader& operator=(const iterator_reader& a_from){
if(&a_from==this) return *this;
m_limit = a_from.m_limit;
_copy(a_from.m_readers);
return *this;
}
public:
void add_reader(ireader* a_reader) {
m_readers.push_back(a_reader); //take ownership.
}
protected:
unsigned char* _open(const image::ireader& a_reader,
const std::string& a_path,
unsigned int& a_w,unsigned int& a_h,
unsigned int& a_bpp){
// permit to put in common code for jpeg and png.
unsigned char* buffer = 0;
if(m_limit) {
if(!a_reader.infos(m_out,a_path,a_w,a_h,a_bpp)) {
m_out << "tools::image::iterator_reader::_open :"
<< " for file " << sout(a_path)
<< " ireader::infos failed."
<< std::endl;
a_w = 0;a_h = 0;a_bpp = 0;
return 0;
}
if((a_w*a_h*a_bpp)>m_limit) {
//unsigned int sw;
//unsigned int sh;
//float aspect = float(w)/float(h);
//if(aspect>=1) {
// sh = 2;
// sw = aspect*sh;
//} else {
// sw = 2;
// sh = sw/aspect;
//}
unsigned int sw = 2;
unsigned int sh = 2;
while(true) {
if(((2*sw)*(2*sh)*a_bpp)>m_limit) break;
sw *=2;
sh *=2;
}
unsigned int sx = (a_w-sw)/2;
unsigned int sy = (a_h-sh)/2;
buffer = a_reader.read_part
(m_out,a_path,sx,sy,sw,sh,a_w,a_h,a_bpp);
} else {
buffer = a_reader.read(m_out,a_path,a_w,a_h,a_bpp);
}
} else {
buffer = a_reader.read(m_out,a_path,a_w,a_h,a_bpp);
}
if(!buffer) {
m_out << "tools::image::iterator_reader::_open :"
<< " for file " << sout(a_path)
<< " read failed."
<< std::endl;
a_w = 0;a_h = 0;a_bpp = 0;
return 0;
}
return buffer;
}
void _clean() {
std::vector<ireader*>::iterator it;
for(it=m_readers.begin();it!=m_readers.end();) {
ireader* obj = *it;
it = m_readers.erase(it);
delete obj;
}
}
void _copy(const std::vector<ireader*>& a_from) {
_clean();
tools_vforcit(ireader*,a_from,it) m_readers.push_back((*it)->copy());
}
protected:
std::ostream& m_out;
unsigned int m_limit;
std::vector<ireader*> m_readers;
};
}}
#endif
-72
View File
@@ -1,72 +0,0 @@
// Copyright (C) 2010, Guy Barrand. All rights reserved.
// See the file tools.license for terms.
#ifndef tools_image_reader
#define tools_image_reader
#include "forit"
#include <string>
#include <vector>
namespace tools {
namespace image {
class ireader {
public:
virtual ~ireader() {}
public:
virtual ireader* copy() const = 0;
virtual bool is(const std::string&) const = 0;
virtual bool infos(std::ostream& a_out,const std::string& a_file,
unsigned int& a_width,unsigned int& a_height,
unsigned int& a_bpp) const = 0;
virtual unsigned char* read(std::ostream& a_out,const std::string& a_file,
unsigned int& a_width,unsigned int& a_height,
unsigned int& a_bpp) const = 0;
virtual unsigned char* read_part(std::ostream& a_out,
const std::string& a_file,
unsigned int a_sx,unsigned int a_sy,
unsigned int a_sw,unsigned int a_sh,
unsigned int& a_rw,unsigned int& a_rh,
unsigned int& a_rbpp) const = 0;
};
class readers {
public:
typedef std::pair<std::string,ireader*> named_reader;
public:
readers(){}
virtual ~readers(){_clear();}
public:
readers(const readers& a_from) {
_copy(a_from.m_readers);
}
readers& operator=(const readers& a_from){
if(&a_from==this) return *this;
_copy(a_from.m_readers);
return *this;
}
public:
void add_reader(const std::string& a_name,ireader* a_reader) {
m_readers.push_back(named_reader(a_name,a_reader)); //take ownership of a_reader.
}
const std::vector<named_reader>& named_readers() const {return m_readers;}
protected:
void _clear(){
tools_vforit(named_reader,m_readers,it) delete (*it).second;
m_readers.clear();
}
void _copy(const std::vector<named_reader>& a_from) {
_clear();
tools_vforcit(named_reader,a_from,it) {
m_readers.push_back(named_reader((*it).first,(*it).second->copy()));
}
}
protected:
std::vector<named_reader> m_readers; //have a vector (and not a map) since the order is important.
};
}}
#endif
-702
View File
@@ -1,702 +0,0 @@
// Copyright (C) 2010, Guy Barrand. All rights reserved.
// See the file tools.license for terms.
#ifndef tools_jpeg
#define tools_jpeg
#include <cstdio> //FILE,size_t
//#define TOOLS_JPEG_OUT_ERR
extern "C" { //Needed on Windows.
#ifndef TOOLS_USE_OUREX_JPEG
#include <jpeglib.h>
#else
#include <ourex_jpeglib.h> //enforce ourex jpeg
#endif
}
#include <csetjmp>
#include <cstring> //memcpy
#include <tools/mnmx>
namespace tools {
namespace jpeg {
inline bool write_file(FILE* a_file,int a_quality,unsigned char* a_buffer,unsigned int a_width,unsigned int a_height,unsigned int a_bpp) {
struct jpeg_compress_struct cinfo;
struct jpeg_error_mgr jerr;
cinfo.err = ::jpeg_std_error(&jerr);
::jpeg_create_compress(&cinfo);
::jpeg_stdio_dest(&cinfo,a_file);
cinfo.image_width = a_width;
cinfo.image_height = a_height;
cinfo.input_components = a_bpp; // # of color components per pixel.
cinfo.in_color_space = JCS_RGB; // colorspace of input image.
::jpeg_set_defaults(&cinfo);
::jpeg_set_quality(&cinfo,a_quality,TRUE);
::jpeg_start_compress(&cinfo,TRUE);
int row_stride = a_width * cinfo.input_components;
while (cinfo.next_scanline < cinfo.image_height) {
JSAMPROW row_pointer =
a_buffer+(cinfo.image_height-1-cinfo.next_scanline) * row_stride;
::jpeg_write_scanlines(&cinfo, &row_pointer, 1);
}
::jpeg_finish_compress(&cinfo);
::jpeg_destroy_compress(&cinfo);
return true;
}
inline bool write_file_100(FILE* a_file,unsigned char* a_buffer,unsigned int a_width,unsigned int a_height,unsigned int a_bpp) {
return tools::jpeg::write_file(a_file,100,a_buffer,a_width,a_height,a_bpp);
}
struct error_mgr {
struct jpeg_error_mgr pub;
jmp_buf setjmp_buffer;
};
typedef struct error_mgr* error_ptr;
extern "C" {
inline void tools_jpeg_error_exit(j_common_ptr cinfo){
error_ptr myerr = (error_ptr) cinfo->err;
//(*cinfo->err->output_message) (cinfo);
//printf("debug : error_exit\n");
//NSLog(@"debug : jpeg::error_exit");
::longjmp(myerr->setjmp_buffer, 1);
}
}
inline bool infos_file(FILE* a_file,unsigned int& a_width,unsigned int& a_height,unsigned int& a_bpp) {
//NOTE : G.Barrand : not sure that in case of error, we cleanup properly !
struct jpeg_decompress_struct cinfo;
struct error_mgr jerr;
cinfo.err = ::jpeg_std_error(&jerr.pub);
jerr.pub.error_exit = tools_jpeg_error_exit;
if(::setjmp(jerr.setjmp_buffer)) {
//printf("debug : out of setjmp\n");
a_width = 0;
a_height = 0;
a_bpp = 0;
return false;
}
::jpeg_create_decompress(&cinfo);
::jpeg_stdio_src(&cinfo,a_file);
::jpeg_read_header(&cinfo, TRUE);
::jpeg_start_decompress(&cinfo);
a_width = cinfo.output_width;
a_height = cinfo.output_height;
a_bpp = cinfo.output_components;
::jpeg_abort_decompress(&cinfo);
::jpeg_destroy_decompress(&cinfo);
return true;
}
inline unsigned char* read_file(FILE* a_file,unsigned int& a_width,unsigned int& a_height,unsigned int& a_bpp) {
// the returned buffer must be delete with "delete []".
//NOTE : G.Barrand : not sure that in case of error, we cleanup properly !
struct jpeg_decompress_struct cinfo;
struct error_mgr jerr;
cinfo.err = ::jpeg_std_error(&jerr.pub);
jerr.pub.error_exit = tools_jpeg_error_exit;
if(::setjmp(jerr.setjmp_buffer)) {
#ifdef TOOLS_JPEG_OUT_ERR
::printf("tools::jpeg::read_file : out of setjmp\n");
#endif
//NOTE : how to be sure to delete the below new if having been done ?
a_width = 0;
a_height = 0;
a_bpp = 0;
return 0;
}
::jpeg_create_decompress(&cinfo);
::jpeg_stdio_src(&cinfo,a_file);
::jpeg_read_header(&cinfo, TRUE);
::jpeg_start_decompress(&cinfo);
int row_stride = cinfo.output_width * cinfo.output_components;
if((!cinfo.output_width)||
(!cinfo.output_height)||
(cinfo.output_components<=0)) {
#ifdef TOOLS_JPEG_OUT_ERR
::printf("tools::jpeg::read_file : bad size, w %u h %u cpnts %d\n",
cinfo.output_width,cinfo.output_height,cinfo.output_components);
#endif
::jpeg_abort_decompress(&cinfo);
::jpeg_destroy_decompress(&cinfo);
a_width = 0;
a_height = 0;
a_bpp = 0;
return 0;
}
a_width = cinfo.output_width;
a_height = cinfo.output_height;
a_bpp = cinfo.output_components;
unsigned char* image_buffer = new unsigned char[row_stride * cinfo.output_height];
if(!image_buffer) {
#ifdef TOOLS_JPEG_OUT_ERR
::printf("tools::jpeg::read_file : alloc of %d bytes failed\n",
row_stride * cinfo.output_height);
#endif
::jpeg_abort_decompress(&cinfo);
::jpeg_destroy_decompress(&cinfo);
a_width = 0;
a_height = 0;
a_bpp = 0;
return 0;
}
//FIXME : iPad : the below crashes on LHCb_artist_16384_4096_80.jpg.
{JSAMPROW buffer[1];
unsigned char* pos = image_buffer + row_stride * cinfo.output_height;
while (cinfo.output_scanline<cinfo.output_height) {
pos -= row_stride;
buffer[0] = pos;
if(::jpeg_read_scanlines(&cinfo, buffer, 1)!=1) {
#ifdef TOOLS_JPEG_OUT_ERR
::printf("tools::jpeg::read_file : jpeg_read_scanlines failed\n");
#endif
::jpeg_abort_decompress(&cinfo);
::jpeg_destroy_decompress(&cinfo);
a_width = 0;
a_height = 0;
a_bpp = 0;
delete [] image_buffer;
return 0;
}
}}
if(cinfo.output_scanline<cinfo.output_height)
::jpeg_abort_decompress(&cinfo);
else
::jpeg_finish_decompress(&cinfo);
::jpeg_destroy_decompress(&cinfo);
return image_buffer;
}
}}
#include <string>
#include <ostream>
#include <tools/sout>
namespace tools {
namespace jpeg {
inline bool is(const std::string& a_file){
FILE* file = ::fopen(a_file.c_str(),"rb");
if(!file) return false; //if file does not exist, then it is not a jpeg !
unsigned char head[4];
size_t nitem = ::fread(head,1,4,file);
::fclose(file);
if(nitem!=4) return false;
if(head[0]!=255) return false;
if(head[1]!=216) return false;
if(head[2]!=255) return false;
//if(head[3]!=224) return false; //LRI.jpg is 225 !
return true;
}
inline bool infos(std::ostream& a_out,const std::string& a_file,unsigned int& a_width,unsigned int& a_height,unsigned int& a_bpp) {
if(!is(a_file)) {
a_out << "tools::jpeg::infos :"
<< " file " << a_file << " is not jpeg."
<< std::endl;
a_width = 0;
a_height = 0;
a_bpp = 0;
return false;
}
FILE* file = ::fopen(a_file.c_str(),"rb");
if(!file) {
a_out << "tools::jpeg::infos :"
<< " can't open " << a_file
<< std::endl;
a_width = 0;
a_height = 0;
a_bpp = 0;
return false;
}
unsigned int w,h,bpp;
bool status = infos_file(file,w,h,bpp);
::fclose(file);
if(!status) {
a_out << "tools::jpeg::infos :"
<< " problem reading " << a_file
<< std::endl;
a_width = 0;
a_height = 0;
a_bpp = 0;
return false;
}
a_width = w;
a_height = h;
a_bpp = bpp;
return true;
}
inline unsigned char* read(std::ostream& a_out,const std::string& a_file,unsigned int& a_width,unsigned int& a_height,unsigned int& a_bpp) {
if(!is(a_file)) {
a_out << "tools::jpeg::read :"
<< " file " << a_file << " is not jpeg."
<< std::endl;
a_width = 0;
a_height = 0;
a_bpp = 0;
return 0;
}
FILE* file = ::fopen(a_file.c_str(),"rb");
if(!file) {
a_out << "tools::jpeg::read :"
<< " can't open " << a_file
<< std::endl;
a_width = 0;
a_height = 0;
a_bpp = 0;
return 0;
}
unsigned int w,h,bpp;
unsigned char* buffer = read_file(file,w,h,bpp);
::fclose(file);
if(!buffer) {
a_out << "tools::jpeg::read :"
<< " problem reading " << a_file
<< std::endl;
a_width = 0;
a_height = 0;
a_bpp = 0;
return 0;
}
a_width = w;
a_height = h;
a_bpp = bpp;
return buffer;
}
inline unsigned char* read_part(std::ostream& a_out,
const std::string& a_file,
unsigned int a_sx,unsigned int a_sy,
unsigned int a_sw,unsigned int a_sh,
unsigned int& a_rw,unsigned int& a_rh,
unsigned int& a_rbpp) {
if(!is(a_file)) {
a_out << "tools::jpeg::read_part :"
<< " file " << a_file << " is not jpeg."
<< std::endl;
a_rw = 0;
a_rh = 0;
a_rbpp = 0;
return 0;
}
FILE* file = ::fopen(a_file.c_str(),"rb");
if(!file) {
a_out << "tools::jpeg::read_part :"
<< " can't open " << a_file
<< std::endl;
a_rw = 0;
a_rh = 0;
a_rbpp = 0;
return 0;
}
struct jpeg_decompress_struct cinfo;
struct error_mgr jerr;
cinfo.err = ::jpeg_std_error(&jerr.pub);
jerr.pub.error_exit = tools_jpeg_error_exit;
if(::setjmp(jerr.setjmp_buffer)) {
//printf("debug : out of setjmp\n");
::fclose(file);
//NOTE : how to be sure to delete the below news if having been done ?
a_rw = 0;
a_rh = 0;
a_rbpp = 0;
return 0;
}
::jpeg_create_decompress(&cinfo);
::jpeg_stdio_src(&cinfo,file);
::jpeg_read_header(&cinfo,TRUE);
::jpeg_start_decompress(&cinfo);
int row_stride = cinfo.output_width * cinfo.output_components;
unsigned int w = cinfo.output_width;
unsigned int h = cinfo.output_height;
if((a_sx>=w)||(a_sy>=h)){
::jpeg_abort_decompress(&cinfo);
::jpeg_destroy_decompress(&cinfo);
::fclose(file);
a_rw = 0;
a_rh = 0;
a_rbpp = 0;
return 0;
}
// 012345
a_rw = tools::mn<unsigned int>(w-a_sx,a_sw);
a_rh = tools::mn<unsigned int>(h-a_sy,a_sh);
a_rbpp = cinfo.output_components;
if(!a_rw||!a_rh||!a_rbpp){
::jpeg_abort_decompress(&cinfo);
::jpeg_destroy_decompress(&cinfo);
::fclose(file);
a_rw = 0;
a_rh = 0;
a_rbpp = 0;
return 0;
}
unsigned char* image_buffer = new unsigned char[a_rw*a_rh*a_rbpp];
if(!image_buffer) {
::jpeg_abort_decompress(&cinfo);
::jpeg_destroy_decompress(&cinfo);
::fclose(file);
a_rw = 0;
a_rh = 0;
a_rbpp = 0;
return 0;
}
unsigned char* line = new unsigned char[row_stride];
if(!line) {
::jpeg_abort_decompress(&cinfo);
::jpeg_destroy_decompress(&cinfo);
::fclose(file);
delete [] image_buffer;
a_rw = 0;
a_rh = 0;
a_rbpp = 0;
return 0;
}
//FIXME : iPad : the below crashes on LHCb_artist_16384_4096_80.jpg.
unsigned int hbeg = a_sy;
unsigned int hend = a_sy+a_rh;
{JSAMPROW buffer[1];
buffer[0] = line;
unsigned char* pos = image_buffer+a_rh*a_rw*a_rbpp;
while(cinfo.output_scanline<cinfo.output_height) {
if(jpeg_read_scanlines(&cinfo, buffer, 1)!=1) {
::jpeg_abort_decompress(&cinfo);
::jpeg_destroy_decompress(&cinfo);
::fclose(file);
delete [] line;
delete [] image_buffer;
a_rw = 0;
a_rh = 0;
a_rbpp = 0;
return 0;
}
if((hbeg<=cinfo.output_scanline)&&(cinfo.output_scanline<hend)){
pos -= a_rw*a_rbpp;
::memcpy(pos,line+a_sx*a_rbpp,a_rw*a_rbpp);
}
}}
if(cinfo.output_scanline<cinfo.output_height)
::jpeg_abort_decompress(&cinfo);
else
::jpeg_finish_decompress(&cinfo);
::jpeg_destroy_decompress(&cinfo);
::fclose(file);
delete [] line;
return image_buffer;
}
inline bool write(std::ostream& a_out,
const std::string& a_file,
unsigned char* a_buffer,
unsigned int a_width,
unsigned int a_height,
unsigned int a_bpp,
int a_quality) {
FILE* file = ::fopen(a_file.c_str(),"wb");
if(!file) {
a_out << "tools::jpeg::write :"
<< " can't open file " << tools::sout(a_file) << "."
<< std::endl;
return false;
}
if(!write_file(file,a_quality,a_buffer,a_width,a_height,a_bpp)) {
::fclose(file);
a_out << "tools::jpeg::write :"
<< " can't write file " << tools::sout(a_file) << "."
<< std::endl;
return false;
}
::fclose(file);
return true;
}
}}
#include <tools/xpm>
namespace tools {
namespace jpeg {
inline bool to_xpm(std::ostream& a_out,const std::string& a_file,const std::string& a_name,bool a_verbose = false) {
return tools::xpm::to_xpm(a_out,a_file,a_name,read,a_verbose);
}
}}
#include <tools/image>
#include <vector>
namespace tools {
namespace jpeg {
inline bool concatenate(std::ostream& a_out,
const std::vector<std::string>& a_files,
unsigned int a_cols,unsigned int a_rows,
unsigned int a_bw,unsigned int a_bh,
unsigned char a_bc,
const std::string& a_file,int a_quality) {
unsigned int wa,ha,bppa;
unsigned char* ba =
tools::image::concatenate
(a_out,a_files,a_cols,a_rows,a_bw,a_bh,a_bc,read,wa,ha,bppa);
if(!ba) {
a_out << "tools::jpeg::concatenate :"
<< " failed to concatenate all buffers."
<< std::endl;
delete [] ba;
return false;
}
FILE* file = ::fopen(a_file.c_str(),"wb");
if(!file) {
a_out << "tools::jpeg::concatenate :"
<< " can't open " << file << " for writing."
<< std::endl;
delete [] ba;
return false;
}
if(!write_file(file,a_quality,ba,wa,ha,bppa)) {
a_out << "tools::jpeg::concatenate :"
<< " can't write " << a_file << "."
<< std::endl;
delete [] ba;
::fclose(file);
return false;
}
delete [] ba;
::fclose(file);
return true;
}
class reader : public virtual tools::image::ireader {
public:
virtual tools::image::ireader* copy() const {return new reader(*this);}
virtual bool is(const std::string& a_file) const {
return tools::jpeg::is(a_file);
}
virtual bool infos(std::ostream& a_out,const std::string& a_file,
unsigned int& a_width,unsigned int& a_height,
unsigned int& a_bpp) const {
return tools::jpeg::infos(a_out,a_file,a_width,a_height,a_bpp);
}
virtual unsigned char* read(std::ostream& a_out,const std::string& a_file,
unsigned int& a_width,unsigned int& a_height,
unsigned int& a_bpp) const {
return tools::jpeg::read(a_out,a_file,a_width,a_height,a_bpp);
}
virtual unsigned char* read_part(std::ostream& a_out,
const std::string& a_file,
unsigned int a_sx,unsigned int a_sy,
unsigned int a_sw,unsigned int a_sh,
unsigned int& a_rw,unsigned int& a_rh,
unsigned int& a_rbpp) const {
return tools::jpeg::read_part(a_out,a_file,
a_sx,a_sy,
a_sw,a_sh,
a_rw,a_rh,
a_rbpp);
}
public:
reader(){}
virtual ~reader(){}
public:
reader(const reader&):ireader(){}
reader& operator=(const reader&){return *this;}
};
}}
//#include <tools/img>
//
//namespace tools {
//namespace jpeg {
//
//class jpeg_data : public tools::img_byte {
//public:
// jpeg_data(std::ostream& a_out)
// :tools::img_byte(3)
// ,m_out(a_out)
// ,m_FILE(0)
// ,m_row_stride(0)
// ,m_pos(0)
// {}
// virtual ~jpeg_data(){
// if(m_FILE) ::fclose(m_FILE);
// }
//protected: //don't copy
// jpeg_data(const jpeg_data& a_from)
// :tools::img_byte(a_from)
// ,m_out(a_from.m_out)
// {}
// jpeg_data& operator=(const jpeg_data& a_from){
// tools::img_byte::operator=(a_from);
// return *this;
// }
//public:
// bool open(const std::string& a_file) {
// if(m_FILE) return false;
//
// if(!tools::jpeg::is(a_file)) {
// m_out << "tools::jpeg::jpeg_data::open :"
// << " file " << a_file << " is not jpeg."
// << std::endl;
// return false;
// }
// m_FILE = ::fopen(a_file.c_str(),"rb");
// if(!m_FILE) {
// m_out << "tools::jpeg::jpeg_data::open :"
// << " can't open " << a_file
// << std::endl;
// return false;
// }
//
// m_cinfo.err = ::jpeg_std_error(&m_jerr.pub);
// m_jerr.pub.error_exit = tools_jpeg_tools_jpeg_tools_jpeg_error_exit;
// if(::setjmp(m_jerr.setjmp_buffer)) {
// m_out << "tools::jpeg::jpeg_data::open :"
// << " setjmp failed." << a_file
// << std::endl;
// ::fclose(m_FILE);
// m_FILE = 0;
// return false;
// }
//
// ::jpeg_create_decompress(&m_cinfo);
// ::jpeg_stdio_src(&m_cinfo,m_FILE);
// ::jpeg_read_header(&m_cinfo,TRUE);
//
// ::jpeg_start_decompress(&m_cinfo);
//
// if(m_cinfo.output_components!=3) {
// m_out << "tools::jpeg::jpeg_data::open :"
// << " file " << a_file << " dont't have three components."
// << std::endl;
// ::fclose(m_FILE);
// m_FILE = 0;
// return false;
// }
//
// m_row_stride = m_cinfo.output_width * m_cinfo.output_components;
//
// unsigned char* buffer =
// new unsigned char[m_row_stride * m_cinfo.output_height];
// if(!buffer) {
// m_out << "tools::jpeg::jpeg_data::open :"
// << " can't alloc " << m_row_stride * m_cinfo.output_height
// << std::endl;
// ::fclose(m_FILE);
// m_FILE = 0;
// return false;
// }
//
// tools::img_byte::set(m_cinfo.output_width,m_cinfo.output_height,
// buffer,true);
// m_pos = buffer + m_row_stride * m_cinfo.output_height;
// return true;
// }
// bool read_row() {
// if(!m_FILE) return false;
// //::printf("debug : read_row %d\n",m_cinfo.output_scanline);
// if(m_cinfo.output_scanline<m_cinfo.output_height) {
// m_pos -= m_row_stride;
// m_jbuffer[0] = m_pos;
// if(::jpeg_read_scanlines(&m_cinfo,m_jbuffer,1)!=1) {
// tools::img_byte::clear();
// ::fclose(m_FILE);
// m_FILE = 0;
// return false;
// }
// m_h = m_cinfo.output_scanline; //in case we have to stop before end.
// return true; //continue reading.
// } else { //done.
// ::jpeg_finish_decompress(&m_cinfo);
// ::jpeg_destroy_decompress(&m_cinfo);
// ::fclose(m_FILE);
// m_FILE = 0;
// return false; //stop reading.
// }
// }
//protected:
// std::ostream& m_out;
// FILE* m_FILE;
// struct jpeg_decompress_struct m_cinfo;
// struct tools::jpeg::error_mgr m_jerr;
// int m_row_stride;
// JSAMPROW m_jbuffer[1];
// unsigned char* m_pos;
//};
//
//}}
#endif
-97
View File
@@ -1,97 +0,0 @@
// Copyright (C) 2010, Guy Barrand. All rights reserved.
// See the file tools.license for terms.
#ifndef tools_eqT
#define tools_eqT
namespace tools {
template <class NUMBER,class PREC>
inline bool numbers_are_equal(const NUMBER& a_left,const NUMBER& a_right,const PREC& a_prec,PREC(*a_fabs)(const NUMBER&)) {
NUMBER diff = a_left - a_right;
if(a_fabs(diff)>=a_prec) return false;
return true;
}
template <class NUMBER,class PREC>
inline bool is_zero(const NUMBER& a_left,const PREC& a_prec,PREC(*a_fabs)(const NUMBER&)) {
if(a_fabs(a_left)>=a_prec) return false;
return true;
}
template <class VEC,class PREC>
inline bool vectors_are_equal(const VEC& a_1,const VEC& a_2,const PREC& a_prec,PREC(*a_fabs)(const PREC&)) {
if(a_1.size()!=a_2.size()) return false;
typedef typename VEC::size_type sz_t;
sz_t sz = a_1.size();
//bool status = true;
for(sz_t index=0;index<sz;index++) {
if(!numbers_are_equal(a_1[index],a_2[index],a_prec,a_fabs))
//{ ::printf("debug : vectors_are_equals : %lu : %g %g\n",index,a_1[index],a_2[index]);
return false;
//status = false;
//}
}
return true;
//return status;
}
template <class VECVEC,class PREC>
inline bool vecvecs_are_equal(const VECVEC& a_1,const VECVEC& a_2,const PREC& a_prec,PREC(*a_fabs)(const PREC&)) {
if(a_1.size()!=a_2.size()) return false;
typedef typename VECVEC::size_type sz_t;
sz_t sz = a_1.size();
for(sz_t index=0;index<sz;index++) {
if(!vectors_are_equal(a_1[index],a_2[index],a_prec,a_fabs)) return false;
}
return true;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// PREC(*a_fabs)(PREC) : /////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
// for histo equals functions.
template <class NUMBER,class PREC>
inline bool numbers_are_equal(const NUMBER& a_left,const NUMBER& a_right,const PREC& a_prec,PREC(*a_fabs)(NUMBER)) {
NUMBER diff = a_left - a_right;
if(a_fabs(diff)>=a_prec) return false;
return true;
}
template <class VEC,class PREC>
inline bool vectors_are_equal(const VEC& a_1,const VEC& a_2,const PREC& a_prec,PREC(*a_fabs)(PREC)) {
if(a_1.size()!=a_2.size()) return false;
typedef typename VEC::size_type sz_t;
sz_t sz = a_1.size();
//bool status = true;
for(sz_t index=0;index<sz;index++) {
if(!numbers_are_equal(a_1[index],a_2[index],a_prec,a_fabs))
//{ ::printf("debug : vectors_are_equals : %lu : %g %g\n",index,a_1[index],a_2[index]);
return false;
//status = false;
//}
}
return true;
//return status;
}
template <class VECVEC,class PREC>
inline bool vecvecs_are_equal(const VECVEC& a_1,const VECVEC& a_2,const PREC& a_prec,PREC(*a_fabs)(PREC)) {
if(a_1.size()!=a_2.size()) return false;
typedef typename VECVEC::size_type sz_t;
sz_t sz = a_1.size();
for(sz_t index=0;index<sz;index++) {
if(!vectors_are_equal(a_1[index],a_2[index],a_prec,a_fabs)) return false;
}
return true;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
}
#endif
-236
View File
@@ -1,236 +0,0 @@
// Copyright (C) 2010, Guy Barrand. All rights reserved.
// See the file tools.license for terms.
#ifndef tools_mat3
#define tools_mat3
#include "mat"
//#include <cmath>
namespace tools {
template <class T>
class mat3 : public mat<T,3> {
typedef mat<T,3> parent;
typedef mat<T,3> pr;
public:
#ifdef TOOLS_MEM
mat3(bool a_inc = true):parent(a_inc) {}
#else
mat3():parent() {}
#endif
mat3(const mat<T,3>& a_from):parent(a_from){}
virtual ~mat3() {}
public:
mat3(const mat3& a_from):parent(a_from){}
mat3& operator=(const mat3& a_from){
parent::operator=(a_from);
return *this;
}
public:
mat3(const T& a_00,const T& a_01,const T& a_02, //first row
const T& a_10,const T& a_11,const T& a_12, //second row
const T& a_20,const T& a_21,const T& a_22) //third row
{
set_matrix(a_00,a_01,a_02,
a_10,a_11,a_12,
a_20,a_21,a_22);
}
public:
void set_matrix(const mat3<T>& a_m){parent::set_matrix(a_m);}
void set_matrix(const T& a_00,const T& a_01,const T& a_02, //1 row
const T& a_10,const T& a_11,const T& a_12, //2 row
const T& a_20,const T& a_21,const T& a_22) { //3 row
//a_<R><C>
//pr::m_vec[R + C * 3];
pr::m_vec[0] = a_00;pr::m_vec[3] = a_01;pr::m_vec[6] = a_02;
pr::m_vec[1] = a_10;pr::m_vec[4] = a_11;pr::m_vec[7] = a_12;
pr::m_vec[2] = a_20;pr::m_vec[5] = a_21;pr::m_vec[8] = a_22;
}
void set_scale(const T& a_s) {_set_scale(a_s,a_s,a_s,pr::m_vec);}
void set_scale(const T& a_1,const T& a_2,const T& a_3) {_set_scale(a_1,a_2,a_3,pr::m_vec);}
void set_rotate(const T& a_x,const T& a_y,const T& a_z,const T& a_angle,T(*a_sin)(T),T(*a_cos)(T)) {
_set_rotate(a_x,a_y,a_z,a_angle,pr::m_vec,a_sin,a_cos);
}
bool get_rotate(T& a_x,T& a_y,T& a_z,T& a_angle,T(*a_acos)(T),T(*a_sin)(T),T(*a_sqrt)(T)) { //warning : acos and not cos.
// used in tests/check_pauli. Same code as matTs/get_rotate.
// we assume that we have a rotation matrix.
// get (a_angle,a_n(x,y,z)) such that matrix is exp(a_angle*a_n*Rs) (passive(=coord) rotation) and then :
// exp(a_angle*n*Rs) = cos_angle*I3+(1-cos_angle)*n*n+sin_theta*n*Rs
// trace = 3*cos_angle+(1-cos_angle)*n2
T cos_angle = T(0.5)*(pr::m_vec[0]+pr::m_vec[4]+pr::m_vec[8]-T(1));
if((cos_angle<T(-1))||(T(1)<cos_angle)) { //matrix is not a rotation :
a_angle = T(0);
a_x = 0;
a_y = 0;
a_z = 0;
return false;
}
if(cos_angle==T(1)) {
a_angle = T(0);
a_x = 0;
a_y = 0;
a_z = 1;
return true; //vector is undefined but we return true anyway.
}
T one_minus_cos_angle = T(1)-cos_angle;
T x2 = (pr::m_vec[0]-cos_angle)/one_minus_cos_angle;
//T y2 = (pr::m_vec[4]-cos_angle)/one_minus_cos_angle;
//T z2 = (pr::m_vec[8]-cos_angle)/one_minus_cos_angle;
/*
if((x2<T(0))||(y2<T(0))||(z2<T(0))||(x2+y2+z2)!=T(1)) { //not a rotation :
a_angle = T(0);
a_x = 0;
a_y = 0;
a_z = 0;
return false;
}
*/
a_angle = a_acos(cos_angle); //in ]0,pi].
T sin_angle = a_sin(a_angle); //in [0,1].
if(sin_angle==T(0)) { //angle is pi. //sym part can determine vector, but up to a sign :
// sym part is : cos_angle*I+(1-cos_angle)*n*n
// cos_angle = -1
T xy = T(0.5)*(pr::m_vec[3]+pr::m_vec[1])/one_minus_cos_angle;
T xz = T(0.5)*(pr::m_vec[6]+pr::m_vec[2])/one_minus_cos_angle;
//T yz = T(0.5)*(pr::m_vec[7]+pr::m_vec[5])/one_minus_cos_angle;
a_x = a_sqrt(x2); //up to a sign.
a_y = xy/a_x;
a_z = xz/a_x;
return true; //vector is defined up to a sign.
}
// antisym part is : sin(theta)*n.Rs
a_z = T(0.5)*(pr::m_vec[3]-pr::m_vec[1])/sin_angle;
a_y = T(-0.5)*(pr::m_vec[6]-pr::m_vec[2])/sin_angle; //warning : -1.
a_x = T(0.5)*(pr::m_vec[7]-pr::m_vec[5])/sin_angle;
return true;
}
public:
void mul_3(T& a_x,T& a_y,T& a_z) const {
// a_[x,y,z] = this * a_[x,y,z]
//pr::m_vec[R + C * 3];
T x = pr::m_vec[0]*a_x+pr::m_vec[3]*a_y+pr::m_vec[6]*a_z;
T y = pr::m_vec[1]*a_x+pr::m_vec[4]*a_y+pr::m_vec[7]*a_z;
T z = pr::m_vec[2]*a_x+pr::m_vec[5]*a_y+pr::m_vec[8]*a_z;
a_x = x;
a_y = y;
a_z = z;
}
void mul_rotate(const T& a_x,const T& a_y,const T& a_z,const T& a_angle,T(*a_sin)(T),T(*a_cos)(T)) {
T rot[9];
_set_rotate(a_x,a_y,a_z,a_angle,rot,a_sin,a_cos);
parent::_mul_mtx(rot);
}
void left_mul_rotate(const T& a_x,const T& a_y,const T& a_z,const T& a_angle,T(*a_sin)(T),T(*a_cos)(T)) {
T _m[9];
_set_rotate(a_x,a_y,a_z,a_angle,_m,a_sin,a_cos);
parent::_left_mul_mtx(_m);
}
void v00(const T& a_value){pr::m_vec[0+0*3] = a_value;}
void v10(const T& a_value){pr::m_vec[1+0*3] = a_value;}
void v20(const T& a_value){pr::m_vec[2+0*3] = a_value;}
void v01(const T& a_value){pr::m_vec[0+1*3] = a_value;}
void v11(const T& a_value){pr::m_vec[1+1*3] = a_value;}
void v21(const T& a_value){pr::m_vec[2+1*3] = a_value;}
void v02(const T& a_value){pr::m_vec[0+2*3] = a_value;}
void v12(const T& a_value){pr::m_vec[1+2*3] = a_value;}
void v22(const T& a_value){pr::m_vec[2+2*3] = a_value;}
const T& v00() const {return pr::m_vec[0+0*3];}
const T& v10() const {return pr::m_vec[1+0*3];}
const T& v20() const {return pr::m_vec[2+0*3];}
const T& v01() const {return pr::m_vec[0+1*3];}
const T& v11() const {return pr::m_vec[1+1*3];}
const T& v21() const {return pr::m_vec[2+1*3];}
const T& v02() const {return pr::m_vec[0+2*3];}
const T& v12() const {return pr::m_vec[1+2*3];}
const T& v22() const {return pr::m_vec[2+2*3];}
protected:
static void _set_scale(const T& a_1,const T& a_2,const T& a_3,T v[]) {
v[0] = a_1;v[3] = 0;v[6] = 0;
v[1] = 0;v[4] = a_2;v[7] = 0;
v[2] = 0;v[5] = 0;v[8] = a_3;
}
static void _set_rotate(const T& a_x,const T& a_y,const T& a_z,const T& a_angle,T v[],T(*a_sin)(T),T(*a_cos)(T)) {
//WARNING : it models the rotation of an object (active rotation) = exp(-a_angle*n(a_x,a_y,a_z)*Rs).
//WARNING : (a_x,a_y,a_z) must be a normalized vector.
T si = a_sin(a_angle);
T co = a_cos(a_angle);
T x = a_x;
T y = a_y;
T z = a_z;
T x2 = x*x;
T y2 = y*y;
T z2 = z*z;
T xy = x*y;
T xz = x*z;
T yz = y*z;
v[0] = x2+(1-x2)*co;v[3] = xy*(1-co)-z*si;v[6] = xz*(1-co)+y*si;
v[1] = xy*(1-co)+z*si;v[4] = y2+(1-y2)*co;v[7] = yz*(1-co)-x*si;
v[2] = xz*(1-co)-y*si;v[5] = yz*(1-co)+x*si;v[8] = z2+(1-z2)*co;
// If :
// n =(x,y,z)
// n2 = x2+y2+z2 = 1
// n.E = x*E1+y*E2+z*E3
// with :
// E1 E2 E3
// 0 0 0 0 0 -1 0 1 0
// 0 0 1 0 0 0 -1 0 0
// 0 -1 0 1 0 0 0 0 0
//
// R(r,c) = cos(theta)*Id(r,c)+(1-cos(theta))*nr*nc-sin(theta)*(n.E)(r,c)
//
// R = exp(-theta*(n.E))
}
public:
private:static void check_instantiation() {mat3<float> dummy;}
};
////////////////////////////////////////////////
/// common matrices : //////////////////////////
////////////////////////////////////////////////
template <class T>
inline const mat3<T>& mat3_zero() {
static const mat3<T> s_v(false); //inc mem count = false
return s_v;
}
//for sf, mf :
//template <class T>
//inline const T* get_data(const mat3<T>& a_v) {return a_v.data();}
}
#include <ostream>
namespace tools {
template <class T>
inline std::ostream& operator<<(std::ostream& a_out,const mat3<T>& a_mtx){
const T* v = a_mtx.data();
a_out << v[0] << "," << v[3] << "," << v[6] << std::endl
<< v[1] << "," << v[4] << "," << v[7] << std::endl
<< v[2] << "," << v[5] << "," << v[8] << std::endl;
return a_out;
}
}
#endif
-66
View File
@@ -1,66 +0,0 @@
// Copyright (C) 2010, Guy Barrand. All rights reserved.
// See the file tools.license for terms.
#ifndef tools_mat3d
#define tools_mat3d
#include "mat3"
#include <cmath>
namespace tools {
class mat3d : public mat3<double> {
typedef mat3<double> parent;
public:
mat3d(){}
virtual ~mat3d() {}
public:
mat3d(const mat3d& a_from):parent(a_from){}
mat3d& operator=(const mat3d& a_from){
parent::operator=(a_from);
return *this;
}
public:
mat3d(double a_00,double a_01,double a_02, //first row
double a_10,double a_11,double a_12, //second row
double a_20,double a_21,double a_22) //third row
:parent(a_00,a_01,a_02,
a_10,a_11,a_12,
a_20,a_21,a_22)
{}
mat3d(const parent& a_from):parent(a_from){}
mat3d& operator=(const parent& a_from){
parent::operator=(a_from);
return *this;
}
public:
mat3d(const mat3<float>& a_from):parent(){
for(unsigned int index=0;index<9;index++) {
m_vec[index] = a_from.data()[index];
}
}
mat3d& operator=(const mat3<float>& a_from){
for(unsigned int index=0;index<9;index++) {
m_vec[index] = a_from.data()[index];
}
return *this;
}
public:
void set_rotate(const double& a_x,const double& a_y,const double& a_z,const double& a_angle) {
parent::set_rotate(a_x,a_y,a_z,a_angle,::sin,::cos);
}
void mul_rotate(const double& a_x,const double& a_y,const double& a_z,const double& a_angle) {
parent::mul_rotate(a_x,a_y,a_z,a_angle,::sin,::cos);
}
void left_mul_rotate(const double& a_x,const double& a_y,const double& a_z,const double& a_angle) {
parent::left_mul_rotate(a_x,a_y,a_z,a_angle,::sin,::cos);
}
bool get_rotate(double& a_x,double& a_y,double& a_z,double& a_angle) {
return parent::get_rotate(a_x,a_y,a_z,a_angle,::acos,::sin,::sqrt); //warning : acos and not cos.
}
public: //operators
};
}
#endif
-50
View File
@@ -1,50 +0,0 @@
// Copyright (C) 2010, Guy Barrand. All rights reserved.
// See the file tools.license for terms.
#ifndef tools_mat3f
#define tools_mat3f
#include "mat3"
//#include "mathf"
namespace tools {
class mat3f : public mat3<float> {
typedef mat3<float> parent;
public:
mat3f(){}
mat3f(float a_00,float a_01,float a_02, //first row
float a_10,float a_11,float a_12, //second row
float a_20,float a_21,float a_22) //third row
:parent(a_00,a_01,a_02,
a_10,a_11,a_12,
a_20,a_21,a_22)
{}
virtual ~mat3f() {}
public:
mat3f(const mat3f& a_from):parent(a_from){}
mat3f& operator=(const mat3f& a_from){
parent::operator=(a_from);
return *this;
}
public:
/*
void set_rotate(const float& a_x,const float& a_y,const float& a_z,const float& a_angle) {
parent::set_rotate(a_x,a_y,a_z,a_angle,fsin,fcos);
}
void mul_rotate(const float& a_x,const float& a_y,const float& a_z,const float& a_angle) {
parent::mul_rotate(a_x,a_y,a_z,a_angle,fsin,fcos);
}
void left_mul_rotate(const float& a_x,const float& a_y,const float& a_z,const float& a_angle) {
parent::left_mul_rotate(a_x,a_y,a_z,a_angle,fsin,fcos);
}
bool get_rotate(float& a_x,float& a_y,float& a_z,float& a_angle) {
return parent::get_rotate(a_x,a_y,a_z,a_angle,facos,fsin,fsqrt); //warning : acos and not cos.
}
*/
public: //operators
};
}
#endif
-82
View File
@@ -1,82 +0,0 @@
// Copyright (C) 2010, Guy Barrand. All rights reserved.
// See the file tools.license for terms.
#ifndef tools_mat4d
#define tools_mat4d
#include "mat4"
#include <cmath>
namespace tools {
class mat4d : public mat4<double> {
typedef mat4<double> parent;
public:
mat4d(){}
virtual ~mat4d() {}
public:
mat4d(const mat4d& a_from):parent(a_from){}
mat4d& operator=(const mat4d& a_from){
parent::operator=(a_from);
return *this;
}
public:
mat4d(double a_00,double a_01,double a_02,double a_03, //first row
double a_10,double a_11,double a_12,double a_13, //second row
double a_20,double a_21,double a_22,double a_23, //third row
double a_30,double a_31,double a_32,double a_33) //fourth row
:parent(a_00,a_01,a_02,a_03,
a_10,a_11,a_12,a_13,
a_20,a_21,a_22,a_23,
a_30,a_31,a_32,a_33)
{}
mat4d(const parent& a_from):parent(a_from){}
mat4d& operator=(const parent& a_from){
parent::operator=(a_from);
return *this;
}
public:
mat4d(const mat4<float>& a_from):parent(){
for(unsigned int index=0;index<16;index++) {
m_vec[index] = a_from.data()[index];
}
}
mat4d& operator=(const mat4<float>& a_from){
for(unsigned int index=0;index<16;index++) {
m_vec[index] = a_from.data()[index];
}
return *this;
}
public:
void set_rotate(const double& a_x,const double& a_y,const double& a_z,const double& a_angle) {
parent::set_rotate(a_x,a_y,a_z,a_angle,::sin,::cos);
}
void mul_rotate(const double& a_x,const double& a_y,const double& a_z,const double& a_angle) {
parent::mul_rotate(a_x,a_y,a_z,a_angle,::sin,::cos);
}
void left_mul_rotate(const double& a_x,const double& a_y,const double& a_z,const double& a_angle) {
parent::left_mul_rotate(a_x,a_y,a_z,a_angle,::sin,::cos);
}
template <class VEC>
void set_rotate(const VEC& a_dir,double a_angle) {
//WARNING : a_dir must be a normalized vector.
parent::set_rotate(a_dir[0],a_dir[1],a_dir[2],a_angle,::sin,::cos);
}
public: //backward compatibility
void mul_2d(double& a_x,double& a_y) const {
parent::mul_2(a_x,a_y);
}
void mul_3d(double& a_x,double& a_y,double& a_z) const {
parent::mul_3(a_x,a_y,a_z);
}
void mul_4d(double& a_x,double& a_y,double& a_z,double& a_w) const {
parent::mul_4(a_x,a_y,a_z,a_w);
}
public: //operators
};
}
#endif
-67
View File
@@ -1,67 +0,0 @@
// Copyright (C) 2010, Guy Barrand. All rights reserved.
// See the file tools.license for terms.
#ifndef tools_rotd
#define tools_rotd
// rotation done with quaternion.
#include "qrot"
#include "vec3d"
#include "vec4d"
#include "mat3d"
#include "mat4d"
namespace tools {
class rotd : public qrot<vec3d,vec4d> {
typedef qrot<vec3d,vec4d> parent;
private:
rotd(double a_q0,double a_q1,double a_q2,double a_q3):parent(a_q0,a_q1,a_q2,a_q3){}
public:
rotd():parent() {} //zero rotation around the positive Z axis.
rotd(const vec3d& a_axis,double a_radians):parent(a_axis,a_radians,::sin,::cos) {}
rotd(const vec3d& a_from,const vec3d& a_to):parent(a_from,a_to,::sqrt,::fabs) {}
virtual ~rotd(){}
public:
rotd(const rotd& a_from):parent(a_from) {}
rotd& operator=(const rotd& a_from){
parent::operator=(a_from);
return *this;
}
public:
rotd& operator*=(const rotd& a_q) {
parent::operator*=(a_q);
return *this;
}
rotd operator*(const rotd& a_r) const {
rotd tmp(*this);
tmp *= a_r;
return tmp;
}
public:
bool set_value(const vec3d& a_from,const vec3d& a_to){
return parent::set_value(a_from,a_to,::sqrt,::fabs);
}
bool set_value(const vec3d& a_from,double a_a){
return parent::set_value(a_from,a_a,::sin,::cos);
}
bool value(vec3d& a_from,double& a_a) const {
return parent::value(a_from,a_a,::sin,::acos); //WARNING acos and not cos
}
//NOTE : don't handle a static object because of mem balance.
//static const rotd& identity() {
// static const rotd s_v(0,0,0,1);
// return s_v;
//}
void value(mat4d& a_m) const {parent::value(a_m);}
void set_value(const mat4d& a_m) {parent::set_value(a_m,::sqrt);}
double value(mat3d& a_m) const {return parent::value_3(a_m);}
};
}
#endif
-89
View File
@@ -1,89 +0,0 @@
// Copyright (C) 2010, Guy Barrand. All rights reserved.
// See the file tools.license for terms.
#ifndef tools_vec4d
#define tools_vec4d
#include "vec4"
#include <cmath>
namespace tools {
class vec4d : public vec4<double> {
typedef vec4<double> parent;
public:
vec4d():parent() {}
vec4d(const double a_vec[4]):parent(a_vec) {}
#ifdef TOOLS_MEM
vec4d(const double& a0,const double& a1,const double& a2,const double& a3,bool a_inc = true):parent(a0,a1,a2,a3,a_inc){}
#else
vec4d(const double& a0,const double& a1,const double& a2,const double& a3):parent(a0,a1,a2,a3){}
#endif
virtual ~vec4d() {}
public:
vec4d(const vec4d& a_from):parent(a_from){}
vec4d& operator=(const vec4d& a_from){parent::operator=(a_from);return *this;}
public: //operators
vec4d operator*(double a_v) const {
return vec4d(m_data[0]*a_v,
m_data[1]*a_v,
m_data[2]*a_v,
m_data[3]*a_v);
}
vec4d operator+(const vec4d& a_v) const {
return vec4d(m_data[0]+a_v.m_data[0],
m_data[1]+a_v.m_data[1],
m_data[2]+a_v.m_data[2],
m_data[3]+a_v.m_data[3]);
}
vec4d operator-(const vec4d& a_v) const {
return vec4d(m_data[0]-a_v.m_data[0],
m_data[1]-a_v.m_data[1],
m_data[2]-a_v.m_data[2],
m_data[3]-a_v.m_data[3]);
}
vec4d& operator+=(const vec4d& a_v) {
m_data[0] += a_v.m_data[0];
m_data[1] += a_v.m_data[1];
m_data[2] += a_v.m_data[2];
m_data[3] += a_v.m_data[3];
return *this;
}
vec4d& operator*=(double a_v) {
m_data[0] *= a_v;
m_data[1] *= a_v;
m_data[2] *= a_v;
m_data[3] *= a_v;
return *this;
}
vec4d operator-() const {
return vec4d(-m_data[0],-m_data[1],-m_data[2],-m_data[3]);
}
public:
double length() const {return parent::length(::sqrt);}
double normalize() {return parent::normalize(::sqrt);}
};
}
/*
#include <vector>
namespace tools {
#ifndef SWIG
//for sf, mf :
inline bool set_from_vec(vec4d& a_v,const std::vector<double>& a_sv) {
if(a_sv.size()!=4) return false;
a_v[0] = a_sv[0];
a_v[1] = a_sv[1];
a_v[2] = a_sv[2];
a_v[3] = a_sv[3];
return true;
}
#endif
}
*/
#endif
-60
View File
@@ -1,60 +0,0 @@
// Copyright (C) 2010, Guy Barrand. All rights reserved.
// See the file tools.license for terms.
#ifndef tools_log_file
#define tools_log_file
#include <cstdio>
#include "sys/process"
#include "sprintf"
namespace tools {
class log_file {
public:
static log_file& get() {
static log_file s_log_file;
return s_log_file;
}
private:
log_file():m_FILE(0) {
#ifdef _WIN32
#if defined(_MSC_VER) && _MSC_VER < 1900
std::string file_name("C:\\cygwin\\tmp\\inlib_log_file_");
#else
std::string file_name("C:\\cygwin64\\tmp\\inlib_log_file_");
#endif
#else
std::string file_name("/tmp/inlib_log_file_");
#endif
std::string spid;
sprintf(spid,128,"%d",process_id());
file_name += spid;
m_FILE = ::fopen(file_name.c_str(),"wb");
}
~log_file() {if(m_FILE) ::fclose(m_FILE);}
protected:
log_file(const log_file&):m_FILE(0) {}
log_file& operator=(const log_file&) {return *this;}
public:
void close() {if(m_FILE) ::fclose(m_FILE);m_FILE = 0;}
void write(const std::string& a_string) const {
if(!m_FILE) return;
if(::fprintf(m_FILE,"%s",a_string.c_str())<0) {}
}
void writef(const char* a_format,...) const {
if(!m_FILE) return;
std::string s;
va_list args;
va_start(args,a_format);
if(vsprintf(s,1000,a_format,args)) write(s);
va_end(args);
}
protected:
FILE* m_FILE;
};
}
#endif
File diff suppressed because it is too large Load Diff
-24
View File
@@ -1,24 +0,0 @@
// Copyright (C) 2010, Guy Barrand. All rights reserved.
// See the file tools.license for terms.
#ifndef tools_metal_session_hm
#define tools_metal_session_hm
#include "../Cocoa/session.hm"
namespace tools {
namespace metal {
class session : public Cocoa::session {
typedef Cocoa::session parent;
public:
session(std::ostream& a_out):parent(a_out){}
virtual ~session() {}
protected:
session(const session& a_from):parent(a_from) {}
session& operator=(const session&){return *this;}
};
}}
#endif
@@ -1,147 +0,0 @@
// Copyright (C) 2010, Guy Barrand. All rights reserved.
// See the file tools.license for terms.
#ifndef tools_metal_sg_viewer_hm
#define tools_metal_sg_viewer_hm
#include "session.hm"
#if MAC_OS_X_VERSION_MAX_ALLOWED <= 1050
@interface tools_metal_sg_viewer_win_delegate : NSObject {
#else
@interface tools_metal_sg_viewer_win_delegate : NSObject<NSWindowDelegate> {
#endif
tools::metal::session* m_session;
}
- (id)init:(tools::metal::session*)a_session;
- (void)dealloc;
- (void)windowWillClose:(NSNotification*)a_not;
@end
@implementation tools_metal_sg_viewer_win_delegate
- (id)init:(tools::metal::session*)a_session {
if(self = [super init]) {}
m_session = a_session;
return self;
}
- (void)dealloc {[super dealloc];}
- (void)windowWillClose:(NSNotification*)a_not {
m_session->set_to_exit();
(void)a_not;
}
@end
#include "view.hm"
#include "render.hm"
namespace tools {
namespace metal {
class sg_viewer : public ui_viewer {
typedef ui_viewer parent;
public:
virtual void win_render() { //ui_viewer::win_render()
if(!m_ww) return;
if(!m_wh) return;
if(!m_win) return;
if(m_mgr_gra.begin_render(0,0,m_ww,m_wh,
m_clear_color.r(),
m_clear_color.g(),
m_clear_color.b(),
m_clear_color.a())) {
render action(m_mgr_gra,m_out,m_ww,m_wh);
action.state().m_use_gsto = m_use_gsto;
m_sg.render(action);
if(!action.end()) { //check that matrices stack are ok.
m_out << "exib::sg::viewer : bad gl_action end." << std::endl;
}
m_mgr_gra.end_render();
}
}
public:
sg_viewer(session& a_session,
int a_x = 0,int a_y = 0,
unsigned int a_width = 500,unsigned int a_height = 500,
const std::string& a_win_title = "")
:parent(a_session.out(),a_width,a_height)
,m_session(a_session)
,m_mgr_gra(a_session.out())
,m_win(0)
,m_view(0)
{
//////////////////////////////////////////////////////////
/// windowing : //////////////////////////////////////////
//////////////////////////////////////////////////////////
m_win = m_session.create_window(a_win_title.c_str(),a_x,a_y,a_width,a_height);
if(!m_win) return; //throw
tools_metal_sg_viewer_win_delegate* _win_delegate = [[tools_metal_sg_viewer_win_delegate alloc] init:&a_session];
[m_win setDelegate:_win_delegate];
NSRect rect;
rect = [m_win frame];
rect = [m_win contentRectForFrameRect:rect]; //window content true size.
{int w = rect.size.width;
int h = rect.size.height;
//::printf("debug : sg_viewer::cstor %d %d\n",w,h);
parent::set_size(w,h);}
m_view = [[tools_metal_view alloc] init:rect device:m_mgr_gra.device() viewer:this];
#ifdef TOOLS_METAL_DRAW_WHEN_NEEDED
m_view.paused = true;
m_view.enableSetNeedsDisplay = true;
#endif
//m_view.presentsWithTransaction = true; //it does not help.
m_view.depthStencilPixelFormat = MTLPixelFormatDepth32Float_Stencil8;
//m_view.clearDepth = -100000;
//m_view.clearStencil = 0;
#ifdef TOOLS_METAL_DRAW_WHEN_NEEDED
#else
tools_metal_view_controller* view_controller = [[tools_metal_view_controller alloc] init];
m_view.delegate = view_controller;
#endif
m_mgr_gra.set_view(m_view);
[m_win setContentView:m_view];
[m_view release];
}
virtual ~sg_viewer() {
if(m_win) {
m_session.delete_window(m_win);
}
}
protected:
sg_viewer(const sg_viewer& a_from)
:parent(a_from)
,m_session(a_from.m_session)
,m_mgr_gra(a_from.m_mgr_gra)
,m_win(a_from.m_win)
{}
sg_viewer& operator=(const sg_viewer& a_from){
parent::operator=(a_from);
m_mgr_gra = a_from.m_mgr_gra;
m_win = a_from.m_win;
return *this;
}
public:
bool has_window() const {return m_win?true:false;} //for SWIG
bool show() {
if(!m_win) return false;
m_session.show_window(m_win);
return true;
}
protected:
session& m_session;
metal::manager m_mgr_gra;
NSWindow* m_win;
tools_metal_view* m_view;
};
}}
#endif
-31
View File
@@ -1,31 +0,0 @@
// Copyright (C) 2010, Guy Barrand. All rights reserved.
// See the file tools.license for terms.
#ifndef tools_metal_ui_viewer
#define tools_metal_ui_viewer
#include <tools/sg/viewer>
namespace tools {
namespace metal {
class ui_viewer : public tools::sg::viewer {
typedef tools::sg::viewer parent;
public:
virtual void win_render() = 0;
//virtual void set_to_render() {} //for Apple/Metal.
public:
ui_viewer(std::ostream& a_out,unsigned int a_width,unsigned int a_height):parent(a_out,a_width,a_height){}
virtual ~ui_viewer(){}
protected:
ui_viewer(const ui_viewer& a_from):parent(a_from){}
ui_viewer& operator=(const ui_viewer& a_from){
if(&a_from==this) return *this;
parent::operator=(a_from);
return *this;
}
};
}}
#endif
-185
View File
@@ -1,185 +0,0 @@
// Copyright (C) 2010, Guy Barrand. All rights reserved.
// See the file tools.license for terms.
#ifndef tools_metal_view_hm
#define tools_metal_view_hm
#import <MetalKit/MetalKit.h>
#include "ui_viewer"
@interface tools_metal_view : MTKView {
@public tools::metal::ui_viewer* m_viewer;
NSCursor* m_cursor_default;
NSCursor* m_cursor_target;
NSCursor* m_cursor_current;
}
- (BOOL)acceptsFirstResponder;
- (nonnull id)init:(NSRect)a_rect device:(nonnull id<MTLDevice>)a_device viewer:(nonnull tools::metal::ui_viewer*)a_viewer;
- (void)dealloc;
#ifdef TOOLS_METAL_DRAW_WHEN_NEEDED
- (void)drawRect:(NSRect)a_rect;
#endif
- (void)resetCursorRects;
- (void)set_cursor:(tools::sg::cursor_shape)a_cursor;
- (void)mouseDown:(nonnull NSEvent*)a_event;
- (void)mouseUp:(nonnull NSEvent*)a_event;
- (void)mouseDragged:(nonnull NSEvent*)a_event;
@end
@implementation tools_metal_view
- (BOOL)acceptsFirstResponder {return YES;}
- (nonnull id)init:(NSRect)a_rect device:(nonnull id<MTLDevice>)a_device viewer:(nonnull tools::metal::ui_viewer*)a_viewer {
//::printf("debug : tools::metal::tools_metal_view::init\n");
self = [super initWithFrame:a_rect device:a_device];
if(!self) return self;
m_viewer = a_viewer;
m_cursor_default = [NSCursor arrowCursor];
m_cursor_target = [NSCursor crosshairCursor];
m_cursor_current = m_cursor_default;
NSTrackingAreaOptions _options = NSTrackingMouseEnteredAndExited | NSTrackingActiveAlways | NSTrackingInVisibleRect;
NSTrackingArea* tracking_area =
[[NSTrackingArea alloc] initWithRect:NSZeroRect
options:_options
owner:self userInfo:nil];
[self addTrackingArea:tracking_area];
return self;
}
- (void)dealloc {[super dealloc];}
#ifdef TOOLS_METAL_DRAW_WHEN_NEEDED
- (void)drawRect:(NSRect)a_rect {
[super drawRect:a_rect];
if(!m_viewer) return;
int w = a_rect.size.width;
int h = a_rect.size.height;
::printf("debug : tools::metal::view::drawRect : %d %d\n",w,h);
m_viewer->set_size(w,h);
m_viewer->win_render();
}
#endif
- (void)mouseDown:(nonnull NSEvent*)a_event {
[super mouseDown:a_event];
::printf("debug : tools::metal::view::mouse_down : begin :\n");
//NSPoint p = [a_event locationInWindow];
//(0,0) = bottom left of window.
//NSLog(@"debug : tools_metal_view::mouseDown %g %g",p.x,p.y);
if(!m_viewer) return;
/*
bool to_render = m_viewer->touch_down(p.x,p.y);
if(m_viewer->do_works()) to_render = true;
if(to_render) {
#ifdef TOOLS_METAL_DRAW_WHEN_NEEDED
::printf("debug : tools::metal::view::mouse_down : to render...\n");
m_viewer->win_render();
#else
[self setNeedsDisplay:YES];
#endif
}
::printf("debug : tools::metal::view::mouse_down : end.\n");
*/
}
- (void)mouseUp:(nonnull NSEvent*)a_event {
[super mouseUp:a_event];
::printf("debug : tools::metal::view::mouse_up : begin :\n");
//NSPoint p = [a_event locationInWindow];
//(0,0) = bottom left of window.
//NSLog(@"debug : tools_metal_view::mouseUp %g %g",p.x,p.y);
if(!m_viewer) return;
/*
m_viewer->add_work_check_arm_buttons();
bool to_render = m_viewer->touch_up(p.x,p.y);
//if(m_viewer->do_works()) to_render = true;
if(to_render) {
#ifdef TOOLS_METAL_DRAW_WHEN_NEEDED
::printf("debug : tools::metal::view::mouse_up : to render...\n");
m_viewer->win_render();
#else
[self setNeedsDisplay:YES];
#endif
}
*/
NSRect rect;
rect.origin.x = 0;
rect.origin.y = 0;
rect.size.width = 700;
rect.size.height = 500;
// [self setNeedsDisplayInRect:rect];
[self display];
/*
if(m_viewer->touch_up(p.x,p.y)) {
//m_viewer->win_render();
[self setNeedsDisplay:YES];
}
*/
::printf("debug : tools::metal::view::mouse_up : end.\n");
}
- (void)mouseDragged:(nonnull NSEvent*)a_event {
[super mouseDragged:a_event];
::printf("debug : tools::metal::view::mouse_dragged\n");
//NSPoint p = [a_event locationInWindow];
//(0,0) = bottom left of window.
//NSLog(@"debug : tools_metal_view::mouseDragged %g %g",p.x,p.y);
if(!m_viewer) return;
//if(m_viewer->touch_move(p.x,p.y)) m_viewer->win_render();
}
- (void)resetCursorRects {
[super resetCursorRects];
//NSLog(@"debug : resetCursorRects");
[self discardCursorRects];
[self addCursorRect:self.bounds cursor:m_cursor_default];
[self addCursorRect:self.bounds cursor:m_cursor_target];
[m_cursor_current set];
}
- (void)mouseEntered:(nonnull NSEvent*)a_event {
[super mouseEntered:a_event];
[m_cursor_current set];
}
- (void)set_cursor:(tools::sg::cursor_shape)a_cursor {
if(a_cursor==tools::sg::cursor_default) {
[m_cursor_default set];
m_cursor_current = m_cursor_default;
} else if(a_cursor==tools::sg::cursor_target) {
[m_cursor_target set];
m_cursor_current = m_cursor_target;
}
}
@end
@interface tools_metal_view_controller : NSViewController<MTKViewDelegate>
@end
@implementation tools_metal_view_controller {
}
-(void)drawInMTKView:(nonnull MTKView*)a_view {
//static unsigned int s_count = 0;
//::printf("debug : tools::metal::tools_metal_view_controller::drawInMtkView : %d\n",s_count);s_count++;
tools_metal_view* _view = static_cast<tools_metal_view*>(a_view);
@autoreleasepool {
_view->m_viewer->win_render();
}
}
- (void)mtkView:(nonnull MTKView*)a_view drawableSizeWillChange:(CGSize)a_size {
int w = a_size.width*0.5;
int h = a_size.height*0.5;
//static unsigned int s_count = 0;
//::printf("debug : tools::metal::tools_metal_view_controller::drawableSizeWillChange : %d :%d %d : %d %d\n",
// s_count,(int)a_size.width,(int)a_size.height,w,h);
tools_metal_view* _view = static_cast<tools_metal_view*>(a_view);
@autoreleasepool {
_view->m_viewer->set_size(w,h);
//_view->m_viewer->win_render(); //no.
}
}
@end
#endif
-50
View File
@@ -1,50 +0,0 @@
// Copyright (C) 2010, Guy Barrand. All rights reserved.
// See the file tools.license for terms.
#ifndef tools_paper_format
#define tools_paper_format
#include "path"
#include "touplow"
namespace tools {
namespace file {
// file::paper_format_extension() is in file_format.
// related files : sg/write_paper.
inline bool extension_paper_format(const std::string& a_file,std::string& a_fmt) {
std::string path,name,suffix;
if(!path_name_suffix(a_file,path,name,suffix)) {a_fmt.clear();return false;}
tolowercase(suffix);
if((suffix=="ps")||(suffix=="eps")) {
a_fmt = "inzb_ps";
return true;
} else if(suffix=="png") {
a_fmt = "inzb_png";
return true;
} else if((suffix=="jpg")||(suffix=="jpeg")) {
a_fmt = "inzb_jpeg";
return true;
} else if(suffix=="pdf") {
a_fmt = "gl2ps_pdf";
return true;
} else if(suffix=="svg") {
a_fmt = "gl2ps_svg";
return true;
} else if(suffix=="pgf") {
a_fmt = "gl2ps_pgf";
return true;
} else if(suffix=="tex") {
a_fmt = "gl2ps_tex";
return true;
}
a_fmt.clear();
return false;
}
}}
#endif
-56
View File
@@ -1,56 +0,0 @@
// Copyright (C) 2010, Guy Barrand. All rights reserved.
// See the file tools.license for terms.
#ifndef tools_path_env
#define tools_path_env
#include "put_env"
#include "num2s"
#include "words"
#include "sep"
#include "vmanip"
namespace tools {
inline bool env_append(const std::string& a_env,const std::string& a_sep,const std::vector<std::string>& a_vals){
std::string env_value;
if(is_env(a_env)) {
if(!get_env(a_env,env_value)) return false;
}
{std::vector<std::string>::const_iterator it;
for(it=a_vals.begin();it!=a_vals.end();++it) {
const std::string& value = *it;
if(value.empty()) continue;
if(env_value.size()) {
std::vector<std::string> ws;
words(env_value,a_sep,false,ws);
// Remove existing one, so that value be put at end.
remove(ws,value);
if(!nums2s<std::string>(ws,env_value,a_sep)) {}
}
if(env_value.size()) env_value += a_sep;
env_value += value;
}}
if(!put_env(a_env,env_value)) return false;
return true;
}
inline bool env_path_append(const std::string& a_env,const std::vector<std::string>& a_paths){
return env_append(a_env,psep(),a_paths);
}
inline bool env_append_path(const std::string& a_env,const std::string& a_path){
std::vector<std::string> v;
v.push_back(a_path);
return env_append(a_env,psep(),v);
}
}
#endif
-495
View File
@@ -1,495 +0,0 @@
// Copyright (C) 2010, Guy Barrand. All rights reserved.
// See the file tools.license for terms.
#ifndef tools_png
#define tools_png
#include <cstdio> //FILE,size_t
#include <string>
#include <tools/sout>
#include <tools/mnmx>
#ifndef TOOLS_USE_OUREX_PNG
#include <png.h>
#else
#include <ourex_png.h> //enforce ourex png
#endif
namespace tools {
namespace png {
inline bool is(const std::string& a_file){
FILE* file = ::fopen(a_file.c_str(),"rb");
if(!file) return false; //if file does not exist, then it is not a png !
png_byte header[8]; // 8 is the maximum size that can be checked
size_t nitem = ::fread(header,1,8,file);
::fclose(file);
if(nitem!=8) return false;
return ::png_sig_cmp(header,0,8)?false:true;
}
}}
#include <ostream>
namespace tools {
namespace png {
inline unsigned char* read_FILE(FILE* a_file,unsigned int& a_width,unsigned int& a_height,unsigned int& a_bpp) {
png_byte header[8]; // 8 is the maximum size that can be checked
if(::fread(header,1,8,a_file)!=8) {
a_width = 0;
a_height = 0;
a_bpp = 0;
return 0;
}
if(::png_sig_cmp(header,0,8)) {
a_width = 0;
a_height = 0;
a_bpp = 0;
return 0;
}
png_structp png_ptr =
::png_create_read_struct(PNG_LIBPNG_VER_STRING,NULL,NULL,NULL);
if(!png_ptr) {
a_width = 0;
a_height = 0;
a_bpp = 0;
return 0;
}
png_infop info_ptr = ::png_create_info_struct(png_ptr);
if(!info_ptr) {
::png_destroy_read_struct(&png_ptr,NULL,NULL);
a_width = 0;
a_height = 0;
a_bpp = 0;
return 0;
}
if(::setjmp(png_jmpbuf(png_ptr))) {
::png_destroy_read_struct(&png_ptr,&info_ptr,NULL);
a_width = 0;
a_height = 0;
a_bpp = 0;
return 0;
}
::png_init_io(png_ptr,a_file);
::png_set_sig_bytes(png_ptr,8);
::png_read_info(png_ptr,info_ptr);
png_uint_32 width = ::png_get_image_width(png_ptr,info_ptr);
png_uint_32 height = ::png_get_image_height(png_ptr,info_ptr);
png_uint_32 rowbytes = ::png_get_rowbytes(png_ptr,info_ptr);
int bpp = width?rowbytes/width:0;
if((width<=0)||(height<=0)||(bpp<=0)) {
::png_destroy_read_struct(&png_ptr,&info_ptr,NULL);
a_width = 0;
a_height = 0;
a_bpp = 0;
return 0;
}
a_bpp = bpp; //avoid the clobbered -W warning.
//png_byte color_type = info_ptr->color_type;
//info_ptr->bit_depth;
//int number_of_passes = ::png_set_interlace_handling(png_ptr);
::png_read_update_info(png_ptr,info_ptr);
if(::setjmp(png_jmpbuf(png_ptr))) {
::png_destroy_read_struct(&png_ptr,&info_ptr,NULL);
a_width = 0;
a_height = 0;
a_bpp = 0;
return 0;
}
unsigned char* buffer = new unsigned char[rowbytes * height];
if(!buffer) {
::png_destroy_read_struct(&png_ptr,&info_ptr,NULL);
a_height = 0;
a_width = 0;
a_bpp = 0;
return 0;
}
{png_bytep* row_pointers = new png_bytep[height];
png_byte* pos = buffer+rowbytes*(height-1);
for(png_uint_32 y=0;y<height;y++) {
row_pointers[y] = pos;
pos -= rowbytes;
}
::png_read_image(png_ptr,row_pointers);
delete [] row_pointers;}
::png_read_end(png_ptr,info_ptr);
::png_destroy_read_struct(&png_ptr,&info_ptr,NULL);
a_width = width;
a_height = height;
//a_bpp = bpp; //avoid the clobbered -W warning.
return buffer;
}
inline unsigned char* read(std::ostream& a_out,const std::string& a_file,unsigned int& a_width,unsigned int& a_height,unsigned int& a_bpp) {
//a_bpp = number of bytes per pixel.
FILE* file = fopen(a_file.c_str(),"rb");
if(!file) {
a_out << "tools::png::read :"
<< " can't open file " << tools::sout(a_file) << "."
<< std::endl;
a_width = 0;
a_height = 0;
a_bpp = 0;
return 0;
}
unsigned char* buffer = read_FILE(file,a_width,a_height,a_bpp);
if(!buffer) {
::fclose(file);
a_width = 0;
a_height = 0;
a_bpp = 0;
a_out << "tools::png::read :"
<< " read_FILE " << tools::sout(a_file) << " failed."
<< std::endl;
return 0;
}
::fclose(file);
return buffer;
}
inline unsigned char* read_part(std::ostream& a_out,
const std::string& a_file,
unsigned int a_sx,unsigned int a_sy,
unsigned int a_sw,unsigned int a_sh,
unsigned int& a_rw,unsigned int& a_rh,
unsigned int& a_rbpp) {
a_out << "tools::png::read_part :"
<< " not yet implemented."
<< std::endl;
a_rw = 0;
a_rh = 0;
a_rbpp = 0;
return 0;
unsigned int w,h,bpp;
unsigned char* buffer = read(a_out,a_file,w,h,bpp);
if(!buffer){
a_rw = 0;
a_rh = 0;
a_rbpp = 0;
return 0;
}
if((a_sx>=w)||(a_sy>=h)){
delete [] buffer;
a_rw = 0;
a_rh = 0;
a_rbpp = 0;
return 0;
}
// 012345
a_rw = tools::mn<unsigned int>(w-a_sx,a_sw);
a_rh = tools::mn<unsigned int>(h-a_sy,a_sh);
a_rbpp = bpp;
if(!a_rw||!a_rh||!a_rbpp){
delete [] buffer;
a_rw = 0;
a_rh = 0;
a_rbpp = 0;
return 0;
}
unsigned char* rb = new unsigned char[a_rw*a_rh*a_rbpp];
if(!rb) {
delete [] buffer;
a_rw = 0;
a_rh = 0;
a_rbpp = 0;
return 0;
}
unsigned int rstride = a_rw * a_rbpp;
unsigned char* rpos = rb;
unsigned int stride = w * bpp;
unsigned char* pos = buffer+a_sy*stride+a_sx*bpp;
for(unsigned int j=0;j<a_rh;j++,rpos+=rstride,pos+=stride) {//j=0 -> bottom.
::memcpy(rpos,pos,rstride);
}
delete [] buffer;
return rb;
}
inline bool write_FILE(FILE* a_file,unsigned char* a_buffer,unsigned int a_width,unsigned int a_height,unsigned int a_bpp) {
//from gl2ps.c.
if((a_bpp!=3)&&(a_bpp!=4)) {
return false;
}
png_structp png_ptr;
if(!(png_ptr = ::png_create_write_struct
(PNG_LIBPNG_VER_STRING,NULL,NULL,NULL))) return false;
png_infop info_ptr;
if(!(info_ptr = ::png_create_info_struct(png_ptr))){
::png_destroy_write_struct(&png_ptr,NULL);
return false;
}
if(::setjmp(png_jmpbuf(png_ptr))) {
::png_destroy_write_struct(&png_ptr,&info_ptr);
return false;
}
#ifndef Z_DEFAULT_COMPRESSION
#define Z_DEFAULT_COMPRESSION (-1)
#endif
::png_init_io(png_ptr,a_file);
::png_set_compression_level(png_ptr,Z_DEFAULT_COMPRESSION);
::png_set_IHDR(png_ptr,info_ptr,a_width,a_height,8,
a_bpp==3?PNG_COLOR_TYPE_RGB:PNG_COLOR_TYPE_RGBA,
PNG_INTERLACE_NONE,
PNG_COMPRESSION_TYPE_BASE,PNG_FILTER_TYPE_BASE);
::png_write_info(png_ptr,info_ptr);
for(unsigned int row=0;row<a_height;row++){
unsigned char* pos = a_buffer+(a_height-1-row)*(a_width*a_bpp);
::png_write_row(png_ptr,(png_bytep)pos);
}
::png_write_end(png_ptr,info_ptr);
::png_destroy_write_struct(&png_ptr,&info_ptr);
return true;
}
inline bool write(std::ostream& a_out,
const std::string& a_file,
unsigned char* a_buffer,
unsigned int a_width,
unsigned int a_height,
unsigned int a_bpp) {
FILE* file = ::fopen(a_file.c_str(),"wb");
if(!file) {
a_out << "tools::png::write :"
<< " can't open file " << tools::sout(a_file) << "."
<< std::endl;
return false;
}
if(!write_FILE(file,a_buffer,a_width,a_height,a_bpp)) {
::fclose(file);
a_out << "tools::png::write :"
<< " can't write file " << tools::sout(a_file) << "."
<< std::endl;
return false;
}
::fclose(file);
return true;
}
inline bool infos_FILE(FILE* a_file,unsigned int& a_width,unsigned int& a_height,unsigned int& a_bpp) {
//a_bpp = number of bytes per pixel.
png_byte header[8]; // 8 is the maximum size that can be checked
if(::fread(header,1,8,a_file)!=8) {
a_width = 0;
a_height = 0;
a_bpp = 0;
return false;
}
if(::png_sig_cmp(header,0,8)) {
a_width = 0;
a_height = 0;
a_bpp = 0;
return false;
}
png_structp png_ptr =
::png_create_read_struct(PNG_LIBPNG_VER_STRING,NULL,NULL,NULL);
if(!png_ptr) {
a_width = 0;
a_height = 0;
a_bpp = 0;
return false;
}
png_infop info_ptr = ::png_create_info_struct(png_ptr);
if(!info_ptr) {
a_width = 0;
a_height = 0;
a_bpp = 0;
return false;
}
if(::setjmp(png_jmpbuf(png_ptr))) {
a_width = 0;
a_height = 0;
a_bpp = 0;
return false;
}
::png_init_io(png_ptr,a_file);
::png_set_sig_bytes(png_ptr,8);
::png_read_info(png_ptr,info_ptr);
png_uint_32 width = ::png_get_image_width(png_ptr,info_ptr);
png_uint_32 height = ::png_get_image_height(png_ptr,info_ptr);
png_uint_32 rowbytes = ::png_get_rowbytes(png_ptr,info_ptr);
a_bpp = width?rowbytes/width:0;
::png_destroy_read_struct(&png_ptr,&info_ptr,NULL);
a_width = width;
a_height = height;
return true;
}
inline bool infos(std::ostream& a_out,const std::string& a_file,unsigned int& a_width,unsigned int& a_height,unsigned int& a_bpp) {
if(!is(a_file)) {
a_out << "tools::png::infos :"
<< " file " << a_file << " is not png."
<< std::endl;
a_width = 0;
a_height = 0;
a_bpp = 0;
return false;
}
FILE* file = ::fopen(a_file.c_str(),"rb");
if(!file) {
a_out << "tools::png::infos :"
<< " can't open " << a_file
<< std::endl;
a_width = 0;
a_height = 0;
a_bpp = 0;
return false;
}
unsigned int w,h,bpp;
bool status = infos_FILE(file,w,h,bpp);
::fclose(file);
if(!status) {
a_out << "tools::png::infos :"
<< " problem reading " << a_file
<< std::endl;
a_width = 0;
a_height = 0;
a_bpp = 0;
return false;
}
a_width = w;
a_height = h;
a_bpp = bpp;
return true;
}
}}
#include <tools/xpm>
namespace tools {
namespace png {
inline bool to_xpm(std::ostream& a_out,const std::string& a_file,const std::string& a_name,bool a_verbose = false) {
return tools::xpm::to_xpm(a_out,a_file,a_name,read,a_verbose);
}
}}
#include <tools/image>
#include <vector>
namespace tools {
namespace png {
inline bool concatenate(std::ostream& a_out,
const std::vector<std::string>& a_files,
unsigned int a_cols,unsigned int a_rows,
unsigned int a_bw,unsigned int a_bh,
unsigned char a_bc,
const std::string& a_file) {
unsigned int wa,ha,bppa;
unsigned char* ba =
tools::image::concatenate
(a_out,a_files,a_cols,a_rows,a_bw,a_bh,a_bc,read,wa,ha,bppa);
if(!ba) {
a_out << "tools::png::concatenate :"
<< " failed to concatenate all buffers."
<< std::endl;
delete [] ba;
return false;
}
FILE* file = ::fopen(a_file.c_str(),"wb");
if(!file) {
a_out << "tools::png::concatenate :"
<< " can't open " << file << " for writing."
<< std::endl;
delete [] ba;
return false;
}
if(!write_FILE(file,ba,wa,ha,bppa)) {
a_out << "tools::png::concatenate :"
<< " can't write " << a_file << "."
<< std::endl;
delete [] ba;
::fclose(file);
return false;
}
delete [] ba;
::fclose(file);
return true;
}
class reader : public virtual tools::image::ireader {
public:
virtual tools::image::ireader* copy() const {return new reader(*this);}
virtual bool is(const std::string& a_file) const {return tools::png::is(a_file);}
virtual bool infos(std::ostream& a_out,const std::string& a_file,
unsigned int& a_width,unsigned int& a_height,unsigned int& a_bpp) const {
return tools::png::infos(a_out,a_file,a_width,a_height,a_bpp);
}
virtual unsigned char* read(std::ostream& a_out,const std::string& a_file,
unsigned int& a_width,unsigned int& a_height,unsigned int& a_bpp) const {
return tools::png::read(a_out,a_file,a_width,a_height,a_bpp);
}
virtual unsigned char* read_part(std::ostream& a_out,const std::string& a_file,
unsigned int a_sx,unsigned int a_sy,
unsigned int a_sw,unsigned int a_sh,
unsigned int& a_rw,unsigned int& a_rh,unsigned int& a_rbpp) const {
return tools::png::read_part(a_out,a_file,a_sx,a_sy,a_sw,a_sh,a_rw,a_rh,a_rbpp);
}
public:
reader(){}
virtual ~reader(){}
public:
reader(const reader&):ireader(){}
reader& operator=(const reader&){return *this;}
};
}}
#endif
-45
View File
@@ -1,45 +0,0 @@
// Copyright (C) 2010, Guy Barrand. All rights reserved.
// See the file tools.license for terms.
#ifndef tools_put_env
#define tools_put_env
//WARNING : CYGWIN/gnu/std=c++11 : putenv, setenv not found.
#include "get_env"
#include "cstr"
namespace tools {
inline bool put_env(const std::string& a_env,const std::string& a_value){
std::string value = a_env+"="+a_value;
#ifdef TOOLS_MEM
if(::putenv(str_dup(value.c_str(),false))) return false;
#else
if(::putenv(str_dup(value.c_str()))) return false;
#endif
//check:
std::string s;
if(!get_env(a_env,s)) return false;
if(s!=a_value) return false;
return true;
}
inline bool rm_env(const std::string& a_env){
#ifdef _MSC_VER
std::string value = a_env+"=";
#ifdef TOOLS_MEM
if(::putenv(str_dup(value.c_str(),false))) return false;
#else
if(::putenv(str_dup(value.c_str()))) return false;
#endif
#else
::unsetenv(a_env.c_str());
#endif
return true;
}
}
#endif
-239
View File
@@ -1,239 +0,0 @@
// Copyright (C) 2010, Guy Barrand. All rights reserved.
// See the file tools.license for terms.
#ifndef tools_randT
#define tools_randT
namespace tools {
template <class FLAT,class REAL>
class rgauss {
typedef REAL(*math_func)(REAL); //for rootcint.
//public:
// typedef REAL value_t;
public:
rgauss(FLAT& a_flat,REAL a_mean = 0,REAL a_std_dev = 1)
:m_flat(a_flat),m_mean(a_mean),m_std_dev(a_std_dev){}
virtual ~rgauss(){}
public:
rgauss(const rgauss& a_from):m_flat(a_from.m_flat),m_mean(a_from.m_mean),m_std_dev(a_from.m_std_dev){}
rgauss& operator=(const rgauss& a_from) {
m_mean = a_from.m_mean;
m_std_dev = a_from.m_std_dev;
return *this;
}
public:
REAL shoot(math_func a_sqrt,math_func a_log) const {
REAL v1,v2,r,fac;
do {
v1 = REAL(2) * m_flat.shoot() - REAL(1);
v2 = REAL(2) * m_flat.shoot() - REAL(1);
r = v1*v1 + v2*v2;
} while (r>REAL(1));
fac = a_sqrt(-REAL(2)*a_log(r)/r);
return (v2 * fac) * m_std_dev + m_mean;
}
FLAT& flat() {return m_flat;}
void set_seed(unsigned int a_seed) {m_flat.set_seed(a_seed);}
void set(REAL a_mean = 0,REAL a_std_dev = 1) {m_mean = a_mean;m_std_dev = a_std_dev;}
protected:
FLAT& m_flat;
REAL m_mean;
REAL m_std_dev;
};
template <class FLAT,class REAL>
class rbw {
public:
rbw(FLAT& a_flat,REAL a_mean = 0,REAL a_gamma = 1):m_flat(a_flat),m_mean(a_mean),m_gamma(a_gamma){}
virtual ~rbw(){}
public:
rbw(const rbw& a_from):m_flat(a_from.m_flat),m_mean(a_from.m_mean),m_gamma(a_from.m_gamma){}
rbw& operator=(const rbw& a_from) {
m_mean = a_from.m_mean;
m_gamma = a_from.m_gamma;
return *this;
}
public:
REAL shoot(const REAL& a_half_pi,REAL(*a_tan)(REAL)) const {
REAL rval = REAL(2) * m_flat.shoot() - REAL(1);
REAL displ = (REAL(1)/REAL(2)) * m_gamma * a_tan(rval * a_half_pi);
return m_mean + displ;
}
FLAT& flat() {return m_flat;}
void set_seed(unsigned int a_seed) {m_flat.set_seed(a_seed);}
protected:
FLAT& m_flat;
REAL m_mean;
REAL m_gamma;
};
template <class FLAT,class REAL>
class rexp {
typedef REAL(*math_func)(REAL); //for rootcint.
public:
rexp(FLAT& a_flat,REAL a_rate = 1):m_flat(a_flat),m_rate(a_rate){}
virtual ~rexp(){}
public:
rexp(const rexp& a_from):m_flat(a_from.m_flat),m_rate(a_from.m_rate){}
rexp& operator=(const rexp& a_from) {m_rate = a_from.m_rate;return *this;}
public:
REAL shoot(math_func a_log) const {
REAL v;
do {
v = m_flat.shoot();
} while(v<=REAL(0));
return -a_log(v)/m_rate;
}
FLAT& flat() {return m_flat;}
void set_seed(unsigned int a_seed) {m_flat.set_seed(a_seed);}
protected:
FLAT& m_flat;
REAL m_rate;
};
template <class FLAT,class REAL>
class rdir2 {
public:
rdir2(FLAT& a_flat):m_flat(a_flat){}
virtual ~rdir2(){}
public:
rdir2(const rdir2& a_from):m_flat(a_from.m_flat){}
rdir2& operator=(const rdir2&) {return *this;}
public:
void shoot(REAL& a_x,REAL& a_y) const {
// from gsl_ran_dir_2d.
REAL u,v,s;
do {
u = REAL(2) * m_flat.shoot()-REAL(1);
v = REAL(2) * m_flat.shoot()-REAL(1);
s = u * u + v * v;
}
while ( (s > REAL(1)) || (s==REAL(0)) );
a_x = (u * u - v * v) / s;
a_y = REAL(2) * u * v / s;
}
FLAT& flat() {return m_flat;}
void set_seed(unsigned int a_seed) {m_flat.set_seed(a_seed);}
protected:
FLAT& m_flat;
};
template <class FLAT,class REAL>
class rdir3 {
public:
rdir3(FLAT& a_flat):m_flat(a_flat){}
virtual ~rdir3(){}
public:
rdir3(const rdir3& a_from):m_flat(a_from.m_flat){}
rdir3& operator=(const rdir3&) {return *this;}
public:
void shoot(REAL& a_x,REAL& a_y,REAL& a_z,REAL(*a_sqrt)(REAL)) const {
// from gsl_ran_dir_3d.
REAL s;
do {
a_x = REAL(2) * m_flat.shoot() - REAL(1);
a_y = REAL(2) * m_flat.shoot() - REAL(1);
s = (a_x) * (a_x) + (a_y) * (a_y);
}
while (s > REAL(1));
a_z = REAL(2) * s - REAL(1);
REAL a = REAL(2) * a_sqrt(REAL(1) - s);
a_x *= a;
a_y *= a;
}
FLAT& flat() {return m_flat;}
void set_seed(unsigned int a_seed) {m_flat.set_seed(a_seed);}
protected:
FLAT& m_flat;
};
// from Geant4/G4Poisson.hh :
// NOTE : not used yet.
template <class FLAT,class REAL,class UINT>
class rpoiss {
public:
rpoiss(FLAT& a_flat,REAL a_mean = 1):m_flat(a_flat),m_mean(a_mean){}
virtual ~rpoiss(){}
public:
rpoiss(const rpoiss& a_from):m_flat(a_from.m_flat),m_mean(a_from.m_mean){}
rpoiss& operator=(const rpoiss& a_from) {
m_mean = a_from.m_mean;
return *this;
}
public:
UINT shoot(const REAL& a_two_pi,REAL(*a_sqrt)(REAL),REAL(*a_log)(REAL),REAL(*a_exp)(REAL),REAL(*a_cos)(REAL)) const {
UINT number = 0;
if(m_mean <= 16) {
REAL position = m_flat.shoot();
REAL poissonValue = a_exp(-m_mean);
REAL poissonSum = poissonValue;
while(poissonSum <= position) {
number++;
poissonValue *= m_mean/REAL(number);
poissonSum += poissonValue;
}
return number;
}
// m_mean > 16 :
REAL t = a_sqrt(-REAL(2)*a_log(m_flat.shoot()));
REAL y = a_two_pi*m_flat.shoot();
t *= a_cos(y);
REAL value = m_mean + t*a_sqrt(m_mean) + REAL(0.5);
if(value <= REAL(0)) return UINT(0);
static const REAL limit = REAL(2e9);
if(value >= limit) return UINT(limit);
return UINT(value);
}
FLAT& flat() {return m_flat;}
void set_seed(unsigned int a_seed) {m_flat.set_seed(a_seed);}
protected:
FLAT& m_flat;
REAL m_mean;
};
template <class FLAT,class REAL,class UINT>
class rbinomial {
public:
rbinomial(FLAT& a_flat,UINT a_n = 1,REAL a_p = REAL(0.5)):m_flat(a_flat),m_n(a_n),m_p(a_p){}
virtual ~rbinomial(){}
public:
rbinomial(const rbinomial& a_from):m_flat(a_from.m_flat),m_n(a_from.m_n),m_p(a_from.m_p){}
rbinomial& operator=(const rbinomial& a_from) {
m_n = a_from.m_n;
m_p = a_from.m_p;
return *this;
}
public:
UINT shoot() const {
// from ROOT/TRandom.cxx.
////////////////////////////////////////////////////////////////////////////////
/// Generates a random integer N according to the binomial law.
/// Coded from Los Alamos report LA-5061-MS.
///
/// N is binomially distributed between 0 and ntot inclusive
/// with mean prob*ntot and prob is between 0 and 1.
///
/// Note: This function should not be used when ntot is large (say >100).
/// The normal approximation is then recommended instead
/// (with mean =*ntot+0.5 and standard deviation sqrt(ntot*prob*(1-prob)).
////////////////////////////////////////////////////////////////////////////////
if((m_p<REAL(0))||(REAL(1)<m_p)) return 0;
UINT n = 0;
for(UINT i=0;i<m_n;i++) {
if(m_flat.shoot()>m_p) continue;
n++;
}
return n;
}
FLAT& flat() {return m_flat;}
void set_seed(unsigned int a_seed) {m_flat.set_seed(a_seed);}
protected:
FLAT& m_flat;
UINT m_n;
REAL m_p;
};
}
#endif
-206
View File
@@ -1,206 +0,0 @@
// Copyright (C) 2010, Guy Barrand. All rights reserved.
// See the file tools.license for terms.
#ifndef tools_randd
#define tools_randd
#include "randT"
#include "rtausmed"
#include "S_STRING"
#include "scast"
namespace tools {
class irandd {
public:
virtual ~irandd() {}
public:
virtual void* cast(const std::string&) const = 0;
public:
virtual double shootd() const = 0;
};
class rbinomiald : public virtual irandd, public rbinomial<rtausmed,double,unsigned int> {
typedef rbinomial<rtausmed,double,unsigned int> parent;
public:
TOOLS_SCLASS(tools::rbinomiald)
public:
virtual void* cast(const std::string& a_class) const {
if(void* p = cmp_cast<rbinomiald>(this,a_class)) return p;
return 0;
}
virtual double shootd() const {return shoot();}
public:
rbinomiald(unsigned int a_n = 1,double a_p = 0.5):parent(m_flat,a_n,a_p),m_flat(){}
virtual ~rbinomiald(){}
public:
rbinomiald(const rbinomiald& a_from):irandd(a_from),parent(m_flat),m_flat(a_from.m_flat){}
rbinomiald& operator=(const rbinomiald& a_from) {
parent::operator=(a_from);
m_flat = a_from.m_flat;
return *this;
}
protected:
rtausmed m_flat;
};
class rgaussd : public virtual irandd, public rgauss<rtausmed,double> {
typedef rgauss<rtausmed,double> parent;
public:
TOOLS_SCLASS(tools::rgaussd)
public:
virtual void* cast(const std::string& a_class) const {
if(void* p = cmp_cast<rgaussd>(this,a_class)) return p;
return 0;
}
virtual double shootd() const {return shoot();}
public:
rgaussd(double a_mean = 0,double a_std_dev = 1):parent(m_flat,a_mean,a_std_dev),m_flat(){}
virtual ~rgaussd(){}
public:
rgaussd(const rgaussd& a_from):irandd(a_from),parent(m_flat),m_flat(a_from.m_flat){}
rgaussd& operator=(const rgaussd& a_from) {
parent::operator=(a_from);
m_flat = a_from.m_flat;
return *this;
}
public:
double shoot() const {return parent::shoot(::sqrt,::log);}
protected:
rtausmed m_flat;
};
class rexpd : public virtual irandd, public rexp<rtausmed,double> {
typedef rexp<rtausmed,double> parent;
public:
TOOLS_SCLASS(tools::rexpd)
public:
virtual void* cast(const std::string& a_class) const {
if(void* p = cmp_cast<rexpd>(this,a_class)) return p;
return 0;
}
virtual double shootd() const {return shoot();}
public:
rexpd(double a_rate = 1):parent(m_flat,a_rate),m_flat(){}
virtual ~rexpd(){}
public:
rexpd(const rexpd& a_from):irandd(a_from),parent(m_flat),m_flat(a_from.m_flat){}
rexpd& operator=(const rexpd& a_from) {
parent::operator=(a_from);
m_flat = a_from.m_flat;
return *this;
}
public:
double shoot() const {return parent::shoot(::log);}
protected:
rtausmed m_flat;
};
class rdir2d : public rdir2<rtausmed,double> {
typedef rdir2<rtausmed,double> parent;
public:
TOOLS_SCLASS(tools::rdir2d)
public:
rdir2d():parent(m_flat),m_flat(){}
virtual ~rdir2d(){}
public:
rdir2d(const rdir2d& a_from):parent(m_flat),m_flat(a_from.m_flat){}
rdir2d& operator=(const rdir2d& a_from) {
parent::operator=(a_from);
m_flat = a_from.m_flat;
return *this;
}
protected:
rtausmed m_flat;
};
class rdir3d : public rdir3<rtausmed,double> {
typedef rdir3<rtausmed,double> parent;
public:
TOOLS_SCLASS(tools::rdir3d)
public:
rdir3d():parent(m_flat),m_flat(){}
virtual ~rdir3d(){}
public:
rdir3d(const rdir3d& a_from):parent(m_flat),m_flat(a_from.m_flat){}
rdir3d& operator=(const rdir3d& a_from) {
parent::operator=(a_from);
m_flat = a_from.m_flat;
return *this;
}
public:
void shoot(double& a_x,double& a_y,double& a_z) const {
parent::shoot(a_x,a_y,a_z,::sqrt);
}
protected:
rtausmed m_flat;
};
}
#include "mathd"
namespace tools {
class rbwd : public virtual irandd, public rbw<rtausmed,double> {
typedef rbw<rtausmed,double> parent;
public:
TOOLS_SCLASS(tools::rbwd)
public:
virtual void* cast(const std::string& a_class) const {
if(void* p = cmp_cast<rbwd>(this,a_class)) return p;
return 0;
}
virtual double shootd() const {return shoot();}
public:
rbwd(double a_mean = 0,double a_gamma = 1):parent(m_flat,a_mean,a_gamma),m_flat(){}
virtual ~rbwd(){}
public:
rbwd(const rbwd& a_from):irandd(a_from),parent(m_flat),m_flat(a_from.m_flat){}
rbwd& operator=(const rbwd& a_from) {
parent::operator=(a_from);
m_flat = a_from.m_flat;
return *this;
}
public:
double shoot() const {return parent::shoot(half_pi(),::tan);}
protected:
rtausmed m_flat;
};
}
#include "typedefs"
namespace tools {
class rpoissd : public virtual irandd, public rpoiss<rtausmed,double,uint64> {
typedef rpoiss<rtausmed,double,uint64> parent;
public:
TOOLS_SCLASS(tools::rpoissd)
public:
virtual void* cast(const std::string& a_class) const {
if(void* p = cmp_cast<rpoissd>(this,a_class)) return p;
return 0;
}
virtual double shootd() const {return double(shoot());}
public:
rpoissd(double a_mean = 1):parent(m_flat,a_mean),m_flat(){}
virtual ~rpoissd(){}
public:
rpoissd(const rpoissd& a_from):irandd(a_from),parent(m_flat),m_flat(a_from.m_flat){}
rpoissd& operator=(const rpoissd& a_from) {
parent::operator=(a_from);
m_flat = a_from.m_flat;
return *this;
}
public:
uint64 shoot() const {return parent::shoot(two_pi(),::sqrt,::log,::exp,::cos);}
protected:
rtausmed m_flat;
};
}
#endif
-74
View File
@@ -1,74 +0,0 @@
// Copyright (C) 2010, Guy Barrand. All rights reserved.
// See the file tools.license for terms.
#ifndef tools_randf
#define tools_randf
#include "randT"
#include "rtausmef"
namespace tools {
class rgaussf : public rgauss<rtausmef,float> {
typedef rgauss<rtausmef,float> parent;
public:
rgaussf(float a_mean = 0,float a_std_dev = 1):parent(m_flat,a_mean,a_std_dev),m_flat(){}
virtual ~rgaussf(){}
public:
rgaussf(const rgaussf& a_from):parent(m_flat),m_flat(a_from.m_flat){}
rgaussf& operator=(const rgaussf& a_from) {
parent::operator=(a_from);
m_flat = a_from.m_flat;
return *this;
}
public:
float shoot() const {return parent::shoot(::sqrtf,::logf);}
protected:
rtausmef m_flat;
};
class rexpf : public rexp<rtausmef,float> {
typedef rexp<rtausmef,float> parent;
public:
rexpf(float a_rate = 1):parent(m_flat,a_rate),m_flat(){}
virtual ~rexpf(){}
public:
rexpf(const rexpf& a_from):parent(m_flat),m_flat(a_from.m_flat){}
rexpf& operator=(const rexpf& a_from) {
parent::operator=(a_from);
m_flat = a_from.m_flat;
return *this;
}
public:
float shoot() const {return parent::shoot(::logf);}
protected:
rtausmef m_flat;
};
}
#include "mathf"
namespace tools {
class rbwf : public rbw<rtausmef,float> {
typedef rbw<rtausmef,float> parent;
public:
rbwf(float a_mean = 0,float a_gamma = 1):parent(m_flat,a_mean,a_gamma),m_flat(){}
virtual ~rbwf(){}
public:
rbwf(const rbwf& a_from):parent(m_flat),m_flat(a_from.m_flat){}
rbwf& operator=(const rbwf& a_from) {
parent::operator=(a_from);
m_flat = a_from.m_flat;
return *this;
}
public:
float shoot() const {return parent::shoot(fhalf_pi(),::tanf);}
protected:
rtausmef m_flat;
};
}
#endif
-56
View File
@@ -1,56 +0,0 @@
// Copyright (C) 2010, Guy Barrand. All rights reserved.
// See the file tools.license for terms.
#ifndef tools_random
#define tools_random
// for backward compatibility.
#include "randd"
namespace tools {
namespace random {
class gauss : public rgaussd {
typedef rgaussd parent;
public:
gauss(double a_mean = 0,double a_std_dev = 1):parent(a_mean,a_std_dev){}
virtual ~gauss(){}
public:
gauss(const gauss& a_from):parent(a_from){}
gauss& operator=(const gauss& a_from) {parent::operator=(a_from);return *this;}
};
class bw : public rbwd {
typedef rbwd parent;
public:
bw(double a_mean = 0,double a_gamma = 1):parent(a_mean,a_gamma){}
virtual ~bw(){}
public:
bw(const bw& a_from):parent(a_from){}
bw& operator=(const bw& a_from) {parent::operator=(a_from);return *this;}
};
class exp : public rexpd {
typedef rexpd parent;
public:
exp(double a_rate = 1):parent(a_rate){}
virtual ~exp(){}
public:
exp(const exp& a_from):parent(a_from){}
exp& operator=(const exp& a_from) {parent::operator=(a_from);return *this;}
};
class flat : public rtausmed {
typedef rtausmed parent;
public:
flat():parent(){}
virtual ~flat(){}
public:
flat(const flat& a_from):parent(a_from){}
flat& operator=(const flat& a_from) {parent::operator=(a_from);return *this;}
};
}}
#endif
@@ -1,99 +0,0 @@
// Copyright (C) 2010, Guy Barrand. All rights reserved.
// See the file tools.license for terms.
#ifndef tools_rroot_member_reader
#define tools_rroot_member_reader
#include "../store/iobj_visitor"
#include "buffer"
namespace tools {
namespace rroot {
class member_reader : public virtual iobj_visitor {
public:
virtual std::ostream& out() const {return m_buf.out();}
virtual bool visit(bool& a_v){return m_buf.read(a_v);}
virtual bool visit(char& a_v){return m_buf.read(a_v);}
virtual bool visit(short& a_v){return m_buf.read(a_v);}
virtual bool visit(int& a_v){return m_buf.read(a_v);}
virtual bool visit(unsigned int& a_v){return m_buf.read(a_v);}
virtual bool visit(int64&){
m_buf.out() << "tools::rroot::member_reader::visit(int64) :"
<< " dummy." << std::endl;
return false; //FIXME
}
virtual bool visit(uint64&){
m_buf.out() << "tools::rroot::member_reader::visit(uint64) :"
<< " dummy." << std::endl;
return false; //FIXME
}
virtual bool visit(float& a_v){return m_buf.read(a_v);}
virtual bool visit(double& a_v){return m_buf.read(a_v);}
virtual bool visit(std::string& a_v){return m_buf.read(a_v);}
//virtual bool visit(const char* a_v){
// return m_buf.read(std::string(a_v));
//}
virtual bool visit(std::vector<bool>& a_v){
std::vector<unsigned char> data;
if(!m_buf.read_array(data)) {a_v.clear();return false;}
size_t number = data.size();
a_v.resize(number);
for(size_t index=0;index<number;index++) {
a_v[index] = (data[index]==1?true:false);
}
return true;
}
virtual bool visit(std::vector<char>& a_v){return m_buf.read_array(a_v);}
virtual bool visit(std::vector<short>& a_v){return m_buf.read_array(a_v);}
virtual bool visit(std::vector<int>& a_v){return m_buf.read_array(a_v);}
virtual bool visit(std::vector<int64>& /*a_v*/){
//FIXME return ::Rio::writeArray<Slash::int64>(fBuffer,a_v);
m_buf.out() << "tools::rroot::member_reader::visit(vector<int64>) :"
<< " dummy." << std::endl;
return false;
}
virtual bool visit(std::vector<float>& a_v){return m_buf.read_array(a_v);}
virtual bool visit(std::vector<double>& a_v){return m_buf.read_array(a_v);}
virtual bool visit(std::vector<unsigned char>& a_v){
return m_buf.read_array(a_v);
}
virtual bool visit(std::vector<std::string>& a_v){return m_buf.read(a_v);}
virtual bool visit(std::vector< std::vector<double> >& a_v){
return m_buf.read_array2(a_v);
}
public:
member_reader(buffer& a_buf):m_buf(a_buf){}
virtual ~member_reader(){}
private:
member_reader(const member_reader& a_from)
:iobj_visitor(a_from)
,m_buf(a_from.m_buf)
{}
member_reader& operator=(const member_reader&){return *this;}
protected:
buffer& m_buf;
};
}}
#endif
-190
View File
@@ -1,190 +0,0 @@
// Copyright (C) 2010, Guy Barrand. All rights reserved.
// See the file tools.license for terms.
#ifndef tools_rroot_tree_manip
#define tools_rroot_tree_manip
#include "file"
#include "tree"
#include "stl_vector"
namespace tools {
namespace rroot {
inline tree* find_tree(file& a_file,ifac& a_fac,const std::string& a_name,bool a_map_objs = false) {
std::ostream& out = a_file.out();
//out << "tools::rroot::find_tree : name : " << file << std::endl;
key* key = a_file.dir().find_key(a_name);
if(!key) {
out << "tools::rroot::find_tree :"
<< " key " << sout(a_name) << " not found."
<< std::endl;
return 0;
}
unsigned int sz;
char* buf = key->get_object_buffer(a_file,sz); //we don't have ownership of buf.
if(!buf) {
out << "tools::rroot::find_tree :"
<< " can't get data buffer of "
<< sout(key->object_name()) << "."
<< std::endl;
return 0;
}
//out << "tools::rroot::find_tree :"
// << " get data buffer size " << sz << "."
// << std::endl;
if(key->object_class()!=TTree_cls()) {
out << "tools::rroot::find_tree :"
<< " key object class "
<< sout(key->object_class())
<< " is not a TTree."
<< std::endl;
return 0;
}
buffer b(out,a_file.byte_swap(),sz,buf,key->key_length(),false);
b.set_map_objs(a_map_objs);
tree* _tree = new tree(a_file,a_fac);
if(!_tree->stream(b)) {
out << "tools::rroot::find_tree :"
<< " TTree streaming failed"
<< std::endl;
delete _tree;
return 0;
}
return _tree;
}
inline branch_element* find_be(tree& a_tree,const std::string& a_name){
std::ostream& out = a_tree.file().out();
branch* _branch = a_tree.find_branch(a_name,true);
if(!_branch) {
out << "tools::rroot::find_be :"
<< " branch not found."
<< std::endl;
return 0;
}
branch_element* be = id_cast<branch,branch_element>(*_branch);
if(!be) {
out << "tools::rroot::find_be :"
<< " branch not a branch_element."
<< std::endl;
return 0;
}
return be;
}
template <class T>
inline stl_vector<T>* find_vec(ifile& a_file,branch_element& a_be,uint64 a_event){
std::ostream& out = a_file.out();
unsigned int n;
if(!a_be.find_entry(a_file,a_event,n)) {
out << "tools::rroot::find_vec : branch_element.find_entry() failed." << std::endl;
return 0;
}
iro* o = a_be.object();
stl_vector<T>* od = id_cast<iro, stl_vector<T> >(*o);
if(!od) {
out << "tools::rroot::find_vec : object not a tools::rroot::stl_vector<T>." << std::endl;
return 0;
}
return od; //WARNING : we are not owner.
}
}}
#include "leaf"
namespace tools {
namespace rroot {
template <class LEAF>
inline bool find_leaf(tree& a_tree,const std::string& a_name,branch*& a_branch,LEAF*& a_leaf) {
//used in MEMPHYS sim.
base_leaf* _base_leaf = a_tree.find_leaf(a_name);
if(!_base_leaf) {
a_tree.out() << "tools::rroot::find_leaf : base_leaf " << sout(a_name) << " not found." << std::endl;
a_branch = 0;
a_leaf = 0;
return false;
}
a_branch = a_tree.find_leaf_branch(*_base_leaf);
if(!a_branch) {
a_tree.out() << "tools::rroot::find_leaf : branch of base_leaf " << sout(a_name) << " not found." << std::endl;
a_branch = 0;
a_leaf = 0;
return false;
}
a_leaf = safe_cast<base_leaf,LEAF>(*_base_leaf);
if(!a_leaf) {
a_tree.out() << "tools::rroot::find_leaf : base_leaf " << sout(a_name) << " is not a LEAF." << std::endl;
a_branch = 0;
a_leaf = 0;
return false;
}
return true;
}
inline branch_element* find_branch_element(tree& a_tree,const std::string& a_name) {
branch* _branch = a_tree.find_branch(a_name);
if(!_branch) {
a_tree.out() << "tools::rroot::find_branch_element : branch " << sout(a_name) << " not found." << std::endl;
return 0;
}
branch_element* be = safe_cast<branch,branch_element>(*_branch);
if(!be) {
a_tree.out() << "tools::rroot::find_branch_element : branch " << sout(a_name) << " not a branch_element."
<< " It is a " << sout(_branch->s_cls()) << "."
<< std::endl;
return 0;
}
return be;
}
template <class TYPE>
inline bool read_leaf(ifile& a_file,branch& a_branch,leaf<TYPE>& a_leaf,uint64 a_event,TYPE& a_value) {
unsigned int n;
if(!a_branch.find_entry(a_file,a_event,n)) {
a_file.out() << "tools::rroot::read_leaf : a_branch.find_entry() failed." << std::endl;
a_value = TYPE(0);
return false;
}
return a_leaf.value(0,a_value);
}
inline bool read_leaf_object(ifile& a_file,branch& a_branch,leaf_object& a_leaf,uint64 a_event) {
unsigned int n;
if(!a_branch.find_entry(a_file,a_event,n)) {
a_file.out() << "tools::rroot::read_leaf_object : a_branch.find_entry() failed." << std::endl;
return false;
}
return true;
}
template <class TYPE>
inline stl_vector<TYPE>* read_std_vec(ifile& a_file,branch_element& a_branch,uint64 a_event) {
unsigned int n;
if(!a_branch.find_entry(a_file,a_event,n)) {
a_file.out() << "tools::rroot::read_std_vec : a_branch.find_entry() failed." << std::endl;
return 0;
}
iro* obj = a_branch.object(); //Not owner.
if(!obj) return 0;
return id_cast<iro, stl_vector<TYPE> >(*obj);
}
}}
#endif
-39
View File
@@ -1,39 +0,0 @@
// Copyright (C) 2010, Guy Barrand. All rights reserved.
// See the file tools.license for terms.
#ifndef tools_rtausmed
#define tools_rtausmed
// G.Barrand : not so clear if 0 and 1 are included.
// With a simple program, we saw no hits with "if(r.shoot()==0)" or "if(r.shoot()==1)".
// (See inlib/tests/rand.cpp).
#include "rtausmeui"
#include "S_STRING"
#include <cmath>
namespace tools {
class rtausmed : public rtausmeui {
typedef rtausmeui parent;
public:
TOOLS_SCLASS(tools::rtausmed)
public:
rtausmed(unsigned int a_seed = 4357):parent(a_seed){}
virtual ~rtausmed(){}
public:
rtausmed(const rtausmed& a_from):parent(a_from){}
rtausmed& operator=(const rtausmed& a_from) {parent::operator=(a_from);return *this;}
protected:
static double two_to_minus_32() {
static const double s_v = std::ldexp(1.0,-32);
return s_v;
}
public:
double shoot() {return double(parent::shoot()) * two_to_minus_32();}
};
}
#endif
-35
View File
@@ -1,35 +0,0 @@
// Copyright (C) 2010, Guy Barrand. All rights reserved.
// See the file tools.license for terms.
#ifndef tools_sargs
#define tools_sargs
#include "S_STRING"
namespace tools {
TOOLS_GLOBAL_STRING_VALUE(arg_verbose,-verbose)
TOOLS_GLOBAL_STRING_VALUE(arg_h,-h)
TOOLS_GLOBAL_STRING_VALUE(arg_help,-help)
TOOLS_GLOBAL_STRING_VALUE(arg_version,-version)
TOOLS_GLOBAL_STRING_VALUE(arg_host,-host)
TOOLS_GLOBAL_STRING_VALUE(arg_port,-port)
TOOLS_GLOBAL_STRING_VALUE(arg_can_shutdown,-can_shutdown)
TOOLS_GLOBAL_STRING_VALUE(arg_land,-land)
TOOLS_GLOBAL_STRING_VALUE(arg_document,-document)
TOOLS_GLOBAL_STRING_VALUE(arg_orders,-orders)
TOOLS_GLOBAL_STRING_VALUE(arg_black,-black)
TOOLS_GLOBAL_STRING_VALUE(arg_full_screen,-full_screen)
TOOLS_GLOBAL_STRING_VALUE(arg_no_decos,-no_decos)
TOOLS_GLOBAL_STRING_VALUE(arg_solid,-solid)
TOOLS_GLOBAL_STRING_VALUE(arg_monitor,-monitor)
TOOLS_GLOBAL_STRING_VALUE(arg_monitors,-monitors)
TOOLS_GLOBAL_STRING_VALUE(arg_terminal,-terminal)
TOOLS_GLOBAL_STRING_VALUE(arg_arg0,-arg0)
}
#endif
-25
View File
@@ -1,25 +0,0 @@
// Copyright (C) 2010, Guy Barrand. All rights reserved.
// See the file tools.license for terms.
#ifndef tools_serrno
#define tools_serrno
#include <cerrno>
#include <cstring>
#include <sstream>
namespace tools {
inline void serrno(std::string& a_s) {
std::ostringstream strm;
strm << (int)errno;
a_s = " error : ";
a_s += strm.str();
a_s += " : ";
a_s += strerror(errno);
a_s += ".";
}
}
#endif
@@ -1,75 +0,0 @@
// Copyright (C) 2010, Guy Barrand. All rights reserved.
// See the file tools.license for terms.
#ifndef tools_sg_GL_plots_viewer
#define tools_sg_GL_plots_viewer
// used in geant4 plotting.
#include <tools/sg/plots_viewer>
#include <tools/sg/base_freetype>
#include "GL_manager"
#include "GL_action"
namespace tools {
namespace sg {
class GL_plots_viewer : public tools::sg::plots_viewer {
TOOLS_HEADER(GL_plots_viewer,tools::sg::GL_plots_viewer,tools::sg::plots_viewer)
public:
void render() {
if(!m_ww) return;
if(!m_wh) return;
m_gl_mgr.begin_render(0,0,m_ww,m_wh,
m_clear_color.r(),
m_clear_color.g(),
m_clear_color.b(),
m_clear_color.a());
GL_action action(m_gl_mgr,m_out,m_ww,m_wh);
action.state().m_use_gsto = m_use_gsto;
m_sg.render(action);
if(!action.end()) { //check that matrices stack are ok.
m_out << "exib::sg::GL_plots_viewer :"
<< " bad gl_action end."
<< std::endl;
}
//after_render();
m_gl_mgr.end_render();
}
public:
GL_plots_viewer(std::ostream& a_out,const tools::sg::base_freetype& a_ttf,
unsigned int a_cols = 1,unsigned int a_rows = 1,
unsigned int a_width = 500,unsigned int a_height = 500)
:parent(a_out,a_ttf,a_cols,a_rows,a_width,a_height)
,m_gl_mgr(a_out)
{}
virtual ~GL_plots_viewer(){
//WARNING : nodes may refer m_gl_mgr (to handle gstos/texs), then we have to delete them first.
m_sg.clear();
m_plots.clear_sg();
}
public:
GL_plots_viewer(const GL_plots_viewer& a_from)
:parent(a_from)
,m_gl_mgr(a_from.m_gl_mgr)
{}
GL_plots_viewer& operator=(const GL_plots_viewer& a_from){
parent::operator=(a_from);
m_gl_mgr = a_from.m_gl_mgr;
return *this;
}
protected:
GL_manager m_gl_mgr;
};
}}
#endif
+12 -3
View File
@@ -28,11 +28,20 @@ public:
GL_action action(m_gl_mgr,m_out,m_ww,m_wh);
action.state().m_use_gsto = m_use_gsto;
action.set_do_transparency(false);
action.set_have_to_do_transparency(false);
m_sg.render(action);
if(!action.end()) { //check that matrices stack are ok.
m_out << "exib::sg::GL_viewer :"
<< " bad gl_action end."
<< std::endl;
m_out << "tools::sg::GL_viewer : bad gl_action end." << std::endl;
} else {
if(action.have_to_do_transparency()) {
action.set_do_transparency(true);
m_sg.render(action);
if(!action.end()) { //check that matrices stack are ok.
m_out << "tools::sg::GL_viewer : bad gl_action end." << std::endl;
}
}
}
//after_render();
+19 -8
View File
@@ -123,18 +123,18 @@ public:
if(touched()) {
if(do_back.value()) gen_back();
if(draw_edges.value()) gen_edges();
#ifdef __APPLE__
m_all_a_one = true;
{tools_vforcit_npp(float,rgbas.values(),it) {
if(*(it+3)!=1) {m_all_a_one = false;break;}
it += 4;
}}
#endif //__APPLE__
clean_gstos();
reset_touched();
}
if(xyzs.empty()) return;
if(!have_to_render(a_action)) return;
const state& state = a_action.state();
if(state.m_use_gsto) {
@@ -326,9 +326,7 @@ public:
,m_xyzs_pos(0)
,m_rgbas_pos(0)
,m_nms_pos(0)
#ifdef __APPLE__
,m_all_a_one(true)
#endif
{
#ifdef TOOLS_MEM
mem::increment(s_class().c_str());
@@ -351,9 +349,7 @@ public:
,m_xyzs_pos(a_from.m_xyzs_pos)
,m_rgbas_pos(a_from.m_rgbas_pos)
,m_nms_pos(a_from.m_nms_pos)
#ifdef __APPLE__
,m_all_a_one(true)
#endif
{
#ifdef TOOLS_MEM
mem::increment(s_class().c_str());
@@ -539,6 +535,23 @@ public:
parent::clear();
}
protected:
bool have_to_render(render_action& a_action) {
bool transparent = false;
if(rgbas.size()) {
if(!m_all_a_one) transparent = true;
} else {
if(a_action.state().m_color.a()!=1) transparent = true;
}
if(transparent) {
if(a_action.do_transparency()) return true;
a_action.set_have_to_do_transparency(true);
return false;
} else {
if(a_action.do_transparency()) return false;
}
return true;
}
void gen_back(){
m_back_xyzs.clear();
m_back_nms.clear();
@@ -688,9 +701,7 @@ protected:
size_t m_xyzs_pos;
size_t m_rgbas_pos;
size_t m_nms_pos;
#ifdef __APPLE__
bool m_all_a_one;
#endif
};
}}
+40 -4
View File
@@ -7,6 +7,7 @@
#include "base_text"
#include "gstos"
#include "sf_string"
#include <map>
// abstract class to handle freetype text.
@@ -73,6 +74,8 @@ public:
,modeling(a_from.modeling)
,unitext(a_from.unitext)
//,font_dirs(a_from.font_dirs)
,m_fonts(a_from.m_fonts)
,m_finders(a_from.m_finders)
{
add_fields();
}
@@ -85,9 +88,15 @@ public:
modeling = a_from.modeling;
unitext = a_from.unitext;
//font_dirs = a_from.font_dirs;
m_fonts = a_from.m_fonts;
m_finders = a_from.m_finders;
return *this;
}
public:
static base_freetype* create(const base_freetype& a_ttf) {
return safe_cast<node,base_freetype>(*(a_ttf.copy()));
}
public:
void dump_unitext(std::ostream& a_out) {
//unitext.values().size()
@@ -104,11 +113,38 @@ public:
a_out << "end line." << std::endl;
}
}
public:
static base_freetype* create(const base_freetype& a_ttf) {
return safe_cast<node,base_freetype>(*(a_ttf.copy()));
public:
typedef const unsigned char*(*font_getter)(unsigned int&);
void add_embedded_font(const std::string& a_name,font_getter a_getter) {
unsigned int size;
const unsigned char* buffer = a_getter(size);
m_fonts[a_name] = embedded_font(size,buffer); //warning: we do not take ownership of buffer.
}
typedef std::pair<unsigned int,const unsigned char*> embedded_font;
void add_embedded_font(const std::string& a_name,unsigned int a_size,const unsigned char* a_buffer) {
//warning: we do not take ownership of a_buffer.
m_fonts[a_name] = embedded_font(a_size,a_buffer);
}
bool find_embedded_font(const std::string& a_name,unsigned int& a_size,const unsigned char*& a_buffer) {
std::map<std::string,embedded_font>::const_iterator it = m_fonts.find(a_name);
if(it==m_fonts.end()) {a_size = 0;a_buffer = 0;return false;}
a_size = (*it).second.first;
a_buffer = (*it).second.second;
return true;
}
public:
typedef bool(*font_finder)(const std::string&,std::string&);
void add_font_finder(font_finder a_finder) {m_finders.push_back(a_finder);}
bool find_font_with_finders(const std::string& a_name,std::string& a_font) {
tools_vforcit(font_finder,m_finders,it) {
if((*it)(a_name,a_font)) return true;
}
a_font.clear();
return false;
}
protected:
std::map<std::string,embedded_font> m_fonts;
std::vector<font_finder> m_finders;
};
}}
+132
View File
@@ -0,0 +1,132 @@
// Copyright (C) 2010, Guy Barrand. All rights reserved.
// See the file tools.license for terms.
#ifndef tools_sg_bcbk
#define tools_sg_bcbk
// "cbk" is for callback. Base class to handle a callback.
#ifdef TOOLS_MEM
#include "../mem"
#endif
#include "../scast"
#include "../S_STRING"
#include <string>
namespace tools {
namespace sg {
enum return_action {
return_none,
return_to_render
};
class bcbk {
public:
TOOLS_SCLASS(tools::sg::bcbk)
public:
virtual void* cast(const std::string& a_class) const {
if(void* p = cmp_cast<bcbk>(this,a_class)) {return p;}
return 0;
}
virtual const std::string& s_cls() const {return s_class();}
public:
virtual return_action action() = 0;
virtual bcbk* copy() const = 0;
//virtual bool equal(const bcbk&) const = 0; //it would need the upper cast.
public:
virtual ~bcbk(){
#ifdef TOOLS_MEM
mem::decrement(s_class().c_str());
#endif
}
protected:
bcbk()
:m_single_shoot(false)
,m_is_valid(true)
{
#ifdef TOOLS_MEM
mem::increment(s_class().c_str());
#endif
}
bcbk(const bcbk& a_from)
:m_single_shoot(a_from.m_single_shoot)
,m_is_valid(a_from.m_is_valid)
{
#ifdef TOOLS_MEM
mem::increment(s_class().c_str());
#endif
}
bcbk& operator=(const bcbk& a_from){
m_single_shoot = a_from.m_single_shoot;
m_is_valid = a_from.m_is_valid;
return *this;
}
public:
void set_single_shoot(bool a_value) {m_single_shoot = a_value;}
bool is_single_shoot() const {return m_single_shoot;}
bool is_valid() const {return m_is_valid;}
void invalidate() {m_is_valid = false;}
protected:
bool m_single_shoot;
bool m_is_valid;
};
}}
#define TOOLS_CBK(a__class,a__sclass,a__parent)\
private:\
typedef a__parent parent;\
public:\
TOOLS_SCLASS(a__sclass)\
public:\
virtual void* cast(const std::string& a_class) const {\
if(void* p = tools::cmp_cast<a__class>(this,a_class)) return p;\
return parent::cast(a_class);\
}\
virtual const std::string& s_cls() const {return s_class();}\
virtual tools::sg::bcbk* copy() const {return new a__class(*this);}
#define TOOLS_T_CBK(a__T,a__class,a__sclass,a__parent)\
private:\
typedef a__parent parent;\
public:\
TOOLS_T_SCLASS(a__T,a__sclass)\
public:\
virtual void* cast(const std::string& a_class) const {\
if(void* p = tools::cmp_cast<a__class>(this,a_class)) return p;\
return parent::cast(a_class);\
}\
virtual const std::string& s_cls() const {return s_class();}\
virtual tools::sg::bcbk* copy() const {return new a__class(*this);}
#define TOOLS_T2_CBK(a__T1,a__T2,a__class,a__sclass,a__parent)\
private:\
typedef a__parent parent;\
public:\
TOOLS_T2_SCLASS(a__T1,a__T2,a__sclass)\
public:\
virtual void* cast(const std::string& a_class) const {\
if(void* p = tools::cmp_cast<a__class>(this,a_class)) return p;\
return parent::cast(a_class);\
}\
virtual const std::string& s_cls() const {return s_class();}\
virtual tools::sg::bcbk* copy() const {return new a__class(*this);}
#define TOOLS_T3_CBK(a__T1,a__T2,a__T3,a__class,a__sclass,a__parent)\
private:\
typedef a__parent parent;\
public:\
TOOLS_T3_SCLASS(a__T1,a__T2,a__T3,a__sclass)\
public:\
virtual void* cast(const std::string& a_class) const {\
if(void* p = tools::cmp_cast<a__class>(this,a_class)) return p;\
return parent::cast(a_class);\
}\
virtual const std::string& s_cls() const {return s_class();}\
virtual tools::sg::bcbk* copy() const {return new a__class(*this);}
#endif
+57
View File
@@ -0,0 +1,57 @@
// Copyright (C) 2010, Guy Barrand. All rights reserved.
// See the file tools.license for terms.
#ifndef tools_sg_cbks
#define tools_sg_cbks
// A dedicated container for callbacks.
#include "bcbk"
#include "../forit"
#include "../vmanip"
#include <vector>
namespace tools {
namespace sg {
class cbks {
public:
cbks() {}
virtual ~cbks(){clear();}
public:
cbks(const cbks& a_from){copy(a_from);}
cbks& operator=(const cbks& a_from){
if(&a_from==this) return *this;
copy(a_from);
return *this;
}
public:
void add(bcbk* a_cbk) {
//we take ownership of a_cbk
m_cbks.push_back(a_cbk);
}
void copy(const cbks& a_from,bool a_clear = true) {
if(&a_from==this) return;
if(a_clear) clear();
tools_vforcit(bcbk*,a_from.m_cbks,it) m_cbks.push_back((*it)->copy());
}
void clear() {
safe_clear<bcbk>(m_cbks);
}
void do_actions() const {
// WARNING : dangerous. Used by offscreen apps.
tools_vforcit(bcbk*,m_cbks,it) (*it)->action();
}
const std::vector<bcbk*>& callbacks() const {return m_cbks;}
std::vector<bcbk*>& callbacks() {return m_cbks;}
bool is_empty() const {return m_cbks.empty();}
protected:
std::vector<bcbk*> m_cbks;
};
}}
#endif
-86
View File
@@ -1,86 +0,0 @@
// Copyright (C) 2010, Guy Barrand. All rights reserved.
// See the file tools.license for terms.
#ifndef tools_sg_color
#define tools_sg_color
#include "node"
#include "sf_vec"
#include "render_action"
#include "../colorf"
namespace tools {
namespace sg {
class color : public node {
TOOLS_NODE(color,tools::sg::color,node)
public:
sf_vec<colorf,float> rgb;
sf<float> transparency; //alpha=1-transparency. Opaque is transparency=0.
public:
virtual const desc_fields& node_desc_fields() const {
TOOLS_FIELD_DESC_NODE_CLASS(tools::sg::color)
static const desc_fields s_v(parent::node_desc_fields(),2, //WARNING : take care of count.
TOOLS_ARG_FIELD_DESC(rgb),
TOOLS_ARG_FIELD_DESC(transparency)
);
return s_v;
}
private:
void add_fields(){
add_field(&rgb);
add_field(&transparency);
}
public:
virtual void render(render_action& a_action) {
// GL-ES : ::glMaterialfv does not work. We then use :
// ::glEnable(GL_COLOR_MATERIAL) and ::glColor.
//if(a_action.state().m_GL_LIGHTING) {
// float params[4];
// params[0] = rgb.value().r();
// params[1] = rgb.value().g();
// params[2] = rgb.value().b();
// params[3] = 1-transparency.value();
// ::glMaterialfv(GL_FRONT,GL_DIFFUSE,params);
//} else {
//}
state& state = a_action.state();
state.m_color[0] = rgb.value().r();
state.m_color[1] = rgb.value().g();
state.m_color[2] = rgb.value().b();
state.m_color[3] = 1-transparency.value();
a_action.color4f(state.m_color);
}
public:
color()
:parent()
,rgb(colorf_default())
,transparency(0.0f)
{
add_fields();
}
virtual ~color(){}
public:
color(const color& a_from)
:parent(a_from)
,rgb(a_from.rgb)
,transparency(a_from.transparency)
{
add_fields();
}
color& operator=(const color& a_from){
parent::operator=(a_from);
rgb = a_from.rgb;
transparency = a_from.transparency;
return *this;
}
};
}}
#endif
+118
View File
@@ -0,0 +1,118 @@
// Copyright (C) 2010, Guy Barrand. All rights reserved.
// See the file tools.license for terms.
#ifndef tools_sg_ecbk
#define tools_sg_ecbk
// A callback class to handle a response to some event
// (viewer/window size, mouse button press, etc...).
// It is typically used through the event_dispatcher node.
#include "bcbk"
#include "event"
#include "event_action"
#include "../forit"
#include "../HEADER"
#include <vector>
namespace tools {
namespace sg {
class node;
}}
namespace tools {
namespace sg {
class ecbk : public bcbk {
TOOLS_HEADER(ecbk,tools::sg::ecbk,bcbk)
public:
ecbk(unsigned int a_action = 0)
:parent()
,m_action(a_action)
,m_no_set_done(false)
,m_event(0)
,m_event_action(0)
,m_node(0)
,m_z(0)
,m_w(0)
{}
virtual ~ecbk(){delete m_event;}
public:
ecbk(const ecbk& a_from)
:parent(a_from)
,m_action(a_from.m_action)
,m_no_set_done(a_from.m_no_set_done)
,m_event(0)
,m_event_action(a_from.m_event_action)
,m_node(a_from.m_node)
,m_z(a_from.m_z)
,m_w(a_from.m_w)
{
if(a_from.m_event) m_event = a_from.m_event->copy();
}
ecbk& operator=(const ecbk& a_from){
parent::operator=(a_from);
m_action = a_from.m_action;
m_no_set_done = a_from.m_no_set_done;
delete m_event;
m_event = 0;
if(a_from.m_event) m_event = a_from.m_event->copy();
m_event_action = a_from.m_event_action;
m_node = a_from.m_node;
m_z = a_from.m_z;
m_w = a_from.m_w;
return *this;
}
public:
void set_action(unsigned int a_v){m_action = a_v;}
void set_no_set_done(bool a_v) {m_no_set_done = a_v;}
// for ArcheryTune :
event& event_ref() const {return *m_event;}
event_action& event_action_ref() const {return *m_event_action;}
public:
static void exec_event_cbks(const std::vector<bcbk*>& a_cbks,
const event& a_evt,
event_action* a_action,
node* a_node,
float a_z = 0,float a_w = 0) {
tools_vforcit(bcbk*,a_cbks,it) {
bcbk* _cbk = (*it)->copy();
if(ecbk* _ecbk = safe_cast<bcbk,ecbk>(*_cbk)){
delete _ecbk->m_event;
_ecbk->m_event = a_evt.copy();
_ecbk->m_event_action = a_action;
_ecbk->m_node = a_node;
_ecbk->m_z = a_z;
_ecbk->m_w = a_w;
_ecbk->action();
if(a_action->done()) {
delete _cbk;
break;
}
}
delete _cbk;
}
}
public:
unsigned int m_action;
bool m_no_set_done; //to tell not doing m_event_action->set_done(true).
event* m_event; //owner
event_action* m_event_action; //not owner.
node* m_node; //not owner.
float m_z;
float m_w;
};
}}
#endif
@@ -0,0 +1,48 @@
// Copyright (C) 2010, Guy Barrand. All rights reserved.
// See the file tools.license for terms.
#ifndef tools_sg_event_dispatcher
#define tools_sg_event_dispatcher
// Node that holds "callbacks" that can be triggered when an event_action
// traversed it. A typical example is to handle a mouse resize of the viewer/window
// and response to it by changing some geomtry in the scene graphs (for example
// to arrange that a tools::sg::plots maps the full viewer/window area).
#include "node"
#include "cbks"
#include "event_action"
#include "ecbk"
namespace tools {
namespace sg {
class event_dispatcher : public node {
TOOLS_NODE(event_dispatcher,tools::sg::event_dispatcher,node)
public:
virtual void event(event_action& a_action) {
ecbk::exec_event_cbks(m_cbks.callbacks(),a_action.get_event(),&a_action,this);
}
public:
event_dispatcher():parent(),m_cbks(){}
virtual ~event_dispatcher(){}
public:
event_dispatcher(const event_dispatcher& a_from):parent(a_from),m_cbks(a_from.m_cbks){}
event_dispatcher& operator=(const event_dispatcher& a_from){
parent::operator=(a_from);
m_cbks = a_from.m_cbks;
return *this;
}
public:
const sg::cbks& cbks() const {return m_cbks;}
//sg::cbks& cbks() {return m_cbks;}
void add_callback(bcbk* a_cbk) {m_cbks.add(a_cbk);} //we take ownership of a_cbk
void copy_cbks(const sg::cbks& a_from,bool a_clear = true) {m_cbks.copy(a_from,a_clear);}
void clear_cbks(){m_cbks.clear();}
protected:
sg::cbks m_cbks;
};
}}
#endif
@@ -648,6 +648,7 @@ inline bool s2format(const std::string& a_format,int& a_gl2ps_format) {
if(a_format=="gl2ps_svg") {a_gl2ps_format = TOOLS_GL2PS_SVG;return true;}
if(a_format=="gl2ps_tex") {a_gl2ps_format = TOOLS_GL2PS_TEX;return true;}
if(a_format=="gl2ps_pgf") {a_gl2ps_format = TOOLS_GL2PS_PGF;return true;}
a_gl2ps_format = TOOLS_GL2PS_PS;
return false;
}
+36
View File
@@ -0,0 +1,36 @@
// Copyright (C) 2010, Guy Barrand. All rights reserved.
// See the file tools.license for terms.
#ifndef tools_sg_light_off
#define tools_sg_light_off
// A node to cancel/switch of the lighting during a render traversal.
#include "node"
#include "render_action"
namespace tools {
namespace sg {
class light_off : public node {
TOOLS_NODE(light_off,tools::sg::light_off,node)
public:
virtual void render(render_action& a_action) {
state& state = a_action.state();
state.m_GL_LIGHTING = false;
a_action.set_lighting(false);
}
public:
light_off():parent() {}
virtual ~light_off(){}
public:
light_off(const light_off& a_from):parent(a_from){}
light_off& operator=(const light_off& a_from){
parent::operator=(a_from);
return *this;
}
};
}}
#endif
-114
View File
@@ -1,114 +0,0 @@
// Copyright (C) 2010, Guy Barrand. All rights reserved.
// See the file tools.license for terms.
#ifndef tools_sg_line_set
#define tools_sg_line_set
#include "node"
#include "mf"
#include "../stype"
#include "render_action"
#include "pick_action"
#include "bbox_action"
namespace tools {
namespace sg {
class line_set : public node {
TOOLS_NODE(line_set,tools::sg::line_set,node)
public:
mf_std_vec<float> lines;
public:
virtual const desc_fields& node_desc_fields() const {
TOOLS_FIELD_DESC_NODE_CLASS(tools::sg::line_set)
static const desc_fields s_v(parent::node_desc_fields(),1, //WARNING : take care of count.
TOOLS_ARG_FIELD_DESC(lines)
);
return s_v;
}
private:
void add_fields(){
add_field(&lines);
}
public:
typedef std::vector<float> line_t;
virtual void render(render_action& a_action) {
tools_vforcit(line_t,lines.values(),it) {
a_action.draw_vertex_array(gl::line_strip(),*it);
}
}
virtual void pick(pick_action& a_action) {
if(a_action.stop_at_first()){
tools_vforcit(line_t,lines.values(),it) {
a_action.add_line_strip(*it);
if(a_action.done()) {
a_action.set_node(this);
return;
}
}
} else {
tools_vforcit(line_t,lines.values(),it) {
a_action.set_done(false);
a_action.zs().clear();
a_action.ws().clear();
a_action.add_line_strip(*it);
if(a_action.done()) {
a_action.add_pick(*this,a_action.zs(),a_action.ws(),a_action.state());
a_action.set_done(false);
}
}
}
}
virtual void bbox(bbox_action& a_action) {
tools_vforcit(line_t,lines.values(),it) {
a_action.add_points(*it);
}
}
public:
line_set()
:parent()
,lines()
{
#ifdef TOOLS_MEM
mem::increment(s_class().c_str());
#endif
add_fields();
}
virtual ~line_set(){
#ifdef TOOLS_MEM
mem::decrement(s_class().c_str());
#endif
}
public:
line_set(const line_set& a_from)
:parent(a_from)
,lines(a_from.lines)
{
#ifdef TOOLS_MEM
mem::increment(s_class().c_str());
#endif
add_fields();
}
line_set& operator=(const line_set& a_from){
parent::operator=(a_from);
lines = a_from.lines;
return *this;
}
public:
bool add(const line_t& a_line) {
size_t npoint = a_line.size()/3;
if(npoint*3!=a_line.size()) return false;
lines.add(a_line);
return true;
}
void clear() {lines.clear();}
};
}}
#endif
+169
View File
@@ -0,0 +1,169 @@
// Copyright (C) 2010, Guy Barrand. All rights reserved.
// See the file tools.license for terms.
//
// Helper functions to handle node(s) paths in a scene graph.
//
#ifndef tools_sg_path
#define tools_sg_path
#include "node"
#include "noderef"
#include "../pointer"
namespace tools {
namespace sg {
typedef std::vector<node*> path_t;
inline bool parent_class(const path_t& a_path,std::string& a_class) {
if(a_path.size()<2) {a_class.clear();return false;}
node* parent = a_path[a_path.size()-2];
a_class = parent->s_cls();
return true;
}
template <class NODE>
inline NODE* rfind(const path_t& a_path) {
path_t::const_reverse_iterator it;
for(it=a_path.rbegin();it!=a_path.rend();++it){
if(NODE* par = safe_cast<node,NODE>(*(*it))) return par;
}
return 0;
}
template <class NODE>
inline NODE* tail(const path_t& a_path) {
if(a_path.empty()) return 0;
node* _node = a_path[a_path.size()-1];
return safe_cast<node,NODE>(*_node);
}
inline bool remove_tail(path_t& a_path) {
if(a_path.empty()) return false;
a_path.resize(a_path.size()-1);
return true;
}
template <class CONTAINER>
inline CONTAINER* container(const path_t& a_path) {
if(a_path.size()<2) return 0;
node* parent = a_path[a_path.size()-2];
return safe_cast<node,CONTAINER>(*parent);
}
template <class CONTAINER>
inline CONTAINER* container_container(const path_t& a_path) {
if(a_path.size()<3) return 0;
node* parent = a_path[a_path.size()-3];
return safe_cast<node,CONTAINER>(*parent);
}
inline void dump(std::ostream& a_out,const path_t& a_path) {
a_out << "tools::sg::dump : path size " << a_path.size() << std::endl;
std::string s;
path_t::const_iterator it;
for(it=a_path.begin();it!=a_path.end();++it){
if(!p2s(*it,s)) {}
a_out << " " << s << " " << (*it)->s_cls();
if(noderef* _ref = safe_cast<node,noderef>(*(*it))) {
if(!p2s(&(_ref->node()),s)) {}
a_out << ", " << s << " " << _ref->node().s_cls();
}
a_out << std::endl;
}
}
//#define TOOLS_RFIND_DEBUG
template <class WHAT,class CONTAINER>
inline bool rfind(const path_t& a_path,const node& a_from,
CONTAINER*& a_container,WHAT*& a_what,
int& a_container_index){
node* from = (node*)&a_from;
path_t::size_type sz = a_path.size();
#ifdef TOOLS_RFIND_DEBUG
::printf("debug : rfind : from %s, a_path.size() %d\n",a_from.s_cls().c_str(),sz);
//::printf("debug : rfind : search node of class %s\n",typename WHAT::s_cls().c_str());
#endif
for(size_t index=1;index<sz;index++) {
node* _node = a_path[sz-index-1];
#ifdef TOOLS_RFIND_DEBUG
::printf("debug : rfind : index %d, node %s\n",index,_node->s_cls().c_str());
#endif
a_container = safe_cast<node,CONTAINER>(*_node);
if(a_container) {
#ifdef TOOLS_RFIND_DEBUG
::printf("debug : rfind : node is a container of size %d\n",a_container->size());
#endif
//the below does not compile.
//a_what = a_container->rsearch_from<WHAT>(from);
//if(a_what) return true;
void* p = a_container->rsearch_from(from,WHAT::s_class(),false);
if(p) {
#ifdef TOOLS_RFIND_DEBUG
::printf("debug : rfind : found in container %lu\n",p);
#endif
a_what = (WHAT*)p;
a_container_index = int(sz-index-1);
return true;
}
from = a_container;
} else if(noderef* _ref = safe_cast<node,noderef>(*_node)) {
#ifdef TOOLS_RFIND_DEBUG
::printf("debug : rfind : node is a noderef with a %s\n",_ref->node().s_cls().c_str());
#endif
from = _ref;
} else { // weird case :
#ifdef TOOLS_RFIND_DEBUG
::printf("debug : rfind : weird case\n");
#endif
break;
}
}
#ifdef TOOLS_RFIND_DEBUG
::printf("debug : rfind : failed\n");
#endif
a_what = 0;
a_container = 0;
a_container_index = -1;
return false;
}
#ifdef TOOLS_RFIND_DEBUG
#undef TOOLS_RFIND_DEBUG
#endif
template <class WHAT,class CONTAINER>
inline bool find_top(const path_t& a_path,const node& a_from,
CONTAINER*& a_container,WHAT*& a_what,
int& a_container_index){
a_what = 0;
a_container = 0;
a_container_index = -1;
path_t _path = a_path;
node* from = (node*)&a_from;
while(true) {
CONTAINER* container;
WHAT* what;
int idx; //index in path of container.
if(!sg::rfind<WHAT,CONTAINER>(_path,*from,container,what,idx)) {
break;
}
a_container = container;
a_what = what;
a_container_index = idx;
_path.resize(idx+1);
_path.push_back(what);
from = what;
}
return a_container?true:false;
}
typedef std::vector<path_t> paths_t;
}}
#endif
@@ -0,0 +1,360 @@
// Copyright (C) 2010, Guy Barrand. All rights reserved.
// See the file tools.license for terms.
#ifndef tools_sg_plotter_some_styles
#define tools_sg_plotter_some_styles
// Functions to set some common styles.
// Typically ROOT_default (the default style of ROOT), hippodraw
// or return/reset to the default inlib style.
#include "plotter"
#include "style_colormap"
namespace tools {
namespace sg {
inline bool set_style_color(std::ostream& a_out,const cmaps_t& a_cmaps,const std::string& a_s,colorf& a_col){
if(!find_color(a_cmaps,a_s,a_col)) {
a_out << "tools::sg::set_style_color: color " << sout(a_s) << " not found." << std::endl;
return false;
}
return true;
}
// a_font = font_arialbd_ttf(); //idem ROOT 62.
// a_font = font_roboto_bold_ttf(); //open source replacement for arialbd.
inline void set_style_font(text_style& a_style,const std::string& a_font){
a_style.font = a_font;
a_style.front_face = winding_cw;
a_style.smoothing = true;
}
inline void set_ROOT_default_style(std::ostream& a_out,const cmaps_t& a_cmaps,plotter& a_plotter,const std::string& a_font) {
a_plotter.value_top_margin = 0.05f;
a_plotter.bottom_margin = 0.1f;
a_plotter.top_margin = 0.1f;
a_plotter.left_margin = 0.1f;
a_plotter.right_margin = 0.1f;
{style& _style = a_plotter.background_style();
_style.visible = true;
//if(!set_style_color(a_out,a_cmaps,"ROOT/grey19",_style.back_color.value())) {}
//border:
if(!set_style_color(a_out,a_cmaps,"black",_style.color.value())) {}
_style.line_width = 0.003; // 0 = no border. In % of width.
}
// <!-- <style name="wall_style"><visible>false</visible></style> -->
{style& _style = a_plotter.grid_style();
_style.visible = false;
//if(!set_style_color(a_out,a_cmaps,"white",_style.color.value())) {}
}
// plot title done with the title_box (and not plotter title):
{text_style& _style = a_plotter.title_style();
_style.visible = false;
}
{text_style& _style = a_plotter.title_box_style();
_style.visible = true;
if(!set_style_color(a_out,a_cmaps,"ROOT/grey19",_style.back_color.value())) {}
_style.back_shadow = 0.015f; //% of width.
if(!set_style_color(a_out,a_cmaps,"black",_style.color.value())) {}
set_style_font(_style,a_font);}
a_plotter.infos_width = 0.35f;
a_plotter.infos_x_margin = 0.01f; //from right border.
a_plotter.infos_y_margin = 0.005f; //from top border.
{text_style& _style = a_plotter.infos_style();
_style.visible = true;
if(!set_style_color(a_out,a_cmaps,"ROOT/grey19",_style.back_color.value())) {}
_style.back_shadow = 0.015f; //% of width.
if(!set_style_color(a_out,a_cmaps,"black",_style.color.value())) {}
_style.modeling = infos_modeling_ROOT(); //to have histo name as info title.
set_style_font(_style,a_font);}
{style& _style = a_plotter.inner_frame_style();
_style.visible = true;
if(!set_style_color(a_out,a_cmaps,"black",_style.color.value())) {}
_style.line_width = 1.0f;
//_style.line_pattern = line_solid;
}
//////////////////////////////////////////////////////////
/// x axis: //////////////////////////////////////////////
//////////////////////////////////////////////////////////
{axis& _axis = a_plotter.x_axis();
_axis.modeling = tick_modeling_hplot();
_axis.divisions = 510;
_axis.title_hjust = right;
_axis.label_to_axis = 0.005f;
_axis.label_height = 0.04f;
_axis.tick_length = 0.03f;
_axis.title_to_axis = 0.05f; //YLAB = 0.05
_axis.title_height = 0.04f;
_axis.is_log = false;
{line_style& _style = _axis.line_style();
if(!set_style_color(a_out,a_cmaps,"black",_style.color.value())) {}
_style.width = 1.0f;}
{line_style& _style = _axis.ticks_style();
if(!set_style_color(a_out,a_cmaps,"black",_style.color.value())) {}
_style.width = 1.0f;}
{text_style& _style = _axis.labels_style();
if(!set_style_color(a_out,a_cmaps,"black",_style.color.value())) {}
_style.scale = 0.6; //To have a good matching with ROOT text size.
set_style_font(_style,a_font);}
{text_style& _style = _axis.title_style();
_style.visible = true;
if(!set_style_color(a_out,a_cmaps,"black",_style.color.value())) {}
_style.scale = 0.6; //To have a good matching with ROOT text size.
set_style_font(_style,a_font);}
{text_style& _style = _axis.mag_style();
if(!set_style_color(a_out,a_cmaps,"black",_style.color.value())) {}
_style.scale = 0.6; //To have a good matching with ROOT text size.
set_style_font(_style,a_font);}
}
//////////////////////////////////////////////////////////
/// y axis: //////////////////////////////////////////////
//////////////////////////////////////////////////////////
{axis& _axis = a_plotter.y_axis();
_axis.modeling = tick_modeling_hplot();
_axis.divisions = 510;
_axis.title_hjust = right;
_axis.label_to_axis = 0.005f;
_axis.label_height = 0.04f;
_axis.tick_length = 0.03f;
_axis.title_to_axis = 0.07f; //XLAB = 0.07
_axis.title_height = 0.04f;
_axis.is_log = false;
{line_style& _style = _axis.line_style();
if(!set_style_color(a_out,a_cmaps,"black",_style.color.value())) {}
_style.width = 1.0f;}
{line_style& _style = _axis.ticks_style();
if(!set_style_color(a_out,a_cmaps,"black",_style.color.value())) {}
_style.width = 1.0f;}
{text_style& _style = _axis.labels_style();
if(!set_style_color(a_out,a_cmaps,"black",_style.color.value())) {}
_style.scale = 0.6;
set_style_font(_style,a_font);}
{text_style& _style = _axis.title_style();
_style.visible = true;
if(!set_style_color(a_out,a_cmaps,"black",_style.color.value())) {}
_style.scale = 0.6; //To have a good matching with ROOT text size.
set_style_font(_style,a_font);}
{text_style& _style = _axis.mag_style();
if(!set_style_color(a_out,a_cmaps,"black",_style.color.value())) {}
_style.scale = 0.6; //To have a good matching with ROOT text size.
set_style_font(_style,a_font);}
}
//////////////////////////////////////////////////////////
/// z axis: //////////////////////////////////////////////
//////////////////////////////////////////////////////////
{axis& _axis = a_plotter.z_axis();
_axis.modeling = tick_modeling_hplot();
_axis.is_log = false;
{line_style& _style = _axis.line_style();
if(!set_style_color(a_out,a_cmaps,"black",_style.color.value())) {}
_style.width = 1.0f;}
{line_style& _style = _axis.ticks_style();
if(!set_style_color(a_out,a_cmaps,"black",_style.color.value())) {}
_style.width = 1.0f;}
{text_style& _style = _axis.labels_style();
if(!set_style_color(a_out,a_cmaps,"black",_style.color.value())) {}
_style.scale = 0.6;}
{text_style& _style = _axis.title_style();
if(!set_style_color(a_out,a_cmaps,"black",_style.color.value())) {}
_style.scale = 0.6;}
{text_style& _style = _axis.mag_style();
if(!set_style_color(a_out,a_cmaps,"black",_style.color.value())) {}
_style.scale = 0.6;}
}
//////////////////////////////////////////////////////////
/// colormap axis: ///////////////////////////////////////
//////////////////////////////////////////////////////////
{axis& _axis = a_plotter.colormap_axis();
_axis.modeling = tick_modeling_hplot();
_axis.divisions = 510;
_axis.title_hjust = right;
_axis.label_to_axis = 0.005f;
_axis.label_height = 0.04f;
_axis.tick_length = 0.03f;
_axis.title_to_axis = 0.07f; //XLAB = 0.07
_axis.title_height = 0.04f;
_axis.is_log = false;
{line_style& _style = _axis.line_style();
if(!set_style_color(a_out,a_cmaps,"black",_style.color.value())) {}
_style.width = 1.0f;}
{line_style& _style = _axis.ticks_style();
if(!set_style_color(a_out,a_cmaps,"black",_style.color.value())) {}
_style.width = 1.0f;}
{text_style& _style = _axis.labels_style();
if(!set_style_color(a_out,a_cmaps,"black",_style.color.value())) {}
_style.scale = 0.6; //To have a good matching with ROOT text size.
set_style_font(_style,a_font);}
{text_style& _style = _axis.title_style();
_style.visible = true;
if(!set_style_color(a_out,a_cmaps,"black",_style.color.value())) {}
_style.scale = 0.6; //To have a good matching with ROOT text size.
set_style_font(_style,a_font);}
{text_style& _style = _axis.mag_style();
if(!set_style_color(a_out,a_cmaps,"black",_style.color.value())) {}
_style.scale = 0.6; //To have a good matching with ROOT text size.
set_style_font(_style,a_font);}
}
{style& _style = a_plotter.bins_style(0);
_style.modeling = modeling_top_lines();
if(!set_style_color(a_out,a_cmaps,"black",_style.color.value())) {}
_style.line_width = 1.0f;
//_style.line_pattern = line_solid;
}
{style& _style = a_plotter.func_style(0);
_style.modeling = modeling_top_lines();
if(!set_style_color(a_out,a_cmaps,"black",_style.color.value())) {}
_style.line_width = 3.0f;
//_style.line_pattern = line_solid;
}
}
// a_font = font_helvetica_ttf();
// a_font = font_lato_regular_ttf(); //open source replacement for helvetica
inline void set_hippodraw_style(std::ostream& a_out,const cmaps_t& a_cmaps,plotter& a_plotter,const std::string& a_font) {
// In memory of P.Kunz.
a_plotter.value_top_margin = 0.05f;
a_plotter.bottom_margin = 0.12f;
a_plotter.top_margin = 0.16f;
a_plotter.left_margin = 0.16f;
a_plotter.right_margin = 0.16f;
a_plotter.title_to_axis = 0.1f;
a_plotter.title_height = 0.03f;
// <!-- <style name="wall_style"><visible>false</visible></style> -->
{style& _style = a_plotter.grid_style();
_style.visible = false;}
{style& _style = a_plotter.inner_frame_style();
_style.visible = true;}
{text_style& _style = a_plotter.infos_style();
_style.visible = false;}
{text_style& _style = a_plotter.title_style();
set_style_font(_style,a_font);
_style.visible = true;}
//////////////////////////////////////////////////////////
/// x axis: //////////////////////////////////////////////
//////////////////////////////////////////////////////////
{axis& _axis = a_plotter.x_axis();
_axis.modeling = tick_modeling_hippo();
_axis.title_hjust = center;
_axis.label_to_axis = 0.015f;
_axis.title_to_axis = 0.07f;
_axis.title_height = 0.035f;
_axis.label_height = 0.02625f; //0.0175F * 1.5F
{text_style& _style = _axis.title_style();
_style.visible = true;
set_style_font(_style,a_font);}
{text_style& _style = _axis.labels_style();
if(!set_style_color(a_out,a_cmaps,"black",_style.color.value())) {}
set_style_font(_style,a_font);}
}
//////////////////////////////////////////////////////////
/// y axis: //////////////////////////////////////////////
//////////////////////////////////////////////////////////
{axis& _axis = a_plotter.y_axis();
_axis.modeling = tick_modeling_hippo();
_axis.title_hjust = center;
_axis.title_to_axis = 0.2f;
_axis.title_height = 0.035f;
_axis.label_height = 0.02625f; //0.0175F * 1.5F
{text_style& _style = _axis.title_style();
_style.visible = true;
set_style_font(_style,a_font);}
{text_style& _style = _axis.labels_style();
if(!set_style_color(a_out,a_cmaps,"black",_style.color.value())) {}
set_style_font(_style,a_font);}
}
//////////////////////////////////////////////////////////
/// z axis: //////////////////////////////////////////////
//////////////////////////////////////////////////////////
{axis& _axis = a_plotter.z_axis();
{text_style& _style = _axis.title_style();
_style.visible = true;
set_style_font(_style,a_font);}
{text_style& _style = _axis.labels_style();
if(!set_style_color(a_out,a_cmaps,"black",_style.color.value())) {}
set_style_font(_style,a_font);}
}
{style& _style = a_plotter.bins_style(0);
_style.modeling = modeling_top_lines();
if(!set_style_color(a_out,a_cmaps,"black",_style.color.value())) {}
_style.line_width = 1.0f;
//_style.line_pattern = line_solid;
}
{style& _style = a_plotter.func_style(0);
_style.modeling = modeling_top_lines();
if(!set_style_color(a_out,a_cmaps,"black",_style.color.value())) {}
_style.line_width = 1.0f;
//_style.line_pattern = line_solid;
}
{style& _style = a_plotter.errors_style(0);
_style.visible = false;
}
}
inline void set_inlib_default_style(std::ostream&,const cmaps_t&,plotter& a_plotter,const std::string&) {
{axis& _axis = a_plotter.colormap_axis();
_axis.label_to_axis = 0.01f;}
}
}}
#endif
-499
View File
@@ -1,499 +0,0 @@
// Copyright (C) 2010, Guy Barrand. All rights reserved.
// See the file tools.license for terms.
#ifndef tools_sg_polyhedron
#define tools_sg_polyhedron
#include "node"
#include "sf"
#include "render_action"
#include "pick_action"
#include "bbox_action"
#include "state"
#include "render_manager"
#include "gstos"
#include "../hep/sf_polyhedron"
#include "../vmanip"
#include "tessellate"
namespace tools {
namespace sg {
class polyhedron : public node, public gstos {
TOOLS_NODE(polyhedron,tools::sg::polyhedron,node)
public:
hep::sf_polyhedron ph;
sf<bool> solid;
sf<bool> reduced_wire_frame;
sf<bool> enforce_edges;
public:
virtual const desc_fields& node_desc_fields() const {
TOOLS_FIELD_DESC_NODE_CLASS(tools::sg::polyhedron)
static const desc_fields s_v(parent::node_desc_fields(),4, //WARNING : take care of count.
TOOLS_ARG_FIELD_DESC(ph),
TOOLS_ARG_FIELD_DESC(solid),
TOOLS_ARG_FIELD_DESC(reduced_wire_frame),
TOOLS_ARG_FIELD_DESC(enforce_edges)
);
return s_v;
}
private:
void add_fields(){
add_field(&ph);
add_field(&solid);
add_field(&reduced_wire_frame);
add_field(&enforce_edges);
}
public: //node
typedef tessellate::prims_t prims_t;
protected: //gstos
virtual unsigned int create_gsto(std::ostream& a_out,render_manager& a_mgr) {
m_size = 0;
if(solid.value()) {
size_t sz = 0;
if(m_draw_edges) sz += m_xyzs.size();
{tools_vforcit(prims_t,m_primss,itt) {
const prims_t& prims = *itt;
tools_vforcit(tess_prim*,prims,it) {
const tess_prim& item = *(*it);
const std::vector<float>& coords = item.m_coords;
const std::vector<float>& norms = item.m_norms;
if(coords.empty()) continue;
if(norms.size()!=coords.size()) {
a_out << "tools::sg::polyhedron::create_gsto :"
<< " bad number of normals."
<< std::endl;
continue;
}
sz += coords.size()+norms.size();
}
}}
if(sz) {
float* buffer = new float[sz];
char* pos = (char*)buffer;
size_t psz = 0;
if(m_draw_edges) {
if(m_xyzs.size()) {
size_t _sz = m_xyzs.size()*sizeof(float);
::memcpy(pos,vec_data<float>(m_xyzs),_sz);
pos += _sz;
psz += _sz;
m_size = m_xyzs.size();
//m_xyzs.clear(); //we need them for pick,write,...
}
}
{tools_vforcit(prims_t,m_primss,itt) {
const prims_t& prims = *itt;
tools_vforcit(tess_prim*,prims,it) {
tess_prim& item = *(*it);
const std::vector<float>& coords = item.m_coords;
const std::vector<float>& norms = item.m_norms;
if(coords.empty()) continue;
if(norms.size()!=coords.size()) continue;
item.m_size = coords.size();
{item.m_pos_coords = psz;
size_t _sz = coords.size()*sizeof(float);
::memcpy(pos,vec_data<float>(coords),_sz);
pos += _sz;
psz += _sz;}
{item.m_pos_norms = psz;
size_t _sz = norms.size()*sizeof(float);
::memcpy(pos,vec_data<float>(norms),_sz);
pos += _sz;
psz += _sz;}
// we don't need coords, norms for rendering
// but needed for pick,write...
//coords.clear();
//norms.clear();
//we still need m_prims.
}
}}
unsigned int id = a_mgr.create_gsto_from_data(sz,buffer);
delete [] buffer;
return id;
}
} else {
m_size = m_xyzs.size();
return a_mgr.create_gsto_from_data(m_xyzs);
}
return 0;
}
public:
virtual void render(render_action& a_action) {
const state& state = a_action.state();
bool draw_edges = false;
if(solid.value()) {
draw_edges = state.m_GL_LIGHTING?false:true;
if(enforce_edges.value()) draw_edges = true;
}
if( touched() ||
(draw_edges && m_xyzs.empty()) ||
(solid.value() && m_primss.empty()) ){
update_what what = lines;
if(solid.value()) what = draw_edges?faces_and_lines:faces;
update_sg(a_action.out(),what);
reset_touched();
}
unsigned int _id = 0;
if(state.m_use_gsto) {
m_draw_edges = draw_edges;
_id = get_gsto_id(a_action.out(),a_action.render_manager());
} else {
clean_gstos(&a_action.render_manager());
}
//a_action.out() << "debug : tools::sg::polyhedron::render_action :"
// << " m_xyzs.size() " << m_xyzs.size()
// << " m_primss.size() " << m_primss.size()
// << std::endl;
if(solid.value()) {
if(_id) {
a_action.begin_gsto(_id);
if(draw_edges && m_size) {
//Same logic as Inventor SoLightModel.model = BASE_COLOR.
a_action.set_lighting(false);
a_action.color4f(0,0,0,1);
a_action.draw_gsto_v(gl::lines(),m_size/3,0);
//pushes back the filled polygons to avoid z-fighting with lines
a_action.set_polygon_offset(true);
a_action.color4f(state.m_color);
a_action.set_lighting(state.m_GL_LIGHTING);
}
{tools_vforcit(prims_t,m_primss,itt) {
const prims_t& prims = *itt;
tools_vforcit(tess_prim*,prims,it) {
const tess_prim& item = *(*it);
a_action.draw_gsto_vn(item.m_mode,item.m_size/3,item.m_pos_coords,item.m_pos_norms);
}
}}
a_action.set_polygon_offset(state.m_GL_POLYGON_OFFSET_FILL);
a_action.end_gsto();
} else {
if(draw_edges){
if(m_xyzs.size()) {
//Same logic as Inventor SoLightModel.model = BASE_COLOR.
a_action.set_lighting(false);
a_action.color4f(0,0,0,1);
a_action.draw_vertex_array(gl::lines(),m_xyzs);
//pushes back the filled polygons to avoid z-fighting with lines
a_action.set_polygon_offset(true);
a_action.color4f(state.m_color);
a_action.set_lighting(state.m_GL_LIGHTING);
}
}
{tools_vforcit(prims_t,m_primss,itt) {
const prims_t& prims = *itt;
tools_vforcit(tess_prim*,prims,it) {
const tess_prim& item = *(*it);
const std::vector<float>& coords = item.m_coords;
if(coords.empty()) continue;
const std::vector<float>& norms = item.m_norms;
if(norms.size()!=coords.size()) {
a_action.out() << "tools::sg::polyhedron::render :"
<< " bad number of normals."
<< std::endl;
continue;
}
a_action.draw_vertex_normal_array(item.m_mode,coords,norms);
}
}}
a_action.set_polygon_offset(state.m_GL_POLYGON_OFFSET_FILL);
}
} else { //not solid
//Same logic as Inventor SoLightModel.model = BASE_COLOR.
a_action.set_lighting(false); // do we want that ?
if(_id) {
a_action.begin_gsto(_id);
a_action.draw_gsto_v(gl::lines(),m_size/3,0);
a_action.end_gsto();
} else {
a_action.draw_vertex_array(gl::lines(),m_xyzs);
}
a_action.set_lighting(state.m_GL_LIGHTING);
}
}
virtual void bbox(bbox_action& a_action) {
if(touched()) {
update_sg(a_action.out(),lines);
reset_touched();
}
if(solid.value()) {
tools_vforcit(prims_t,m_primss,itt) {
const prims_t& prims = *itt;
tools_vforcit(tess_prim*,prims,it) {
const tess_prim& item = *(*it);
const std::vector<float>& coords = item.m_coords;
a_action.add_points(coords);
}
}
} else {
a_action.add_points(m_xyzs);
}
}
virtual void pick(pick_action& a_action) {
if(touched()) {
update_what what = solid.value()?faces:lines;
update_sg(a_action.out(),what);
reset_touched();
}
if(solid.value()) {
tools_vforcit(prims_t,m_primss,itt) {
const prims_t& prims = *itt;
tools_vforcit(tess_prim*,prims,it) {
const tess_prim& item = *(*it);
const std::vector<float>& coords = item.m_coords;
if(a_action.add__primitive(*this,item.m_mode,coords,true)) return;
}
}
} else {
a_action.add__lines(*this,m_xyzs,true);
}
}
public:
polyhedron()
:parent()
,ph(hep::polyhedron())
,solid(true)
,reduced_wire_frame(true)
,enforce_edges(false)
,m_tess(0)
{
add_fields();
}
virtual ~polyhedron(){
_clear();
delete m_tess;
}
public:
polyhedron(const polyhedron& a_from)
:parent(a_from)
,gstos(a_from)
,ph(a_from.ph)
,solid(a_from.solid)
,reduced_wire_frame(a_from.reduced_wire_frame)
,enforce_edges(a_from.enforce_edges)
,m_xyzs(a_from.m_xyzs)
,m_tess(0)
{
add_fields();
}
polyhedron& operator=(const polyhedron& a_from){
parent::operator=(a_from);
gstos::operator=(a_from);
ph = a_from.ph;
solid = a_from.solid;
reduced_wire_frame = a_from.reduced_wire_frame;
enforce_edges = a_from.enforce_edges;
m_xyzs = a_from.m_xyzs;
return *this;
}
public:
enum update_what {
faces = 0,
lines = 1,
faces_and_lines
};
void update_sg(std::ostream& a_out,const update_what& a_what) {
//a_out << "debug : tools::sg::polyhedron::update_sg" << std::endl;
clean_gstos(); //must reset for all render_manager.
_clear();
const hep::polyhedron& sbPolyhedron = ph.value();
if(sbPolyhedron.GetNoFacets()<=0) {
//a_out << "tools::sg::polyhedron::update_sg : abnormal polyhedron." << std::endl;
return; // Abnormal polyhedron.
}
if((a_what==faces)||(a_what==faces_and_lines)) {
std::vector<double> doubles;
vec3d unitNormal;
vec3d* pV = sbPolyhedron.GetPV();
// Assume all facets are convex quadrilaterals :
bool notLastFace;
do {
notLastFace = sbPolyhedron.GetNextUnitNormal(unitNormal);
doubles.clear(); //begin POLYGON
bool notLastEdge;
int edgeFlag = 1;
do {
// optimize to avoid copying vec3f.
//notLastEdge = sbPolyhedron.GetNextVertex(vertex,edgeFlag);
int index;
notLastEdge = sbPolyhedron.GetNextVertexIndex(index,edgeFlag);
vec3d* vertex = pV+index; //WARNING : must not be modified !
doubles.push_back((*vertex)[0]);
doubles.push_back((*vertex)[1]);
doubles.push_back((*vertex)[2]);
} while (notLastEdge);
if(!m_tess) m_tess = new tessellate(a_out);
m_primss.push_back(prims_t());
prims_t& prims = m_primss.back();
m_tess->do_it(doubles.size()/3,vec_data(doubles),prims);
m_tess->clear();
} while (notLastFace);
}
if((a_what==lines)||(a_what==faces_and_lines)) {
float pvbx = 0;
float pvby = 0;
float pvbz = 0;
float pvex,pvey,pvez;
vec3d unitNormal;
vec3d* pV = sbPolyhedron.GetPV();
bool notLastFace;
do {
notLastFace = sbPolyhedron.GetNextUnitNormal(unitNormal);
// Treat edges :
int edgeFlag = 1;
int prevEdgeFlag = edgeFlag;
bool notLastEdge;
bool firstEdge = true;
do {
int index;
notLastEdge = sbPolyhedron.GetNextVertexIndex(index,edgeFlag);
vec3d* vertex = pV+index; //WARNING : must not be modified !
if(!reduced_wire_frame) edgeFlag = 1;
if(firstEdge) {
if(edgeFlag) {
pvbx = (float)(*vertex)[0];
pvby = (float)(*vertex)[1];
pvbz = (float)(*vertex)[2];
} else {
}
firstEdge = false;
prevEdgeFlag = edgeFlag;
} else {
if(edgeFlag!=prevEdgeFlag) {
if(edgeFlag) { // Pass to a visible edge :
pvbx = (float)(*vertex)[0];
pvby = (float)(*vertex)[1];
pvbz = (float)(*vertex)[2];
} else { // Pass to an invisible edge :
pvex = (float)(*vertex)[0];
pvey = (float)(*vertex)[1];
pvez = (float)(*vertex)[2];
m_xyzs.push_back(pvbx);
m_xyzs.push_back(pvby);
m_xyzs.push_back(pvbz);
m_xyzs.push_back(pvex);
m_xyzs.push_back(pvey);
m_xyzs.push_back(pvez);
}
prevEdgeFlag = edgeFlag;
} else {
if(edgeFlag) {
pvex = (float)(*vertex)[0];
pvey = (float)(*vertex)[1];
pvez = (float)(*vertex)[2];
m_xyzs.push_back(pvbx);
m_xyzs.push_back(pvby);
m_xyzs.push_back(pvbz);
m_xyzs.push_back(pvex);
m_xyzs.push_back(pvey);
m_xyzs.push_back(pvez);
pvbx = pvex;
pvby = pvey;
pvbz = pvez;
} else {
}
}
}
} while (notLastEdge);
} while (notLastFace);
}
}
const std::vector<float>& xyzs() const {return m_xyzs;}
protected:
void _clear(){
tools_vforit(prims_t,m_primss,it) raw_clear(*it);
m_primss.clear();
m_xyzs.clear();
}
protected:
std::vector<float> m_xyzs;
//gluTess
tessellate* m_tess;
std::vector<prims_t> m_primss;
size_t m_size;
bool m_draw_edges;
};
}}
#endif
+27 -1
View File
@@ -77,17 +77,40 @@ public:
virtual sg::render_manager& render_manager() = 0; //sg:: is needed.
public:
render_action(std::ostream& a_out,unsigned int a_ww,unsigned int a_wh)
:parent(a_out,a_ww,a_wh){}
:parent(a_out,a_ww,a_wh)
,m_do_transparency(false)
,m_have_to_do_transparency(false)
{}
virtual ~render_action(){}
public:
render_action(const render_action& a_from)
:parent(a_from)
,m_do_transparency(a_from.m_do_transparency)
,m_have_to_do_transparency(a_from.m_have_to_do_transparency)
{}
render_action& operator=(const render_action& a_from){
parent::operator=(a_from);
m_do_transparency = a_from.m_do_transparency;
m_have_to_do_transparency = a_from.m_have_to_do_transparency;
return *this;
}
public:
void set_do_transparency(bool a_value) {m_do_transparency = a_value;}
bool do_transparency() const {return m_do_transparency;}
void set_have_to_do_transparency(bool a_value) {m_have_to_do_transparency = a_value;}
bool have_to_do_transparency() const {return m_have_to_do_transparency;}
bool have_to_render() {
bool transparent = state().m_color.a()!=1?true:false;
if(transparent) {
if(m_do_transparency) return true;
m_have_to_do_transparency = true;
return false;
}
if(m_do_transparency) return false;
return true;
}
void load_matrices_to_identity() {
load_proj_matrix(m_identity);
load_model_matrix(m_identity);
@@ -288,6 +311,9 @@ public:
}
a_out << "dump_vertex_array_xy : end." << std::endl;
}
protected:
bool m_do_transparency;
bool m_have_to_do_transparency;
};
}}
+150
View File
@@ -0,0 +1,150 @@
// Copyright (C) 2010, Guy Barrand. All rights reserved.
// See the file tools.license for terms.
//
// Helper functions to search node(s) in a scene graph.
//
#ifndef tools_sg_search
#define tools_sg_search
#include "search_action"
#include "node"
namespace tools {
namespace sg {
template <class NODE>
inline NODE* find_first_node_of_class(std::ostream& a_out,node& a_from) {
search_action action(a_out);
action.reset();
action.set_what(search_action::search_node_of_class);
action.set_stop_at_first(true);
action.set_class(NODE::s_class());
a_from.search(action);
const std::vector<void*>& _objs = action.objs();
if(_objs.empty()) return 0;
return (NODE*)_objs[0];
}
inline node* find_first_node_with_class(std::ostream& a_out,node& a_from,const std::string& a_class) {
search_action action(a_out);
action.reset();
action.set_what(search_action::search_node_of_class);
action.set_stop_at_first(true);
action.set_class(a_class);
a_from.search(action);
const std::vector<void*>& _objs = action.objs();
if(_objs.empty()) return 0;
return (node*)_objs[0];
}
}}
#include "path"
namespace tools {
namespace sg {
inline const path_t& find_path(search_action& a_action,node& a_from,node& a_node,bool a_verbose) {
a_action.reset();
a_action.set_what(search_action::search_path_to_node);
a_action.set_node(&a_node);
a_from.search(a_action);
if(!a_action.done()) {
if(a_verbose) {
a_action.out() << "tools::sg::find_path :"
<< " not found node of class " << a_node.s_cls()
<< " from head node of class " << a_from.s_cls()
<< std::endl;
}
a_action.clear_path();
return a_action.path();
}
if(a_verbose) {
a_action.out() << "tools::sg::find_path :"
<< " found node of class " << a_node.s_cls()
<< " from head node of class " << a_from.s_cls()
<< std::endl;
}
const path_t& path = a_action.path();
if(path.empty()) {
if(a_verbose) {
a_action.out() << "tools::sg::find_path :"
<< " node has no path !"
<< std::endl;
}
return path;
}
if(&a_node!=path[path.size()-1]) {
a_action.out() << "tools::sg::find_path :"
<< " node / path tail mismatch !"
<< " node " << a_node.s_cls()
<< " tail " << path[path.size()-1]->s_cls()
<< std::endl;
a_action.clear_path();
return a_action.path();
}
return path;
}
inline const search_action::paths_t& find_paths(search_action& a_action,node& a_from,const std::string& a_class){
a_action.reset();
a_action.set_what(search_action::search_path_to_node_of_class);
a_action.set_class(a_class);
a_from.search(a_action);
return a_action.paths();
}
template <class NODE>
inline const search_action::paths_t& find_paths(search_action& a_action,node& a_from){
a_action.reset();
a_action.set_what(search_action::search_path_to_node_of_class);
a_action.set_class(NODE::s_class());
a_from.search(a_action);
return a_action.paths();
}
template <class NODE>
inline NODE* find_ancestor(std::ostream& a_out,node& a_from,node& a_node,bool a_verbose) {
search_action action(a_out);
return rfind<NODE>(find_path(action,a_from,a_node,a_verbose));
}
template <class CONTAINER>
inline CONTAINER* find_container(std::ostream& a_out,node& a_from,node& a_node,bool a_verbose) {
search_action action(a_out);
return container<CONTAINER>(find_path(action,a_from,a_node,a_verbose));
}
template <class NODE>
inline NODE* search_node(std::ostream& a_out,node& a_from) {
search_action sa(a_out);
const paths_t& paths = find_paths<NODE>(sa,a_from);
tools_vforcit(path_t,paths,it) {
NODE* _node = tail<NODE>(*it);
if(_node) return _node;
}
return 0;
}
template <class SELECTABLE>
inline SELECTABLE* search_selectable(std::ostream& a_out,node& a_from) {
search_action sa(a_out);
const paths_t& paths = find_paths<SELECTABLE>(sa,a_from);
tools_vforcit(path_t,paths,it) {
SELECTABLE* _node = tail<SELECTABLE>(*it);
if(_node && _node->border_visible.value()) return _node;
}
/*
tools_vforcit(sg::path_t,paths,it) {
SELECTABLE* _node = sg::tail<SELECTABLE>(*it);
if(_node) return _node;
}
*/
return 0;
}
}}
#endif
@@ -1,104 +0,0 @@
// Copyright (C) 2010, Guy Barrand. All rights reserved.
// See the file tools.license for terms.
#ifndef tools_sg_set_plotter_camera
#define tools_sg_set_plotter_camera
#include "plotter"
#include "ortho"
namespace tools {
namespace sg {
inline void set_plotter_camera(float a_XSIZ,float a_YSIZ,float a_ZSIZ,
plotter& a_plotter,ortho& a_camera,unsigned int a_ww,unsigned int a_wh) {
if(!a_ww || !a_wh) return;
a_plotter.width.value(a_XSIZ);
a_plotter.height.value(a_YSIZ);
a_plotter.depth.value(a_ZSIZ);
enum plotter_viewport_mapping {
pvp_adjust_viewport,
pvp_leave_alone
};
plotter_viewport_mapping pvp = pvp_adjust_viewport;
//plotter_viewport_mapping pvp = pvp_leave_alone;
typedef plotter::shape_type st_t;
st_t plotter_shape = plotter::xy;
float aspect = float(a_ww)/float(a_wh);
{float XSIZ = a_plotter.width.value();
float YSIZ = a_plotter.height.value();
if((plotter_shape==plotter::xy) &&
(pvp==pvp_adjust_viewport)) {
// Adjust the plotter XSIZ and YSIZ so that YSIZ matches viewport height
// and plotter XSIZ matches viewport width.
// It it the CERN-ROOT and osc-plot logic.
if(aspect>=1) { //w>h
// camera must match in height YSIZ. Adjust XSIZ.
a_plotter.width.value(YSIZ * aspect);
} else {
// camera must match in width XSIZ. Adjust YSIZ.
a_plotter.height.value(XSIZ / aspect);
}
}}
{float camera_znear = 0;
float camera_zfar = 0;
float camera_z_pos = 0;
// if camera ortho :
float camera_height = 0;
float XSIZ = a_plotter.width.value();
float YSIZ = a_plotter.height.value();
float z = 4 * a_plotter.depth.value();
camera_z_pos = z;
camera_znear = 0.01F*z;
camera_zfar = 100*z;
//cam ortho :
if(plotter_shape==plotter::xyz) {
camera_height = YSIZ;
} else {
if(pvp==pvp_leave_alone) {
// Adjust camera so that plotter XSIZ/YSIZ be not distorded.
// If viewport aspect ratio > plotter aspect ratio
// the plotter YSIZ matches the viewport height. If not
// it is the plotter XSIZ that will match the viewport width.
// It is the PAW logic for one region.
float plotterAspect = XSIZ/YSIZ;
if(aspect<plotterAspect) {
camera_height = XSIZ / aspect;
} else {
camera_height = YSIZ;
}
} else if(pvp==pvp_adjust_viewport) {
camera_height = YSIZ;
}
}
a_camera.height.value(camera_height);
a_camera.znear.value(camera_znear);
a_camera.zfar.value(camera_zfar);
a_camera.position.value(vec3f(0,0,camera_z_pos));
a_camera.orientation.value(rotf(vec3f(0,0,1),0));}
}
inline void set_plotter_camera(plotter& a_plotter,ortho& a_camera,unsigned int a_ww,unsigned int a_wh) {
//PAW logic :
float xfac = 1.0F/20.0F; //0.05
float yfac = 1.0F/20.0F; //0.05
float XSIZ = 20 * xfac; //1 //page width
float YSIZ = 20 * yfac; //1 //page height
float zfac = 1.0F/20.0F; //0.05
float ZSIZ = 20 * zfac; //1 //page depth
set_plotter_camera(XSIZ,YSIZ,ZSIZ,a_plotter,a_camera,a_ww,a_wh);
}
}}
#endif
-37
View File
@@ -1,37 +0,0 @@
// Copyright (C) 2010, Guy Barrand. All rights reserved.
// See the file tools.license for terms.
#ifndef tools_sg_sf_vec2f
#define tools_sg_sf_vec2f
#include "sf_vec"
#include "../lina/vec2f"
#include "../HEADER"
namespace tools {
namespace sg {
class sf_vec2f : public sf_vec<vec2f,float> {
typedef sf_vec<vec2f,float> _parent;
TOOLS_HEADER(sf_vec2f,tools::sg::sf_vec2f,_parent)
public:
sf_vec2f():parent(){}
sf_vec2f(const vec2f& a_v):parent(a_v){}
virtual ~sf_vec2f(){}
public:
sf_vec2f(const sf_vec2f& a_from):parent(a_from){}
sf_vec2f& operator=(const sf_vec2f& a_from){
parent::operator=(a_from);
return *this;
}
public:
sf_vec2f& operator+=(const vec2f& a_value) {parent::operator+=(a_value);return *this;}
public: //for iv2sg
void setValue(const vec2f& a_v) {value(a_v);}
void setValue(float a_0,float a_1) {value(vec2f(a_0,a_1));}
};
}}
#endif
-532
View File
@@ -1,532 +0,0 @@
// Copyright (C) 2010, Guy Barrand. All rights reserved.
// See the file tools.license for terms.
#ifndef tools_sg_tessellate
#define tools_sg_tessellate
//#include "../tessellate"
#include <vector>
#include "../glprims"
#ifdef TOOLS_MEM
#include "../mem"
#include "../S_STRING"
#endif
namespace tools {
namespace sg {
class tess_prim {
#ifdef TOOLS_MEM
TOOLS_SCLASS(tools::sg::tess_prim)
#endif
public:
tess_prim()
:m_mode(gl::triangles())
,m_size(0)
,m_pos_coords(0)
,m_pos_norms(0)
{
#ifdef TOOLS_MEM
mem::increment(s_class().c_str());
#endif
}
virtual ~tess_prim(){
#ifdef TOOLS_MEM
mem::decrement(s_class().c_str());
#endif
}
public:
tess_prim(const tess_prim& a_from)
:m_mode(a_from.m_mode)
,m_coords(a_from.m_coords)
,m_norms(a_from.m_norms)
,m_size(a_from.m_size)
,m_pos_coords(a_from.m_pos_coords)
,m_pos_norms(a_from.m_pos_norms)
{
#ifdef TOOLS_MEM
mem::increment(s_class().c_str());
#endif
}
tess_prim& operator=(const tess_prim& a_from){
if(&a_from==this) return *this;
m_mode = a_from.m_mode;
m_coords = a_from.m_coords;
m_norms = a_from.m_norms;
m_size = a_from.m_size;
m_pos_coords = a_from.m_pos_coords;
m_pos_norms = a_from.m_pos_norms;
return *this;
}
public:
gl::mode_t m_mode;
std::vector<float> m_coords;
std::vector<float> m_norms;
//for gsto :
size_t m_size;
typedef size_t bufpos;
bufpos m_pos_coords;
bufpos m_pos_norms;
};
}}
#include "../vdata"
#include "../forit"
#include "primitive_visitor"
#include <ostream>
#include <cmath> //sqrt
#ifdef TOOLS_MEM
#include "../S_STRING"
#include "../mem"
#endif
#include "../glutess/glutess"
namespace tools {
namespace sg {
class tessellate {
#ifdef TOOLS_MEM
TOOLS_SCLASS(tools::sg::tessellate);
#endif
public:
tessellate(std::ostream& a_out):m_out(a_out),m_tobj(0) {
#ifdef TOOLS_MEM
mem::increment(s_class().c_str());
#endif
m_tobj = gluNewTess();
::gluTessCallback(m_tobj,(GLUenum)GLU_TESS_BEGIN_DATA, (Func)begin_cbk);
::gluTessCallback(m_tobj,(GLUenum)GLU_TESS_END_DATA, (Func)end_cbk);
::gluTessCallback(m_tobj,(GLUenum)GLU_TESS_VERTEX_DATA, (Func)vertex_cbk);
::gluTessCallback(m_tobj,(GLUenum)GLU_TESS_COMBINE_DATA,(Func)combine_cbk);
::gluTessCallback(m_tobj,(GLUenum)GLU_TESS_ERROR_DATA, (Func)error_cbk);
//set winding rule to positive => no holes
::gluTessProperty(m_tobj,(GLUenum)GLU_TESS_WINDING_RULE,GLU_TESS_WINDING_POSITIVE);
//m_out << "tools::sg::tessellate::tessellate :"
// << " GL_TRIANGLE_STRIP " << GL_TRIANGLE_STRIP
// << " GL_TRIANGLE_FAN " << GL_TRIANGLE_FAN
// << " GL_TRIANGLES " << GL_TRIANGLES
// << std::endl;
}
virtual ~tessellate(){
::gluDeleteTess(m_tobj);
_clear();
#ifdef TOOLS_MEM
mem::decrement(s_class().c_str());
#endif
}
public:
tessellate(const tessellate& a_from):m_out(a_from.m_out),m_tobj(0) {
#ifdef TOOLS_MEM
mem::increment(s_class().c_str());
#endif
m_tobj = gluNewTess();
::gluTessCallback(m_tobj,(GLUenum)GLU_TESS_BEGIN_DATA, (Func)begin_cbk);
::gluTessCallback(m_tobj,(GLUenum)GLU_TESS_END_DATA, (Func)end_cbk);
::gluTessCallback(m_tobj,(GLUenum)GLU_TESS_VERTEX_DATA, (Func)vertex_cbk);
::gluTessCallback(m_tobj,(GLUenum)GLU_TESS_COMBINE_DATA,(Func)combine_cbk);
::gluTessCallback(m_tobj,(GLUenum)GLU_TESS_ERROR_DATA, (Func)error_cbk);
//set winding rule to positive => no holes
::gluTessProperty(m_tobj,(GLUenum)GLU_TESS_WINDING_RULE,GLU_TESS_WINDING_POSITIVE);
}
tessellate& operator=(const tessellate& a_from){
if(&a_from==this) return *this;
_clear();
return *this;
}
public:
typedef std::vector<tess_prim*> prims_t;
void do_it(size_t a_npt,const double* a_contour,prims_t& a_prims){
::gluTessBeginPolygon(m_tobj,this);
::gluTessBeginContour(m_tobj);
double* pos = (double*)a_contour;
for(size_t i=0;i<a_npt;i++,pos+=3) {
::gluTessVertex(m_tobj,pos,pos);
}
::gluTessEndContour(m_tobj);
a_prims.clear();
m_prims = &a_prims;
m_combine_trids_num = 0;
::gluTessEndPolygon(m_tobj); //trigger callbacks and fill a_prims.
}
void clear(){_clear();}
protected:
typedef _GLUfuncptr Func;
static void GLUAPIENTRY begin_cbk(GLUenum a_which,void* a_this) {
tessellate& self = *((tessellate*)a_this);
self.m_prims->push_back(new tess_prim());
tess_prim& prim = *(self.m_prims->back());
prim.m_mode = a_which;
prim.m_coords.reserve(12); //4 points.
prim.m_norms.reserve(12);
self.m_coords = &prim.m_coords;
//::printf("tools::sg::tessellate::begin_cbk : %d : STRIP %d FAN %d TRIS %d\n",
// a_which,GL_TRIANGLE_STRIP,GL_TRIANGLE_FAN,GL_TRIANGLES);
}
static void GLUAPIENTRY vertex_cbk(void* a_vertex,void* a_this) {
tessellate& self = *((tessellate*)a_this);
double* vertex = (double*)a_vertex;
self.m_coords->push_back(float(vertex[0]));
self.m_coords->push_back(float(vertex[1]));
self.m_coords->push_back(float(vertex[2]));
}
typedef float _vec3f[3];
static void GLUAPIENTRY end_cbk(void* a_this){
tessellate& self = *((tessellate*)a_this);
tess_prim& prim = *(self.m_prims->back());
//self.m_out << "tools::sg::tessellate::end_cbk : "
// << prim.m_coords.size()/3 << std::endl;
add_prm aprm(self.m_out,prim.m_norms);
float* data = vec_data<float>(prim.m_coords);
bool ok = true;
if(prim.m_mode==gl::triangles()) {
if(!aprm.add_triangles(prim.m_coords.size(),data,false)) {
self.m_out << "tools::sg::tessellate::end_cbk : "
<< " add_triangles failed."
<< std::endl;
ok = false;
}
} else if(prim.m_mode==gl::triangle_strip()) {
if(!aprm.add_triangle_strip(prim.m_coords.size(),data,false)){
self.m_out << "tools::sg::tessellate::end_cbk : "
<< " add_triangle_strip failed."
<< std::endl;
ok = false;
}
} else if(prim.m_mode==gl::triangle_fan()) {
if(!aprm.add_triangle_fan(prim.m_coords.size(),data,false)) {
self.m_out << "tools::sg::tessellate::end_cbk : "
<< " add_triangle_fan failed."
<< std::endl;
ok = false;
}
} else {
self.m_out << "tools::sg::tessellate::end_cbk : "
<< " mode " << prim.m_mode << " not yet treated."
<< std::endl;
ok = false;
}
if(!ok) {
size_t num = prim.m_coords.size();
self.m_out << "tools::sg::tessellate::end_cbk :"
<< " primitive anomaly."
<< " num points " << num
<< " mode " << prim.m_mode
<< " (TRIANGLES=4, STRIP=5, FAN=6)."
<< std::endl;
float* pos = vec_data<float>(prim.m_coords);
for(size_t ipt=0;ipt<num;ipt++) {
self.m_out << " " << ipt << " :"
<< " " << *(pos+0)
<< " " << *(pos+1)
<< " " << *(pos+2)
<< std::endl;
pos += 3;
}
prim.m_coords.clear();
prim.m_norms.clear();
}
}
static void GLUAPIENTRY combine_cbk(double a_coords[3],
void* /*a_vertex_data*/[4],
float /*a_weight*/[4],
void** a_data_out,
void* a_this) {
tessellate& self = *((tessellate*)a_this);
double* v = self.add_combine_vec3d(a_coords[0],a_coords[1],a_coords[2]);
//if(!v) ???
*a_data_out = v;
}
static void GLUAPIENTRY error_cbk(GLUenum,void*) {
//const GLubyte* estring = gluErrorString(aErrorCode);
//::fprintf(stderr, "Tessellation Error: %s\n", estring);
//SbTessContour* This = (SbTessContour*)aThis;
//This->setError(true);
}
double* add_combine_vec3d(double a_x,double a_y,double a_z) {
double* v = 0;
if(m_combine_trids_num>=m_combine_trids.size()) {
v = new double[3];
m_combine_trids.push_back(v);
} else {
v = m_combine_trids[m_combine_trids_num];
}
m_combine_trids_num++;
v[0] = a_x;
v[1] = a_y;
v[2] = a_z;
return v;
}
void _clear() {
tools_vforit(double*,m_combine_trids,it) delete [] *it;
m_combine_trids.clear();
m_combine_trids_num = 0;
}
protected:
class add_prm : public primitive_visitor {
protected:
virtual bool project(float&,float&,float&,float&) {return true;}
virtual bool add_point(float,float,float,float) {return false;}
virtual bool add_point(float,float,float,float,
float,float,float,float) {return false;}
virtual bool add_line(float,float,float,float,
float,float,float,float) {return false;}
virtual bool add_line(float,float,float,float,float,float,float,float,
float,float,float,float,float,float,float,float) {
return false;
}
virtual bool add_triangle(float a_p1x,float a_p1y,float a_p1z,float,
float a_p2x,float a_p2y,float a_p2z,float,
float a_p3x,float a_p3y,float a_p3z,float){
float vx = a_p2x-a_p1x;
float vy = a_p2y-a_p1y;
float vz = a_p2z-a_p1z;
float wx = a_p3x-a_p2x;
float wy = a_p3y-a_p2y;
float wz = a_p3z-a_p2z;
// vx wx
// vy ^ wy
// vz wz
float cx = vy*wz-vz*wy;
float cy = vz*wx-vx*wz;
float cz = vx*wy-vy*wx;
float len = (float)::sqrt(cx*cx + cy*cy + cz*cz);
if(!len) {
//m_out << "tools::sg::tessellate::add_prm : null normal."
// << std::endl;
} else {
cx /= len;
cy /= len;
cz /= len;
}
if(m_mode==gl::triangles()) {
m_norms.push_back(cx);
m_norms.push_back(cy);
m_norms.push_back(cz);
m_norms.push_back(cx);
m_norms.push_back(cy);
m_norms.push_back(cz);
m_norms.push_back(cx);
m_norms.push_back(cy);
m_norms.push_back(cz);
} else if( (m_mode==gl::triangle_strip()) ||
(m_mode==gl::triangle_fan()) ){
if(m_norms.empty()) { //startup : three vertices.
m_norms.push_back(cx);
m_norms.push_back(cy);
m_norms.push_back(cz);
m_norms.push_back(cx);
m_norms.push_back(cy);
m_norms.push_back(cz);
m_norms.push_back(cx);
m_norms.push_back(cy);
m_norms.push_back(cz);
} else { //one vertex :
m_norms.push_back(cx);
m_norms.push_back(cy);
m_norms.push_back(cz);
}
}
return true;
}
virtual bool add_triangle(float a_p1x,float a_p1y,float a_p1z,float a_p1w,
float,float,float,float,
float a_p2x,float a_p2y,float a_p2z,float a_p2w,
float,float,float,float,
float a_p3x,float a_p3y,float a_p3z,float a_p3w,
float,float,float,float){
return add_prm::add_triangle(a_p1x,a_p1y,a_p1z,a_p1w,
a_p2x,a_p2y,a_p2z,a_p2w,
a_p3x,a_p3y,a_p3z,a_p3w);
}
virtual bool project_normal(float& a_x,float& a_y,float& a_z) {
(void)a_x;(void)a_y;(void)a_z;
return true;
}
virtual bool add_point_normal(float a_x,float a_y,float a_z,float a_w,
float a_nx,float a_ny,float a_nz) {
(void)a_x;(void)a_y;(void)a_z;(void)a_w;
(void)a_nx;(void)a_ny;(void)a_nz;
return false;
}
virtual bool add_point_normal(float a_x,float a_y,float a_z,float a_w,
float a_nx,float a_ny,float a_nz,
float a_r,float a_g,float a_b,float a_a) {
(void)a_x;(void)a_y;(void)a_z;(void)a_w;
(void)a_nx;(void)a_ny;(void)a_nz;
(void)a_r;(void)a_g;(void)a_b;(void)a_a;
return false;
}
virtual bool add_line_normal(float a_bx,float a_by,float a_bz,float a_bw,
float a_bnx,float a_bny,float a_bnz,
float a_ex,float a_ey,float a_ez,float a_ew,
float a_enx,float a_eny,float a_enz) {
(void)a_bx;(void)a_by;(void)a_bz;(void)a_bw;
(void)a_bnx;(void)a_bny;(void)a_bnz;
(void)a_ex;(void)a_ey;(void)a_ez;(void)a_ew;
(void)a_enx;(void)a_eny;(void)a_enz;
return false;
}
virtual bool add_line_normal(float a_bx,float a_by,float a_bz,float a_bw,
float a_bnx,float a_bny,float a_bnz,
float a_br,float a_bg,float a_bb,float a_ba,
float a_ex,float a_ey,float a_ez,float a_ew,
float a_enx,float a_eny,float a_enz,
float a_er,float a_eg,float a_eb,float a_ea){
(void)a_bx;(void)a_by;(void)a_bz;(void)a_bw;
(void)a_bnx;(void)a_bny;(void)a_bnz;
(void)a_br;(void)a_bg;(void)a_bb;(void)a_ba;
(void)a_ex;(void)a_ey;(void)a_ez;(void)a_ew;
(void)a_enx;(void)a_eny;(void)a_enz;
(void)a_er;(void)a_eg;(void)a_eb;(void)a_ea;
return false;
}
virtual bool add_triangle_normal(
float a_p1x,float a_p1y,float a_p1z,float a_p1w,
float a_n1x,float a_n1y,float a_n1z,
float a_p2x,float a_p2y,float a_p2z,float a_p2w,
float a_n2x,float a_n2y,float a_n2z,
float a_p3x,float a_p3y,float a_p3z,float a_p3w,
float a_n3x,float a_n3y,float a_n3z) {
add_triangle(a_p1x,a_p1y,a_p1z,a_p1w,
a_p2x,a_p2y,a_p2z,a_p2w,
a_p3x,a_p3y,a_p3z,a_p3w);
//m_this.m_triangles.add_normal(a_n1x,a_n1y,a_n1z);
//m_this.m_triangles.add_normal(a_n2x,a_n2y,a_n2z);
//m_this.m_triangles.add_normal(a_n3x,a_n3y,a_n3z);
(void)a_n1x;(void)a_n1y;(void)a_n1z;
(void)a_n2x;(void)a_n2y;(void)a_n2z;
(void)a_n3x;(void)a_n3y;(void)a_n3z;
return true;
}
virtual bool add_triangle_normal(
float a_p1x,float a_p1y,float a_p1z,float a_p1w,
float a_n1x,float a_n1y,float a_n1z,
float a_r1,float a_g1,float a_b1,float a_a1,
float a_p2x,float a_p2y,float a_p2z,float a_p2w,
float a_n2x,float a_n2y,float a_n2z,
float a_r2,float a_g2,float a_b2,float a_a2,
float a_p3x,float a_p3y,float a_p3z,float a_p3w,
float a_n3x,float a_n3y,float a_n3z,
float a_r3,float a_g3,float a_b3,float a_a3){
add_triangle(a_p1x,a_p1y,a_p1z,a_p1w,
a_r1,a_g1,a_b1,a_a1,
a_p2x,a_p2y,a_p2z,a_p2w,
a_r2,a_g2,a_b2,a_a2,
a_p3x,a_p3y,a_p3z,a_p3w,
a_r3,a_g3,a_b3,a_a3);
//m_this.m_triangles.add_normal(a_n1x,a_n1y,a_n1z);
//m_this.m_triangles.add_normal(a_n2x,a_n2y,a_n2z);
//m_this.m_triangles.add_normal(a_n3x,a_n3y,a_n3z);
(void)a_n1x;(void)a_n1y;(void)a_n1z;
(void)a_n2x;(void)a_n2y;(void)a_n2z;
(void)a_n3x;(void)a_n3y;(void)a_n3z;
return true;
}
public:
add_prm(std::ostream& a_out,std::vector<float>& a_norms)
:m_out(a_out)
,m_norms(a_norms)
{}
virtual ~add_prm(){}
public:
add_prm(const add_prm& a_from):primitive_visitor(a_from),m_out(a_from.m_out),m_norms(a_from.m_norms) {}
add_prm& operator=(const add_prm& a_from){
primitive_visitor::operator=(a_from);
return *this;
}
protected:
std::ostream& m_out;
public:
std::vector<float>& m_norms;
};
protected:
std::ostream& m_out;
GLUtesselator* m_tobj;
std::vector<float>* m_coords;
std::vector<double*> m_combine_trids;
size_t m_combine_trids_num;
prims_t* m_prims;
};
/*
class tessellate_factory {
#ifdef TOOLS_MEM
TOOLS_SCLASS(tools::sg::tessellate_factory);
#endif
public:
tessellate_factory(){
#ifdef TOOLS_MEM
mem::increment(s_class().c_str());
#endif
}
virtual ~tessellate_factory(){
#ifdef TOOLS_MEM
mem::decrement(s_class().c_str());
#endif
}
public:
tessellate_factory(const tessellate_factory& a_from) {
#ifdef TOOLS_MEM
mem::increment(s_class().c_str());
#endif
}
tessellate_factory& operator=(const tessellate_factory&){
return *this;
}
public:
virtual tessellate* create(std::ostream& a_out) {
return new tessellate(a_out);
}
};
*/
}}
#endif
+32 -12
View File
@@ -875,7 +875,7 @@ protected:
::gluTessCallback(m_tobj,(GLUenum)GLU_TESS_COMBINE_DATA,(Func)combine_cbk);
::gluTessCallback(m_tobj,(GLUenum)GLU_TESS_ERROR_DATA, (Func)error_cbk);
#else
// NOTE : the gluTessCallback_<enum>() functions are inlib/glutess specific.
// NOTE : the gluTessCallback_<enum>() functions are tools/glutess specific.
// They had been introduced to avoid g++-8.1.0 warnings :
// warnings : cast between incompatible function types.
::gluTessCallback_GLU_TESS_BEGIN_DATA (m_tobj,begin_cbk);
@@ -1775,26 +1775,45 @@ protected:
::FT_Done_Face(m_face);
m_face = 0;
}
if(font.value().empty()) {
a_out << "tools::sg::text_freetype::load_face :"
<< " no font file given."
<< " no font given."
<< std::endl;
return;
}
std::string file;
//if(tools::file::exists(font.value())) { //look in current directory.
// file = font.value(); //ok
//} else if(!inlib::find_with_dirs(a_out,font_dirs.values(),font.value(),file,false)) {
if(!tools::find_with_env(a_out,s_TOOLS_FONT_PATH(),font.value(),file,false)) {
// look for embedded fonts:
{unsigned int size;
const unsigned char* buffer;
if(parent::find_embedded_font(font.value(),size,buffer)) {
FT_Error error =
::FT_New_Memory_Face(m_library,(const FT_Byte*)buffer,(FT_Long)size,0,&m_face);
if(error) {
a_out << "tools::sg::text_freetype::load_face :"
<< " font file not found for font "
<< tools::sout(font.value()) << "."
<< " FT_New_Memory_Face : error : " << serror(error) << "."
<< std::endl;
m_face = 0;
return;
}
//}
if(m_verbose) a_out << "tools::sg::text_freetype::load_face : load embedded font ok." << std::endl;
return;
}}
std::string file;
if(parent::find_font_with_finders(font.value(),file)) {
} else {
tools::find_with_env(a_out,s_TOOLS_FONT_PATH(),font.value(),file,false);
}
if(file.empty()) {
a_out << "tools::sg::text_freetype::load_face :"
<< " font file not found for font "
<< tools::sout(font.value()) << "."
<< std::endl;
return;
}
if(m_verbose) {
a_out << "tools::sg::text_freetype::load_face :"
@@ -2128,7 +2147,7 @@ protected:
FT_Library m_library;
FT_Face m_face;
unsigned short m_encoding_offset;
bool m_verbose; //append _ to avoid clash with inlib/sg/guib::m_verbose
bool m_verbose; //append _ to avoid clash with tools/sg/guib::m_verbose
////////////////////////////////////////////////////////
/// outline ////////////////////////////////////////////
////////////////////////////////////////////////////////
@@ -2174,4 +2193,5 @@ protected:
}}
#endif
@@ -35,7 +35,14 @@ public:
float zz = 0;
a_action.load_matrices_to_identity();
{tools::mat4f _mtx;
_mtx.set_translate(x,y,zz);
if(!m_bitmaps.size()) {
if(state.m_ww) _mtx.mul_scale(float(state.m_wh)/float(state.m_ww),1,1);
}
a_action.load_model_matrix(_mtx);}
///////////////////////////////////////////////////////////
/// lines /////////////////////////////////////////////////
///////////////////////////////////////////////////////////
@@ -45,11 +52,7 @@ public:
size_t num = item.second;
if(!num) continue;
const float* data = tools::vec_data<float>(m_xys)+pos;
float* vp = _trans3(num,data,x,y,zz); //have an extra z for Windows GL.
if(vp) {
a_action.draw_vertex_array(tools::gl::line_strip(),num*3,vp);
delete [] vp;
}
a_action.draw_vertex_array_xy(tools::gl::line_strip(),num*2,data);
}}
///////////////////////////////////////////////////////////
@@ -65,21 +68,13 @@ public:
// << std::endl;
const float* data = tools::vec_data<float>(m_xys)+pos;
float* vp = _trans3(num,data,x,y,zz); //have an extra z for Windows GL.
if(vp) {
a_action.draw_vertex_array((*it).first,num*3,vp);
delete [] vp;
}
a_action.draw_vertex_array_xy((*it).first,num*2,data);
}}
///////////////////////////////////////////////////////////
/// bitmap ////////////////////////////////////////////////
///////////////////////////////////////////////////////////
if(m_bitmaps.size()) {
tools::mat4f _m;
_m.set_translate(x,y,zz);
a_action.load_model_matrix(_m);
#if defined(ANDROID) /*|| TARGET_OS_IPHONE*/
// we do not have transparent texture here (see also gl/tex_img() that does img/4-bytes => img/3-bytes) :
{tools::sg::state& _state = a_action.state();
@@ -106,6 +101,8 @@ public:
}
virtual void pick(tools::sg::pick_action& a_action) {
const tools::sg::state& state = a_action.state();
{bool _char_height_touched = char_height_touched(a_action.state());
if(touched()||_char_height_touched) {
update_sg(a_action.out(),font.touched(),a_action.state());
@@ -118,10 +115,14 @@ public:
a_action.set_matrices_to_identity();
a_action.model_matrix().set_translate(x,y,zz);
if(!m_bitmaps.size()) {
if(state.m_ww) a_action.model_matrix().mul_scale(float(state.m_wh)/float(state.m_ww),1,1);
}
///////////////////////////////////////////////////////////
/// lines /////////////////////////////////////////////////
///////////////////////////////////////////////////////////
{tools_vforcit(line_t,m_lines,it) {
const line_t& item = *it;
size_t pos = item.first;
@@ -166,10 +167,9 @@ public:
/// bitmap ////////////////////////////////////////////////
///////////////////////////////////////////////////////////
if(m_bitmaps.size()) {
a_action.model_matrix().set_translate(x,y,zz);
m_bitmaps.pick(a_action);
}
///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////
@@ -245,18 +245,6 @@ protected:
height.value_no_cmp(old_height);
}
float* _trans3(size_t a_num,const float* a_data,float a_x,float a_y,float a_z) {
float* vp = new float[a_num*3];
if(!vp) return 0;
float* pos = vp;
float* pda = (float*)a_data;
for(size_t index=0;index<a_num;index++){
*pos = *pda + a_x;pos++;pda++;
*pos = *pda + a_y;pos++;pda++;
*pos = a_z;pos++;
}
return vp;
}
float* _trans2(size_t a_num,const float* a_data,float a_x,float a_y) {
float* vp = new float[a_num*2];
if(!vp) return 0;
+10 -12
View File
@@ -33,12 +33,12 @@ public:
get_segments(segs); //must be after changing the height.
a_action.load_matrices_to_identity();
{std::vector<float>::iterator it;
for(it=segs.begin();it!=segs.end();) {
*it += x;it++; //Android don't like *it++.
*it += y;it++;
}}
{tools::mat4f _mtx;
_mtx.set_translate(x,y,0);
if(state.m_ww) _mtx.mul_scale(float(state.m_wh)/float(state.m_ww),1,1);
a_action.load_proj_matrix(_mtx);}
a_action.draw_vertex_array_xy(gl::lines(),segs);
a_action.load_matrices_from_state();
@@ -65,12 +65,10 @@ public:
get_segments(segs);
a_action.set_matrices_to_identity();
{std::vector<float>::iterator it;
for(it=segs.begin();it!=segs.end();) {
*it += x;it++;
*it += y;it++;
}}
{tools::mat4f& _mtx = a_action.model_matrix();
_mtx.set_translate(x,y,0);
if(state.m_ww) _mtx.mul_scale(float(state.m_wh)/float(state.m_ww),1,1);}
a_action.add__lines_xy(*this,segs);
+128
View File
@@ -0,0 +1,128 @@
// Copyright (C) 2018, Guy Barrand. All rights reserved.
// See the file tools.license for terms.
#ifndef tools_sg_write_paper
#define tools_sg_write_paper
// To traverse a scene graph and "export" it at various file formats
// by using various rendering actions.
// For example by using gl2ps_action, handle the formats:
// gl2ps_eps: gl2ps producing eps
// gl2ps_ps: gl2ps producing ps
// gl2ps_pdf: gl2ps producing pdf
// gl2ps_svg: gl2ps producing svg
// gl2ps_tex: gl2ps producing tex
// gl2ps_pgf: gl2ps producing pgf
// By using the zb_action (zb for zbuffer):
// zb_ps: tools::sg offscreen zbuffer put in a PostScript file.
// zb_png: zbuffer put in a png file. It needs to provide a "png_writer" function.
// zb_jpeg: zbuffer put in a jpeg file. It needs to provide a "jpeg_writer" function.
#include "zb_action"
#include "node"
#include "gl2ps_action"
#include "../wps"
#include "../typedefs"
#include "../touplow"
namespace tools {
namespace sg {
typedef bool (*png_writer)(std::ostream&,const std::string&,
unsigned char*,unsigned int,unsigned int,unsigned int);
typedef bool (*jpeg_writer)(std::ostream&,const std::string&,
unsigned char*,unsigned int,unsigned int,unsigned int,int);
inline bool write_paper(std::ostream& a_out,
gl2ps_manager& a_gl2ps_mgr,zb_manager& a_zb_mgr,
png_writer a_png_writer,jpeg_writer a_jpeg_writer,
float a_back_r,float a_back_g,float a_back_b,float a_back_a,
node& a_scene_graph,
unsigned int a_width,unsigned int a_height,
const std::string& a_file,const std::string& a__format) {
if(!a_width || !a_height) return false;
std::string a_format = a__format;
tolowercase(a_format); //handle legacy.
int gl2ps_format;
if(s2format(a_format,gl2ps_format)) {
gl2ps_action action(a_gl2ps_mgr,a_out,a_width,a_height);
action.clear_color(a_back_r,a_back_g,a_back_b,a_back_a);
if(!action.open(a_file,gl2ps_format)) return false;
a_scene_graph.render(action);
action.close();
return true;
}
zb_action action(a_zb_mgr,a_out,a_width,a_height);
action.zbuffer().clear_color_buffer(0);
action.add_color(a_back_r,a_back_g,a_back_b,a_back_a);
action.zbuffer().clear_depth_buffer();
a_scene_graph.render(action);
if((a_format=="zb_ps")||(a_format=="inzb_ps")) {
wps wps(a_out);
if(!wps.open_file(a_file)) {
a_out << "tools::sg::write_paper : can't open " << a_file << "." << std::endl;
return false;
}
wps.PS_BEGIN_PAGE();
wps.PS_PAGE_SCALE(float(a_width),float(a_height));
wps.PS_IMAGE(a_width,a_height,wps::rgb_4,zb_action::get_rgb,&action);
wps.PS_END_PAGE();
wps.close_file();
return true;
}
if((a_format=="zb_png")||(a_format=="inzb_png")) {
if(!a_png_writer) {
a_out << "tools::sg::write_paper : no png_writer given." << std::endl;
return false;
}
size_t sz;
unsigned char* buffer = action.get_rgbas(sz);
if(!buffer) {
a_out << "tools::sg::write_paper : can't get rgba image." << std::endl;
return false;
}
if(!a_png_writer(a_out,a_file,buffer,a_width,a_height,4)) {
a_out << "tools::sg::write_paper : tools::png::write() failed." << std::endl;
delete [] buffer;
return false;
}
delete [] buffer;
return true;
}
if((a_format=="zb_jpeg")||(a_format=="zb_jpg")||(a_format=="inzb_jpeg")) {
if(!a_jpeg_writer) {
a_out << "tools::sg::write_paper : no jpeg_writer given." << std::endl;
return false;
}
size_t sz;
unsigned char* buffer = action.get_rgbs(sz);
if(!buffer) {
a_out << "tools::sg::write_paper : can't get rgb image." << std::endl;
return false;
}
if(!a_jpeg_writer(a_out,a_file,buffer,a_width,a_height,3,100)) {
a_out << "tools::sg::write_paper : tools::jpeg::write() failed." << std::endl;
delete [] buffer;
return false;
}
delete [] buffer;
return true;
}
a_out << "tools::sg::write_paper : unknown format " << a_format << std::endl;
return false;
}
}}
#endif
-28
View File
@@ -1,28 +0,0 @@
// Copyright (C) 2010, Guy Barrand. All rights reserved.
// See the file tools.license for terms.
#ifndef tools_std_system
#define tools_std_system
#include <cstdlib>
#include <ostream>
#if defined(__APPLE__)
#include <TargetConditionals.h>
#endif
namespace tools {
inline int std_system(std::ostream& a_out,const std::string& a_string) {
#if TARGET_OS_IPHONE
a_out << "tools::std_system : system() not available on iOS. Can't execute " << sout(a_string) << "." << std::endl;
return EXIT_FAILURE;
#else
return ::system(a_string.c_str());
(void)a_out;
#endif
}
}
#endif
-64
View File
@@ -1,64 +0,0 @@
// Copyright (C) 2010, Guy Barrand. All rights reserved.
// See the file tools.license for terms.
#ifndef tools_svalues
#define tools_svalues
// See also snums.
#include "sto"
#include <vector>
namespace tools {
template <class T>
inline bool values(const std::string& a_string,const std::string& a_sep,bool a_take_empty,std::vector<T>& a_values){
// same logic as words() function.
a_values.clear();
if(a_string.empty()) return true;
std::string::size_type lim = (a_take_empty?0:1);
if(a_sep.empty()) {
T value;
if(!to<T>(a_string,value)) {
a_values.clear();
return false;
}
a_values.push_back(value);
} else {
std::string::size_type l = a_string.length();
std::string::size_type llimiter = a_sep.length();
std::string::size_type pos = 0;
while(true) {
std::string::size_type index = a_string.find(a_sep,pos);
if(index==std::string::npos){ // Last word.
if((l-pos)>=lim) {
T value;
if(!to<T>(a_string.substr(pos,l-pos),value)) {
a_values.clear();
return false;
}
a_values.push_back(value);
}
break;
} else {
// abcxxxef
// 0 3 67
if((index-pos)>=lim) {
T value;
if(!to<T>(a_string.substr(pos,index-pos),value)) {
a_values.clear();
return false;
}
a_values.push_back(value);
}
pos = index + llimiter;
}
}
}
return true;
}
}
#endif
-140
View File
@@ -1,140 +0,0 @@
// Copyright (C) 2010, Guy Barrand. All rights reserved.
// See the file tools.license for terms.
#ifndef tools_sys_dir
#define tools_sys_dir
// on Windows, avoid windows.h.
// See files to get directory entries (that needs windows.h on Windows).
#include <string>
#ifdef _MSC_VER
#include <direct.h>
//extern "C" {char* _getdcwd(int,char*,int);}
#else
#include <unistd.h>
#include <cstdlib> //getenv.
#endif
#include <sys/stat.h>
namespace tools {
namespace dir {
inline bool pwd(std::string& a_pwd) {
// Return current directory.
unsigned int mx_path_len = 2048;
char* cwd = new char[mx_path_len];
#ifdef _MSC_VER
// driveletter = 0 means return the working directory for the default drive.
if(::_getdcwd(0,cwd,mx_path_len)==NULL) {
delete [] cwd;
a_pwd.clear();
return false;
}
#else
if(::getcwd(cwd,mx_path_len)==NULL) {
delete [] cwd;
a_pwd.clear();
return false;
}
#endif
a_pwd = cwd;
delete [] cwd;
return true;
}
inline bool cd(const std::string& a_path){
if(::chdir(a_path.c_str())!=0) return false;
return true;
}
inline bool create(const std::string& a_name){
// a_name should be a single directory name, and not a file system path.
// Then it must not contain : ., .., /, \ etc...
#ifdef _MSC_VER
return (::mkdir(a_name.c_str())==0 ? true : false);
#else
return (::mkdir(a_name.c_str(), 0755)==0 ? true : false);
#endif
}
inline bool home(std::string& a_s) {
#ifdef _WIN32
const char* env = ::getenv("USERPROFILE");
#else
const char* env = ::getenv("HOME");
#endif
if(!env) {a_s.clear();return false;}
a_s = env;
return true;
}
inline bool cd_home() {
std::string s;
home(s);
if(s.empty()) return false;
return cd(s);
}
//NOTE : SWIG : exists is also a method in file
// (can be fix with a %rename(directory_exists))
inline bool in_fs(const std::string& a_path){
struct stat finfo;
if (::stat(a_path.c_str(),&finfo) < 0) return false;
return true;
}
//NOTE : SWIG : "is" is a Python keyword.
inline bool is_a(const std::string& a_path,bool& a_value) {
a_value = false;
struct stat finfo;
if (::stat(a_path.c_str(),&finfo) < 0) return false;
a_value = ( ((finfo.st_mode & S_IFMT) == S_IFDIR) ? true : false);
return true;
}
inline bool is_a(const std::string& a_path) {
bool _is;
if(!is_a(a_path,_is)) return false;
return _is;
}
inline bool is_dot(const std::string& a_path) {
#ifdef _WIN32
char sep = '\\';
#else
char sep = '/';
#endif
size_t l = a_path.size();
if((l==1) && (a_path[0]=='.') ) return true;
if((l==2) && (a_path[0]=='.') && (a_path[l]=='.') ) return true;
if((l>=2) && (a_path[l-1]=='.') && (a_path[l-2]==sep) ) return true;
if((l>=3) && (a_path[l-1]=='.') && (a_path[l-2]=='.') && (a_path[l-3]==sep) )
return true;
return false;
}
inline bool mkdir(const std::string& a_name) {
// a_name should be a single directory name, and not a file system path.
// Then it must not contain : ., .., /, \ etc...
bool is;
if(!is_a(a_name,is)) { //a_name does not exist as a file or dir.
if(!create(a_name)) return false;
} else {
if(!is) return false; //a_name exists but is not a directory.
}
return true;
}
inline bool mkcd(const std::string& a_name) {
// a_name should be a single directory name, and not a file system path.
// Then it must not contain : ., .., /, \ etc...
if(!mkdir(a_name)) return false;
return cd(a_name);
}
}}
#endif
-21
View File
@@ -1,21 +0,0 @@
// Copyright (C) 2010, Guy Barrand. All rights reserved.
// See the file tools.license for terms.
#ifndef tools_sys_process
#define tools_sys_process
#ifdef _MSC_VER
#include <process.h>
#else
#include <unistd.h>
#endif
namespace tools {
inline int process_id() {
return static_cast<int>(::getpid());
}
}
#endif
-209
View File
@@ -1,209 +0,0 @@
// Copyright (C) 2010, Guy Barrand. All rights reserved.
// See the file tools.license for terms.
#ifndef tools_system
#define tools_system
#include <cstdlib>
#include "cstr"
#include "sout"
#include "num2s"
#include "sto"
#include "words"
#include "sep"
#include "vmanip"
#include "srep"
#if defined(__APPLE__)
#include <TargetConditionals.h>
#endif
namespace tools {
inline bool is_env(const std::string& a_string){
const char* env = ::getenv(a_string.c_str());
return (env?true:false);
}
inline bool isenv(const std::string& a_string){return is_env(a_string);} //deprecated.
inline bool get_env(const std::string& a_string,std::string& a_value){
const char* env = ::getenv(a_string.c_str());
if(env) {
a_value = std::string(env?env:"");
return true;
} else {
a_value.clear();
return false;
}
}
inline bool getenv(const std::string& a_string,std::string& a_value){return get_env(a_string,a_value);} //deprecated.
template <class T>
inline bool get_env(const std::string& a_string,T& a_v,const T& a_def = T()){
std::string s;
if(!getenv(a_string,s)) {a_v = a_def;return false;}
return to<T>(s,a_v,a_def);
}
inline bool get_env_bool(const std::string& a_string,bool& a_v){
std::string s;
if(!getenv(a_string,s)) return false;
return to(s,a_v);
}
inline bool put_env(const std::string& a_env,const std::string& a_value){
std::string value = a_env+"="+a_value;
#ifdef TOOLS_MEM
if(::putenv(str_dup(value.c_str(),false))) return false;
#else
if(::putenv(str_dup(value.c_str()))) return false;
#endif
//check:
std::string s;
if(!getenv(a_env,s)) return false;
if(s!=a_value) return false;
return true;
}
inline bool putenv(const std::string& a_env,const std::string& a_value){return put_env(a_env,a_value);} //deprecated.
inline bool rm_env(const std::string& a_env){
#ifdef _MSC_VER
std::string value = a_env+"=";
#ifdef TOOLS_MEM
if(::putenv(str_dup(value.c_str(),false))) return false;
#else
if(::putenv(str_dup(value.c_str()))) return false;
#endif
#else
::unsetenv(a_env.c_str());
#endif
return true;
}
inline bool rmenv(const std::string& a_env) {return rm_env(a_env);} //deprecated. Still used in OnX.
inline bool check_getenv(std::ostream& a_out,
const std::string& a_new,const std::string& a_old,
std::string& a_env){
if(get_env(a_new,a_env)) return true;
if(get_env(a_old,a_env)) {
a_out << "Environment variable " << sout(a_old) << " is deprecated. Use " << sout(a_new) << " instead." << std::endl;
return true;
}
return false;
}
inline int std_system(std::ostream& a_out,const std::string& a_string) {
#if TARGET_OS_IPHONE
a_out << "tools::std_system : system() not available on iOS. Can't execute " << sout(a_string) << "." << std::endl;
return EXIT_FAILURE;
#else
return ::system(a_string.c_str());
(void)a_out;
#endif
}
inline bool env_append(const std::string& a_env,const std::string& a_sep,const std::vector<std::string>& a_vals){
std::string env_value;
if(is_env(a_env)) {
if(!get_env(a_env,env_value)) return false;
}
{std::vector<std::string>::const_iterator it;
for(it=a_vals.begin();it!=a_vals.end();++it) {
const std::string& value = *it;
if(value.empty()) continue;
if(env_value.size()) {
std::vector<std::string> ws;
words(env_value,a_sep,false,ws);
// Remove existing one, so that value be put at end.
remove(ws,value);
if(!nums2s<std::string>(ws,env_value,a_sep)) {}
}
if(env_value.size()) env_value += a_sep;
env_value += value;
}}
if(!putenv(a_env,env_value)) return false;
return true;
}
inline bool env_path_append(const std::string& a_env,const std::vector<std::string>& a_paths){
return env_append(a_env,psep(),a_paths);
}
inline bool env_append_path(const std::string& a_env,const std::string& a_path){
std::vector<std::string> v;
v.push_back(a_path);
return env_append(a_env,psep(),v);
}
// OpenPAW, Panoramix :
inline bool rep_env(std::string& a_string) {
char spec_char = '\n';
std::string::size_type dollar;
while((dollar=a_string.find('$'))!=std::string::npos){
std::string::size_type slash = a_string.find('/',dollar+1);
std::string::size_type back_slash = a_string.find('\\',dollar+1);
std::string::size_type pos = std::string::npos;
if(slash!=std::string::npos) {
if(back_slash!=std::string::npos) {
pos = slash<back_slash?slash:back_slash;
} else {
pos = slash;
}
} else {
if(back_slash!=std::string::npos) {
pos = back_slash;
} else {
pos = std::string::npos;
}
}
std::string env;
if(pos==std::string::npos) {
env = a_string.substr(dollar+1,a_string.length()-(dollar+1));
} else {
// abc$xxx/ef
// 0 3 7 9
env = a_string.substr(dollar+1,pos-(dollar+1));
}
char* val = ::getenv(env.c_str());
if(!val) {
// We may have $ in a_string not attached to an env variable.
// For example at LAL, some Windows account name have a leading $
// that is found back in the home directory path. To bypass this
// problem we change temporarily the $ by spec_char and continue
// the loop. We change back all the spec_chars to $ at end.
a_string[dollar] = spec_char;
} else {
std::string value = a_string.substr(0,dollar);
value += val;
if(pos!=std::string::npos) value += a_string.substr(pos,a_string.length()-pos);
a_string = value;
}
}
replace(a_string,spec_char,'$');
return true;
}
inline bool repenv(std::string& a_string) {return rep_env(a_string);} //deprecated.
inline bool file_name(const std::string& a_path,std::string& a_name) {
//used in osc packages and a tools::xml::parser::load_file() compatible for OnX.
a_name = a_path;
if(!rep_env(a_name)) {a_name.clear();return false;}
#ifdef _WIN32
replace(a_name,"/","\\");
replace(a_name,"\"","");
#endif
return true;
}
}
#endif
-216
View File
@@ -1,216 +0,0 @@
// Copyright (C) 2010, Guy Barrand. All rights reserved.
// See the file tools.license for terms.
#ifndef tools_test
#define tools_test
#include <ostream>
#include <string>
namespace tools {
inline bool equal(std::ostream& a_out,const char* a_file,int a_line,const std::string& a_v,const std::string& a_expected) {
if(a_v!=a_expected) {
a_out << "failed in file :" << std::endl
<< a_file << std::endl
<< "at line :" << std::endl
<< a_line << std::endl
<< "strg value \"" << a_v << "\"" << std::endl
<< ", expected \"" << a_expected << "\"." << std::endl;
return false;
}
return true;
}
inline bool equal(std::ostream& a_out,const char* a_file,int a_line,bool a_v,bool a_expected) {
if(a_v!=a_expected) {
a_out << "failed in file :" << std::endl
<< a_file << std::endl
<< "at line :" << std::endl
<< a_line << std::endl
<< "value " << (a_v?"true":"false") << ", expected " << (a_expected?"true":"false") << std::endl;
return false;
}
return true;
}
#define TOOLS_TEST_FUNC(a__func) \
if(!tools::equal(a_out,__FILE__,__LINE__,(a__func),true)) return false;
template <class CLASS>
inline bool valid_pointer(std::ostream& a_out,const char* a_file,int a_line,CLASS* a_p) {
if(!a_p) {
a_out << "failed in file :" << std::endl
<< a_file << std::endl
<< "at line :" << std::endl
<< a_line << std::endl
<< "null pointer." << std::endl;
return false;
}
return true;
}
template <class INTEGER>
inline bool equal(std::ostream& a_out,const char* a_file,int a_line,const INTEGER& a_v,const INTEGER& a_expected) {
if(a_v!=a_expected) {
a_out << "failed in file :" << std::endl
<< a_file << std::endl
<< "at line :" << std::endl
<< a_line << std::endl
<< "value " << a_v << ", expected " << a_expected << std::endl;
return false;
}
return true;
}
template <class INTEGER>
inline bool not_equal(std::ostream& a_out,const char* a_file,int a_line,const INTEGER& a_v,const INTEGER& a_expected) {
if(a_v==a_expected) {
a_out << "failed in file :" << std::endl
<< a_file << std::endl
<< "at line :" << std::endl
<< a_line << std::endl
<< "value " << a_v << ", expected " << a_expected << std::endl;
return false;
}
return true;
}
template <class INTEGER>
inline bool ge(std::ostream& a_out,const char* a_file,int a_line,const INTEGER& a_v,const INTEGER& a_expected) {
if(a_v<a_expected) {
a_out << "failed in file :" << std::endl
<< a_file << std::endl
<< "at line :" << std::endl
<< a_line << std::endl
<< "value " << a_v << " < " << a_expected << std::endl;
return false;
}
return true;
}
template <class REAL>
inline bool equal(std::ostream& a_out,const char* a_file,int a_line,const REAL& a_v,const REAL& a_expected,const REAL& a_tolerance,REAL(*a_fabs)(const REAL&)) {
REAL diff = a_fabs(a_v-a_expected);
if(diff>=a_tolerance) {
a_out << "failed in file :" << std::endl
<< a_file << std::endl
<< "at line :" << std::endl
<< a_line << std::endl
<< "value " << a_v << ", expected " << a_expected << ",diff " << diff << std::endl;
return false;
}
return true;
}
template <class REAL>
inline bool not_equal(std::ostream& a_out,const char* a_file,int a_line,const REAL& a_v,const REAL& a_expected,const REAL& a_tolerance,REAL(*a_fabs)(const REAL&)) {
REAL diff = a_fabs(a_v-a_expected);
if(diff<a_tolerance) {
a_out << "failed in file :" << std::endl
<< a_file << std::endl
<< "at line :" << std::endl
<< a_line << std::endl
<< "value " << a_v << ", not expected to be " << a_expected << ",diff " << diff << std::endl;
return false;
}
return true;
}
// with complex number
template <class NUMBER,class PREC>
inline bool _equal(std::ostream& a_out,const char* a_file,int a_line,const NUMBER& a_v,const NUMBER& a_expected,const PREC& a_tolerance,PREC(*a_fabs)(const NUMBER&)) {
PREC diff = a_fabs(a_v-a_expected);
if(diff>=a_tolerance) {
a_out << "failed in file :" << std::endl
<< a_file << std::endl
<< "at line :" << std::endl
<< a_line << std::endl
<< "value " << a_v << ", expected " << a_expected << ",diff " << diff << std::endl;
return false;
}
return true;
}
template <class REAL>
inline bool equal(std::ostream& a_out,const char* a_file,int a_line,size_t a_size,const REAL* a_v,const REAL* a_expected,const REAL& a_tolerance,REAL(*a_fabs)(const REAL&)){
for(size_t index=0;index<a_size;index++) {
if(!equal<REAL>(a_out,a_file,a_line,a_v[index],a_expected[index],a_tolerance,a_fabs)) return false;
}
return true;
}
template <class VEC,class REAL>
inline bool equal(std::ostream& a_out,const char* a_file,int a_line,const VEC& a_1,const VEC& a_2,const REAL& a_tolerance,REAL(*a_fabs)(const REAL&)){
if(a_1.dimension()!=a_2.dimension()) {
a_out << "failed in file :" << std::endl
<< a_file << std::endl
<< "at line :" << std::endl
<< a_line << std::endl
<< "vector dimension " << a_1.dimension() << " != " << a_2.dimension() << std::endl;
return false;
}
for(size_t index=0;index<a_1.dimension();index++) {
if(!equal<REAL>(a_out,a_file,a_line,a_1[index],a_2[index],a_tolerance,a_fabs)) return false;
}
return true;
}
template <class MAT,class REAL>
inline bool mat_equal(std::ostream& a_out,const char* a_file,int a_line,const MAT& a_1,const MAT& a_2,const REAL& a_tolerance,REAL(*a_fabs)(const REAL&)){
if(a_1.dimension()!=a_2.dimension()) {
a_out << "failed in file :" << std::endl
<< a_file << std::endl
<< "at line :" << std::endl
<< a_line << std::endl
<< "matrix dimension " << a_1.dimension() << " != " << a_2.dimension() << std::endl;
return false;
}
if(a_1.data_size()!=a_2.data_size()) {
a_out << "failed in file :" << std::endl
<< a_file << std::endl
<< "at line :" << std::endl
<< a_line << std::endl
<< "matrix data_size " << a_1.data_size() << " != " << a_2.data_size() << std::endl;
return false;
}
for(size_t index=0;index<a_1.data_size();index++) {
if(!equal<REAL>(a_out,a_file,a_line,a_1.data()[index],a_2.data()[index],a_tolerance,a_fabs)) return false;
}
return true;
}
}
#include <vector>
namespace tools {
inline bool equal(std::ostream& a_out,const char* a_file,int a_line,const std::vector<std::string>& a_v,const std::vector<std::string>& a_expected) {
if(a_v.size()!=a_expected.size()) {
a_out << "failed in file :" << std::endl
<< a_file << std::endl
<< "at line :" << std::endl
<< a_line << std::endl
<< "vector value.size() " << a_v.size() << ", expected " << a_expected.size() << std::endl;
return false;
}
std::vector<std::string>::const_iterator it1 = a_v.begin();
std::vector<std::string>::const_iterator it2 = a_expected.begin();
for(;it1!=a_v.end();++it1,++it2) {
if((*it1)!=(*it2)) {
a_out << "failed in file :" << std::endl
<< a_file << std::endl
<< "at line :" << std::endl
<< a_line << std::endl
<< "line value \"" << (*it1) << "\"" << std::endl
<< ", expected \"" << (*it2) << "\"" << std::endl;
return false;
}
}
return true;
}
}
#endif
+53
View File
@@ -0,0 +1,53 @@
// Copyright (C) 2010, Guy Barrand. All rights reserved.
// See the file tools.license for terms.
#ifndef tools_tokenize
#define tools_tokenize
#include <string>
#include <vector>
namespace tools {
inline bool double_quotes_get_token(const std::string& a_cmd,std::string::size_type a_begIdx,
std::string::size_type& a_endIdx,std::string& a_token) {
while ( a_cmd[a_begIdx] == ' ') ++a_begIdx; // Loop checking, 23.06.2015, I. Hrivnacova
if ( a_cmd[a_begIdx] == '"' ) {
a_endIdx = a_cmd.find('"', a_begIdx+1);
if ( a_endIdx == std::string::npos ) a_endIdx = a_cmd.length();
a_token = a_cmd.substr(a_begIdx+1, (a_endIdx-1)-a_begIdx);
++a_endIdx;
}
else {
a_endIdx = a_cmd.find(' ', a_begIdx);
if ( a_endIdx == std::string::npos ) a_endIdx = a_cmd.length();
a_token = a_cmd.substr(a_begIdx, a_endIdx-a_begIdx);
}
return ( a_token.length() > 0 );
}
// From a string, double_quotes_tokenize permits to get arguments
// by taking into account strings enclosed by double quotes and potentially
// containing spaces (for example to specify a file path containing spaces).
// Example:
// if a_cmd is the string: aa bbb "ccc ddd" ee "fff gg"
// Returned a_args string list will be:
// "aa", "bb", "ccc ddd", "ee", "fff gg"
// Algorithm from Geant4/G4AnalysisUtilities.cc/Tokenize() done by Ivana Hrivnacova.
inline void double_quotes_tokenize(const std::string& a_cmd, std::vector<std::string>& a_args) {
std::string::size_type begIdx = 0;
std::string::size_type endIdx = 0;
std::string token;
do {
if ( double_quotes_get_token(a_cmd, begIdx, endIdx, token) ) {
a_args.push_back(token);
}
begIdx = endIdx + 1;
}
while ( endIdx < a_cmd.length() ); // Loop checking, 23.06.2015, I. Hrivnacova
}
}
#endif
-167
View File
@@ -1,167 +0,0 @@
// Copyright (C) 2010, Guy Barrand. All rights reserved.
// See the file tools.license for terms.
#ifndef tools_utest
#define tools_utest
#include "args"
#include <cstdio> //for FILE*
namespace tools {
class test {
public:
typedef bool(*func)(std::ostream&,bool);
typedef bool(*func2)(std::ostream&,const args&);
typedef bool(*func3)(std::ostream&,int,char**);
typedef bool(*cfunc)(FILE*,bool);
public:
test():m_do_it(false),m_func(0),m_func2(0),m_func3(0),m_cfunc(0){}
test(bool a_do_it,func a_func):m_do_it(a_do_it),m_func(a_func),m_func2(0),m_func3(0),m_cfunc(0){}
test(bool a_do_it,func2 a_func):m_do_it(a_do_it),m_func(0),m_func2(a_func),m_func3(0),m_cfunc(0){}
test(bool a_do_it,func3 a_func):m_do_it(a_do_it),m_func(0),m_func2(0),m_func3(a_func),m_cfunc(0){}
test(bool a_do_it,cfunc a_func):m_do_it(a_do_it),m_func(0),m_func2(0),m_func3(0),m_cfunc(a_func){}
virtual ~test(){}
public:
test(const test& a_from)
:m_do_it(a_from.m_do_it)
,m_func(a_from.m_func),m_func2(a_from.m_func2),m_func3(a_from.m_func3),m_cfunc(a_from.m_cfunc){}
test& operator=(const test& a_from) {
m_do_it = a_from.m_do_it;
m_func = a_from.m_func;
m_func2 = a_from.m_func2;
m_func3 = a_from.m_func3;
m_cfunc = a_from.m_cfunc;
return *this;
}
public:
bool m_do_it;
func m_func;
func2 m_func2;
func3 m_func3;
cfunc m_cfunc;
};
class utest : public std::vector< std::pair<std::string,test> > {
typedef std::pair<std::string,test> named_test;
typedef std::vector<named_test> parent;
public:
utest(std::ostream& a_out):m_out(a_out){}
virtual~ utest(){}
public:
utest(const utest& a_from):parent(a_from),m_out(a_from.m_out){}
utest& operator=(const utest& a_from){ parent::operator=(a_from);return *this;}
public:
void add(const std::string& a_name,test::func a_func) {
(*this).push_back(named_test(a_name,test(false,a_func)));
}
void add(const std::string& a_name,test::func2 a_func) {
(*this).push_back(named_test(a_name,test(false,a_func)));
}
void add(const std::string& a_name,test::func3 a_func) {
(*this).push_back(named_test(a_name,test(false,a_func)));
}
void add(const std::string& a_name,test::cfunc a_func) {
(*this).push_back(named_test(a_name,test(false,a_func)));
}
bool exec(const args& a_args,bool a_verbose,int a_argc=0,char** a_argv=0) {
{tools_vforit(named_test,*this,it) (*it).second.m_do_it = false;}
{tools_vforcit(args::arg,a_args.get_args(),it) {
const std::string& key = (*it).first;
bool found = false;
tools_vforit(named_test,*this,itn) {
const std::string& name = (*itn).first;
if(key==std::string("-"+name)) {found=true;break;}
if(key==std::string("-no_"+name)) {found=true;break;} //valid arg, but not a test.
}
if(!found) {
m_out << "WARNING : arg " << sout(key) << " is not a test." << std::endl;
}
}}
bool some = false;
{tools_vforit(named_test,*this,it) {
const std::string& name = (*it).first;
if(a_args.is_arg("-"+name)) {
(*it).second.m_do_it = true;
some = true;
}
}}
if(!some) { //do all.
tools_vforit(named_test,*this,it) (*it).second.m_do_it = true;
}
{tools_vforit(named_test,*this,it) {
const std::string& name = (*it).first;
if(a_args.is_arg("-no_"+name)) {
(*it).second.m_do_it = false;
}
}}
bool status = true;
{tools_vforcit(named_test,*this,it) {
const std::string& name = (*it).first;
if((*it).second.m_do_it && (*it).second.m_func) {
if(a_verbose) m_out << "test_" << name << " ..." << std::endl;
if(!(*it).second.m_func(m_out,a_verbose)) {
m_out << "test_" << name << " failed." << std::endl;
status = false;
}
if(a_verbose) m_out << "test_" << name << " end." << std::endl;
}
}}
{tools_vforcit(named_test,*this,it) {
const std::string& name = (*it).first;
if((*it).second.m_do_it && (*it).second.m_func2) {
if(a_verbose) m_out << "test_" << name << " ..." << std::endl;
if(!(*it).second.m_func2(m_out,a_args)) {
m_out << "test_" << name << " failed." << std::endl;
status = false;
}
if(a_verbose) m_out << "test_" << name << " end." << std::endl;
}
}}
{tools_vforcit(named_test,*this,it) {
const std::string& name = (*it).first;
if((*it).second.m_do_it && (*it).second.m_func3) {
if(a_verbose) m_out << "test_" << name << " ..." << std::endl;
if(!(*it).second.m_func3(m_out,a_argc,a_argv)) {
m_out << "test_" << name << " failed." << std::endl;
status = false;
}
if(a_verbose) m_out << "test_" << name << " end." << std::endl;
}
}}
{tools_vforcit(named_test,*this,it) {
const std::string& name = (*it).first;
if((*it).second.m_do_it && (*it).second.m_cfunc) {
if(a_verbose) m_out << "test_" << name << " ..." << std::endl;
if(!(*it).second.m_cfunc(stdout,a_verbose)) {
m_out << "test_" << name << " failed." << std::endl;
status = false;
}
if(a_verbose) m_out << "test_" << name << " end." << std::endl;
}
}}
tools_vforit(named_test,*this,it) (*it).second.m_do_it = false;
return status;
}
void list() {tools_vforit(named_test,*this,it) m_out << (*it).first << std::endl;}
protected:
std::ostream& m_out;
};
}
#endif
+4 -4
View File
@@ -5,13 +5,13 @@
#define tools_version
#define TOOLS_MAJOR_VERSION 5
#define TOOLS_MINOR_VERSION 4
#define TOOLS_MINOR_VERSION 6
#define TOOLS_PATCH_VERSION 0
#define TOOLS_VERSION "5.4.0"
#define TOOLS_VERSION_VRP "v5r4p0"
#define TOOLS_VERSION "5.6.0"
#define TOOLS_VERSION_VRP "v5r6p0"
namespace tools {
inline unsigned int version() {return 50400;}
inline unsigned int version() {return 50600;}
}
#endif
+13
View File
@@ -325,6 +325,19 @@ public:
return;
}
} else if((*it).cls_id()==_cid_std_vector<std::string>()) {
std::vector<std::string>* vec = (std::vector<std::string>*)(*it).user_obj();
if(vec) {
create_column<std::string>((*it).name(),*vec);
} else {
a_out << "tools::waxml::ntuple :"
<< " for std::vector column " << sout((*it).name())
<< ", the user vector pointer is null."
<< std::endl;
safe_clear<iobj>(m_cols);
return;
}
} else {
a_out << "tools::waxml::ntuple :"
<< " for column " << sout((*it).name())
-191
View File
@@ -1,191 +0,0 @@
// Copyright (C) 2010, Guy Barrand. All rights reserved.
// See the file tools.license for terms.
#ifndef tools_xpm
#define tools_xpm
#include <cstdio> //FILE,size_t
#include <string>
#include <vector>
#include <ostream>
#include "charmanip"
namespace tools {
namespace xpm {
typedef unsigned char* (*file_reader)(std::ostream&,const std::string&,unsigned int&,unsigned int&,unsigned int&);
inline bool to_xpm(std::ostream& a_out,const std::string& a_file,const std::string& a_name,file_reader a_file_reader,bool a_verbose) {
// a_name is the xpm name. Then a string without a path and without
// the .xpm suffix.
unsigned int w,h,bpp;
unsigned char* buffer = a_file_reader(a_out,a_file,w,h,bpp);
if(!buffer) {
a_out << "tools::xpm::to_xpm :"
<< " read_file failed."
<< std::endl;
return false;
}
// get colormap :
typedef unsigned int color;
std::vector<color> colors;
{unsigned char r,g,b;
for(unsigned int j=0;j<h;j++) {
unsigned char* pos = buffer + j * (w * 3);
for(unsigned int i=0;i<w;i++) {
r = *pos;pos++;
g = *pos;pos++;
b = *pos;pos++;
color c = 0;
unsigned char* ca = (unsigned char*)&c;
ca[0] = r;
ca[1] = g;
ca[2] = b;
ca[3] = 0;
//printf("debug : get : %d %d %d : %lu\n",r,g,b,colors.size());
bool found = false;
std::vector<color>::iterator it;
for(it=colors.begin();it!=colors.end();++it) {
if(*it==c) {
found = true;
break;
}
}
if(!found) colors.push_back(c);
}
}}
unsigned int colorn = (unsigned int)colors.size();
//get a set of non problematic characters (for exa avoid \).
std::vector<unsigned char> chars;
{for(unsigned char c=0;c<255;c++) {
if(is_letter(c)||is_digit(c)) {
chars.push_back(c);
}
}}
unsigned int base = (unsigned int)chars.size();
unsigned int nchar = 1;
{unsigned int i = colorn;
while(i>=base) {
//unsigned int r = i%base;
i /= base;
nchar++;
}}
if(a_verbose) {
a_out << "colors " << colorn
<< " base " << base
<< " nchar " << nchar
<< std::endl;
}
std::string xpm = a_name+".xpm";
FILE* out = ::fopen(xpm.c_str(),"wb");
if(!out) {
a_out << "tools::xpm::to_xpm :"
<< " can't open " << xpm
<< std::endl;
delete [] buffer;
return false;
}
::fprintf(out,"%s","/* XPM */\n");
::fprintf(out,"static const char *%s[] = {\n",a_name.c_str());
::fprintf(out,"\"%u %u %u %u\",\n",w,h,colorn,nchar);
// write colormap :
{for(unsigned int index=0;index<colorn;index++) {
::fprintf(out,"%s","\"");
{unsigned int ix = index;
for(unsigned int ic=0;ic<nchar;ic++) {
::fprintf(out,"%c",chars[ix%base]);
ix /= base;
}}
::fprintf(out,"%s","\tc #");
color c = colors[index];
unsigned char* ca = (unsigned char*)&c;
::fprintf(out,"%02x%02x%02x",ca[0],ca[1],ca[2]);
::fprintf(out,"%s","\",\n");
}}
//pixmap :
{unsigned char r,g,b;
for(unsigned int j=0;j<h;j++) {
unsigned char* pos = buffer + j * (w * 3);
::fprintf(out,"%s","\"");
for(unsigned int i=0;i<w;i++) {
r = *pos;pos++;
g = *pos;pos++;
b = *pos;pos++;
color c;
unsigned char* ca = (unsigned char*)&c;
ca[0] = r;
ca[1] = g;
ca[2] = b;
ca[3] = 0;
bool found = false;
{for(unsigned int index=0;index<colorn;index++) {
//unsigned char c1 = index%base;
//unsigned char c2 = index/base;
if(c==colors[index]) {
{unsigned int ix = index;
for(unsigned int ic=0;ic<nchar;ic++) {
::fprintf(out,"%c",chars[ix%base]);
ix /= base;
}}
//::fprintf(out,"%c%c",chars[c1],chars[c2]);
found = true;
break;
}
}}
if(!found) {
a_out << "tools::xpm::to_xpm :"
<< " color not found in the colormap."
<< std::endl;
::fclose(out);
::remove(xpm.c_str());
delete [] buffer;
return false;
}
}
if(j==(h-1))
::fprintf(out,"%s\n","\"");
else
::fprintf(out,"%s\n","\",");
}}
::fprintf(out,"%s","};");
::fclose(out);
delete [] buffer;
return true;
}
}}
#endif
File diff suppressed because it is too large Load Diff
+7
View File
@@ -0,0 +1,7 @@
//
// Guy Barrand 8 October 2021.
//
// Dummy file so that Geant4/cmake can build a module for g4tools.
//
bool g4tools_dummy_function() {return true;}