GL Studio C++ Runtime API
util.h
Go to the documentation of this file.
1/// \file util.h
2/// \brief Generally useful defines, macros, enumerations and function prototypes.
3///
4/// \par Copyright Information
5///
6/// Copyright (c) 2017 by The DiSTI Corporation.<br>
7/// 12249 Science Drive; Suite 300<br>
8/// Orlando, Florida 32826<br>
9/// USA<br>
10/// <br>
11/// All rights reserved.<br>
12///
13/// This Software contains proprietary trade secrets of DiSTI and may not be
14/// reproduced, in whole or part, in any form, or by any means of electronic,
15/// mechanical, or otherwise, without the written permission of DiSTI. Said
16/// permission may be derived through the purchase of applicable DiSTI product
17/// licenses which detail the distribution rights of this content and any
18/// Derivative Works based on this or other copyrighted DiSTI Software.
19///
20/// NO WARRANTY. THE SOFTWARE IS PROVIDED "AS-IS," WITHOUT WARRANTY OF ANY KIND,
21/// AND ANY USE OF THIS SOFTWARE PRODUCT IS AT YOUR OWN RISK. TO THE MAXIMUM EXTENT
22/// PERMITTED BY APPLICABLE LAW, DISTI AND ITS SUPPLIERS DISCLAIM ALL WARRANTIES
23/// AND CONDITIONS, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
24/// IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY AND/OR FITNESS FOR A
25/// PARTICULAR PURPOSE, TITLE, AND NON-INFRINGEMENT, WITH REGARD TO THE SOFTWARE.
26///
27/// LIMITATION OF LIABILITY. TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW,
28/// IN NO EVENT SHALL DISTI OR ITS SUPPLIERS BE LIABLE FOR ANY SPECIAL, INCIDENTAL,
29/// INDIRECT, OR CONSEQUENTIAL DAMAGES WHATSOEVER (INCLUDING, WITHOUT LIMITATION,
30/// DAMAGES FOR LOSS OF BUSINESS PROFITS, BUSINESS INTERRUPTION, LOSS OF BUSINESS
31/// INFORMATION, OR ANY OTHER PECUNIARY LOSS) ARISING OUT OF THE USE OF OR
32/// INABILITY TO USE THE SOFTWARE, EVEN IF DISTI HAS BEEN ADVISED OF THE POSSIBILITY
33/// OF SUCH DAMAGES. DISTI'S ENTIRE LIABILITY AND YOUR EXCLUSIVE REMEDY SHALL NOT
34/// EXCEED FIVE DOLLARS (US$5.00).
35///
36/// The aforementioned terms and restrictions are governed by the laws of the
37/// State of Florida and the United States of America.
38
39#ifndef INCLUDED_GLS_RUNTIME_UTIL_H
40#define INCLUDED_GLS_RUNTIME_UTIL_H
41
42#include "ConvertUTF.h"
43#include "disti_assert.h"
44#include "dynamic_array.h"
46#include "gls_include.h"
47#include "gls_matrix_affine.h"
48#include "scoped_ptr.h"
49#include "unhide_globals.h"
50#include "vertex.h"
51
52#include <algorithm>
53#include <cmath>
54#include <iostream>
55#include <sstream>
56#include <string>
57#include <typeinfo>
58#include <vector>
59
60#ifdef WIN32
61# include <direct.h>
62
63# define _CRT_FUNCTIONS_REQUIRED 1
64#else
65# include <unistd.h>
66#endif
67
68#if defined( QNX )
69# include <stdio.h>
70#else
71# include <cstdio>
72#endif
73
74#if defined( LINUX ) || defined( __VXWORKS__ ) || defined( __APPLE__ ) || defined( QNX )
75# include <strings.h>
76#endif
77
78#ifdef ANDROID
79# include <android/asset_manager.h>
80#endif
81
82const int DIALOG_MAX_DIRECTORY_LENGTH = 1024; ///< Limited by FLTK FileBrowser.
83
84class Fl_Window;
85
86/// Wrap code that should only be compiled in debug in GLS_DEBUG_CODE().
87#if defined( GLS_DEBUG ) || !defined( NDEBUG )
88# define GLS_DEBUG_CODE( x ) x
89#else
90# define GLS_DEBUG_CODE( x )
91#endif
92
93namespace disti
94{
95class Vertex;
96class DisplayObject;
97class DisplayFrame;
98
99#ifndef TRUE
100# define TRUE 1 ///< True macro, for backward compatibility purposes.
101#endif
102
103#ifndef FALSE
104# define FALSE 0 ///< False macro, for backward compatibility purposes.
105#endif
106
107#ifdef WIN32
108inline int strcasecmp( const char* const x, const char* const y )
109{
110 return _stricmp( x, y );
111}
112#endif
113
114/** Used to generate inline textures. The writing and reading of the lines need to know the length. */
116
117const char PARSER_CLEARSTRING_DELIMETER_START[] = "#$STRING_START$#"; ///< Used for parsing lines of clear (multiline otherwise unencoded) text.
118const char PARSER_CLEARSTRING_DELIMETER_END[] = "#$STRING_END$#"; ///< Used for parsing lines of clear (multiline otherwise unencoded) text.
119
120const double HIT_TOLERANCE = 5.0; ///< The hit tolerance in logical units for selecting objects in the editor.
121
122/// Determines if x is included in the range x1 to x2.
123/// \param x The value to check.
124/// \param x1 The minimum range.
125/// \param x2 The maximum range.
126/// \return Whether or not x is in the range.
127template<class X, class X1, class X2>
128bool BETWEEN( const X& x, const X1& x1, const X2& x2 )
129{
130 return ( x >= x1 && x <= x2 )
131 || ( x >= x2 && x <= x1 );
132}
133
134/// Determines if the argument is negative.
135/// \param x The value to check.
136/// \return True if x is negative.
137template<class X>
138bool IS_NEGATIVE( const X& x ) { return std::fabs( x ) > 0.0001 ? ( x < 0.0 ) : 0; }
139
140/// Determines if the argument is positive.
141/// \param x The value to check.
142/// \return True if x is positive.
143template<class X>
144bool IS_POSITIVE( const X& x ) { return std::fabs( x ) > 0.0001 ? ( x > 0.0 ) : 0; }
145
146/// Determines if the argument is small (< 1e-1).
147/// \param x The value to check.
148/// \param threshold A small value near zero to check from.
149/// \return True if x is closer to zero than threshold.
150template<class X>
151bool CloseToZero( const X x, const X threshold = X( 1e-1 ) )
152{
153 return std::fabs( x ) < threshold;
154}
155
156/// Determines if the argument is extremely small (< 10E-4).
157/// \param x The value to check.
158/// \return True if x is very close to zero.
159template<class X>
160bool VeryCloseToZero( X x ) { return CloseToZero( x, X( 0.0001 ) ); }
161
162/// Determines if the argument is very small (< 10E-3).
163/// \param x The value to check.
164/// \return True if x is close to zero.
165template<class X>
166bool IsNearZero( X x ) { return CloseToZero( x, X( 0.001 ) ); }
167
168/// \deprecated Renamed to IsNearZero().
169/// \param x The value to check.
170/// \return True if x is close to zero.
171template<class X>
172bool IS_ZERO( X x ) { return IsNearZero( x ); }
173
174#ifndef MIN
175/// Determines which argument is smaller
176/// \deprecated Use disti::Min() instead.
177# define MIN( A, B ) ( ( A ) < ( B ) ? ( A ) : ( B ) )
178#endif
179
180#ifndef MAX
181/// Determines which argument is larger
182/// \deprecated Use disti::Min() instead.
183# define MAX( A, B ) ( ( A ) > ( B ) ? ( A ) : ( B ) )
184#endif
185
186/// Use for determining the current OpenGL version available in the current runtime environment.
187/// It may not be valid until called after a valid rendering context has been assigned.
188/// \return The X.Y OpenGL version.
190
191/// \return Whether or not the requested OpenGL extension is supported.
192/// \param extension The string name of the extension to check.
193GLS_EXPORT bool gltIsExtSupported( const char* extension );
194
195// Additional #defines
196/// From glext.h Available at http://oss.sgi.com/projects/ogl-sample/registry/
197#ifndef GLES
198# define GLSTUDIO_CLAMP_TO_EDGE ( OpenGLVersion() >= 1.2f ? 0x812F : GL_CLAMP )
199#else
200# define GLSTUDIO_CLAMP_TO_EDGE GL_CLAMP_TO_EDGE
201#endif
202
203/** GL Studio color defines */
204// \enum color enumerations for use with GlsDefinedColor methods
206{
207 GLS_COLOR_WHITE,
208 GLS_COLOR_CYAN,
209 GLS_COLOR_RED,
210 GLS_COLOR_AMBER,
211 GLS_COLOR_GREEN,
212 GLS_COLOR_YELLOW,
213 GLS_COLOR_MAGENTA,
214 GLS_COLOR_BLACK,
215 GLS_COLOR_BLUE,
216 GLS_COLOR_MAX
217};
218
219/** Predefined colors (see \sa GlsDefinedColorEnum for the values). Use \sa GlsDefinedColor() for a range-checked version. */
220GLS_EXPORT extern unsigned char glsDefinedColors[ GLS_COLOR_MAX ][ 4 ];
221
222/** Gets a predefined color in \sa GlsDefinedColorEnum.
223 * \param index of defined color
224 * \return an unsigned char array of the specified index
225 */
226inline unsigned char* GlsDefinedColor( GlsDefinedColorEnum index )
227{
228 if( ( index < 0 ) || ( index >= GLS_COLOR_MAX ) )
229 return glsDefinedColors[ 0 ];
230 else
231 return glsDefinedColors[ index ];
232}
233
234/// Allow the user to change the predefined colors.
235/// \param index The index of the color to change.
236/// \param red The new red channel value to set (0-255).
237/// \param green The new green channel value to set (0-255).
238/// \param blue The new blue channel value to set (0-255).
239/// \param alpha The new alpha channel value to set (0-255).
242 unsigned char red,
243 unsigned char green,
244 unsigned char blue,
245 unsigned char alpha )
246{
247 if( ( index >= 0 ) && ( index < GLS_COLOR_MAX ) )
248 {
249 glsDefinedColors[ index ][ 0 ] = red;
250 glsDefinedColors[ index ][ 1 ] = green;
251 glsDefinedColors[ index ][ 2 ] = blue;
252 glsDefinedColors[ index ][ 3 ] = alpha;
253 }
254}
255
256#ifndef WIN32
257/** helper class that enables use of basic_string< unsigned short > on unix
258 * \see std::char_traits
259 */
261{
262 typedef unsigned short char_type; ///< Typedef for the underlying char type.
263 typedef int int_type; ///< Typedef for the underlying int type.
264 typedef std::streampos pos_type; ///< Typedef for the underlying stream position type.
265 typedef std::streamoff off_type; ///< Typedef for the underlying stream offset type.
266 typedef std::mbstate_t state_type; ///< Typedef for the underlying multibyte conversion state type.
267
268 /// \see std::char_traits::assign
269 /// \param c1
270 /// \param c2
271 static void assign( char_type& c1, const char_type& c2 )
272 {
273 c1 = c2;
274 }
275
276 /// \see std::char_traits::eq
277 /// \param c1
278 /// \param c2
279 /// \return
280 static bool eq( const char_type& c1, const char_type& c2 )
281 {
282 return c1 == c2;
283 }
284
285 /// \see std::char_traits::lt
286 /// \param c1
287 /// \param c2
288 /// \return
289 static bool lt( const char_type& c1, const char_type& c2 )
290 {
291 return c1 < c2;
292 }
293
294 /// \see std::char_traits::compare
295 /// \param s1
296 /// \param s2
297 /// \param n
298 /// \return
299 static int compare( const char_type* s1, const char_type* s2, size_t n )
300 {
301 if( n == 0 )
302 {
303 return ( 0 );
304 }
305 do
306 {
307 if( *s1 != *s2++ )
308 {
309 return ( *s1 - *( s2 - 1 ) );
310 }
311 if( *s1++ == 0 )
312 {
313 break;
314 }
315 } while( --n != 0 );
316 return ( 0 );
317 }
318
319 /// \see std::char_traits::length
320 /// \param s
321 /// \return
322 static size_t length( const char_type* s )
323 {
324 size_t x = 0u;
325 while( *s++ )
326 {
327 ++x;
328 }
329 return ( x );
330 }
331
332 /// \see std::char_traits::find
333 /// \param s
334 /// \param n
335 /// \param a
336 /// \return
337 static const char_type* find( const char_type* s, size_t n, const char_type& a )
338 {
339 while( n-- > 0 )
340 {
341 if( *s == a )
342 {
343 return s;
344 }
345 ++s;
346 }
347 return NULL;
348 }
349
350 /// \see std::char_traits::move
351 /// \param s1
352 /// \param s2
353 /// \param n
354 /// \return
355 static char_type* move( char_type* s1, const char_type* s2, size_t n )
356 {
357 return static_cast<char_type*>( memmove( s1, s2, n * sizeof( char_type ) ) );
358 }
359
360 /// \see std::char_traits::copy
361 /// \param s1
362 /// \param s2
363 /// \param n
364 /// \return
365 static char_type* copy( char_type* s1, const char_type* s2, size_t n )
366 {
367 return static_cast<char_type*>( memcpy( s1, s2, n * sizeof( char_type ) ) );
368 }
369
370 /// \see std::char_traits::assign
371 /// \param s
372 /// \param n
373 /// \param a
374 /// \return
375 static char_type* assign( char_type* s, size_t n, char_type a )
376 {
377 for( size_t idx = 0u; idx < n; ++idx )
378 {
379 s[ idx ] = a;
380 }
381 return ( s );
382 }
383
384 /// \see std::char_traits::to_char_type
385 /// \param c
386 /// \return
387 static char_type to_char_type( const int_type& c )
388 {
389 return static_cast<char_type>( c );
390 }
391
392 /// \see std::char_traits::to_int_type
393 /// \param c
394 /// \return
395 static int_type to_int_type( const char_type& c )
396 {
397 return static_cast<int_type>( c );
398 }
399
400 /// \see std::char_traits::eq_int_type
401 /// \param c1
402 /// \param c2
403 /// \return
404 static bool eq_int_type( const int_type& c1, const int_type& c2 )
405 {
406 return c1 == c2;
407 }
408
409 /// \see std::char_traits::eof
410 /// \return
411 static int_type eof()
412 {
413 return static_cast<int_type>( EOF );
414 }
415
416 /// \see std::char_traits::not_eof
417 /// \param c
418 /// \return
419 static int_type not_eof( const int_type& c )
420 {
421 return ( c == eof() ) ? 0 : c;
422 }
423};
424
425typedef std::basic_string<unsigned short, CharTraitsUnsignedShort> UTF16String; ///< A cross platform UTF-16 encoded string.
426typedef std::ofstream UTF16Outfilestream; ///< A cross platform UTF-16 encoded ofstream.
427typedef std::ostream UTF16Outstream; ///< A cross platform UTF-16 encoded ostream.
428typedef std::string UnicodeString; ///< A cross platform UTF-8 encoded string.
429typedef std::ofstream UnicodeOutfilestream; ///< A cross platform UTF-8 encoded ofstream.
430typedef std::ostream UnicodeOutstream; ///< A cross platform UTF-8 encoded string.
431
432#else
433
434typedef std::wstring UTF16String; ///< A cross platform UTF-16 encoded string.
435typedef std::wofstream UTF16Outfilestream; ///< A cross platform UTF-16 encoded ofstream.
436typedef std::wostream UTF16Outstream; ///< A cross platform UTF-16 encoded ostream.
437typedef std::wstring UnicodeString; ///< A cross platform UTF-8 encoded string.
438typedef std::wofstream UnicodeOutfilestream; ///< A cross platform UTF-8 encoded ofstream.
439typedef std::wostream UnicodeOutstream; ///< A cross platform UTF-8 encoded string.
440
441#endif
442
443/// Convert the given UTF8 string to UTF16.
444/// \param src The string in question.
445/// \return The given string in UTF16.
446inline UTF16String ConvertUTF8ToWide( const std::string& src )
447{
448 UTF16String ret;
449 if( src.size() > 0u )
450 {
451 // allocate buffer for string plus terminator
452 const unsigned int srcLen = (unsigned int)src.size();
453 const unsigned int utf16BufLen = (unsigned int)( src.size() + 1u );
454 UTF16* utf16Buf = new UTF16[ src.size() + 1u ];
455 // NULL out buffer
456 memset( utf16Buf, 0, ( utf16BufLen * sizeof( UTF16 ) ) );
457
458 // convert UTF8 to UTF16
459 {
460 const UTF8* srcUTF8 = (const UTF8*)( src.c_str() );
461 UTF16* targetUTF16 = utf16Buf;
462 ConvertUTF8toUTF16( &srcUTF8, &srcUTF8[ srcLen ], &targetUTF16, &( targetUTF16[ utf16BufLen - 1u ] ), strictConversion );
463 }
464 // force terminate
465 utf16Buf[ utf16BufLen - 1u ] = 0;
466 // store out
467#ifdef WIN32
468 ret.assign( (wchar_t*)utf16Buf );
469#else
470 ret.assign( (unsigned short*)utf16Buf );
471#endif
472
473 // done with buf
474 delete[]( utf16Buf );
475 utf16Buf = NULL;
476 }
477
478 return ( ret );
479}
480
481/// Return whether two numbers are "equal" to eachother taking into account
482/// a certain precision. You can use this method on any numeric types and
483/// even mix types as the parameters. Eg. you can compare integers with
484/// floating point types or compare floats and doubles without casting.
485/// \param x First number to use in the comparison which determines the range
486/// \param y Number to check if within the range determined by x and precision
487/// \param precision Number that is added to and subtracted from x to
488/// determine the range to check y against.
489/// \return True if the numbers are close enough to be considered equal.
490template<class T1, class T2>
491bool Equal( T1 x, T2 y, float precision = 0.001f )
492{
493 return ( x - precision ) <= y && y <= ( x + precision );
494}
495
496/// \return The minimum of two objects.
497/// \param x The first object to compare.
498/// \param y The second object to compare.
499/// \note The class T must have the < operator defined.
500template<class T>
501const T& Min( const T& x, const T& y )
502{
503 return x < y ? x : y;
504}
505
506/// \return The maximum of two objects.
507/// \param x The first object to compare.
508/// \param y The second object to compare.
509/// \note The class T must have the < operator defined.
510template<class T>
511const T& Max( const T& x, const T& y )
512{
513 return x < y ? y : x;
514}
515
516/// \return The minimum of two objects determined by a predicate.
517/// If pr(x, y) is true, x is returned else y.
518/// \param x The first object to compare.
519/// \param y The second object to compare.
520/// \param pr The function to serve as the predicate.
521template<class T, class Pred>
522const T& Min( const T& x, const T& y, Pred pr )
523{
524 return pr( x, y ) ? x : y;
525}
526
527/// \return The maximum of two objects determined by a predicate.
528/// If pr(x, y) is true, y is returned else x.
529/// \param x The first object to compare.
530/// \param y The second object to compare.
531/// \param pr The function to serve as the predicate.
532template<class T, class Pred>
533const T& Max( const T& x, const T& y, Pred pr )
534{
535 return pr( x, y ) ? y : x;
536}
537
538/** \brief Class to contain current OpenGL view, projection and draw matrices */
540{
541private:
542 bool _needsDelete;
543
544public:
545 int* viewMatrix; ///< The viewport matrix.
546 GlsMatrixType* projMatrix; ///< The projection matrix.
547 GlsMatrixType* modelMatrix; ///< The modelview matrix.
548
549 /// Default constructor.
550 /// Keeps everything NULL.
552
553 /// Copy constructor.
554 /// \note Pointers are copied as-is, copies of the data are NOT made.
555 /// \param src The object to copy from.
557
558 /// Another constructor.
559 /// \note Pointers are copied as-is, copies of the data are NOT made.
560 /// \param view The viewport matrix to use.
561 /// \param proj The projection matrix to use.
562 /// \param model The modelview matrix to use.
564
565 /// Destructor.
567
568 /// Retrieves the current OpenGL Matrices from the OpenGL Subsystem.
570};
571
572/// Find a transformation that will convert to a new coordinate
573/// system defined by the given origin and basis vectors (i,j,k).
574/// \note The new i,j,k vectors are in respect to the current origin.
575/// (i.e. for transformation that moves the origin
576/// along the x axis by 5 units you should pass in
577/// (Vector(5,0,0), Vector(1,0,0), Vector(0,1,0) , Vector(0,0,1))
578/// NOT (Vector(5,0,0), Vector(6,0,0), Vector(5,1,0) , Vector(5,0,1))
579/// Template argument is either double or float.
580/// \param new_origin Vector to the new coordinate system origin.
581/// \param new_i Vector parallel to the new x-axis with magnitude equal to one unit in the new coordinate system.
582/// \param new_j Vector parallel to the new y-axis with magnitude equal to one unit in the new coordinate system.
583/// \param new_k Vector parallel to the new z-axis with magnitude equal to one unit in the new coordinate system.
584/// \returns transformation matrix to the new coordinate system
585template<class T>
586GlsMatrixAffine<T> FindCoordinateTransformation( const Vector& new_origin, const Vector& new_i, const Vector& new_j, const Vector& new_k )
587{
588 GlsMatrixAffine<T> transform;
589 GlsMatrixAffine<T> rotation_scaling;
590
591 // First translate to the new origin
592
593 transform.Translate( -new_origin );
594
595 // Build a matrix taking the standard basis vectors to the new basis vectors
596
597 rotation_scaling( 0, 0 ) = new_i.x;
598 rotation_scaling( 0, 1 ) = new_j.x;
599 rotation_scaling( 0, 2 ) = new_k.x;
600 rotation_scaling( 1, 0 ) = new_i.y;
601 rotation_scaling( 1, 1 ) = new_j.y;
602 rotation_scaling( 1, 2 ) = new_k.y;
603 rotation_scaling( 2, 0 ) = new_i.z;
604 rotation_scaling( 2, 1 ) = new_j.z;
605 rotation_scaling( 2, 2 ) = new_k.z;
606
607 // Invert because we want the new basis vectors to become the standard basis vectors
608 rotation_scaling.Invert();
609
610 // Combine the translation and rotation to produce the complete transformation
611 return rotation_scaling * transform;
612}
613
614/// Find a transformation that will convert to a new coordinate
615/// system defined by the given origin and basis vectors (i,j,k).
616/// \note The new i,j,k vectors are in respect to the current origin.
617/// (i.e. for transformation that moves the origin
618/// along the x axis by 5 units you should pass in
619/// (Vector(5,0,0), Vector(1,0,0), Vector(0,1,0) , Vector(0,0,1))
620/// NOT (Vector(5,0,0), Vector(6,0,0), Vector(5,1,0) , Vector(5,0,1))
621/// Template argument is either double or float.
622/// \param new_origin Vector to the new coordinate system origin.
623/// \param new_i Vector parallel to the new x-axis with magnitude equal to one unit in the new coordinate system.
624/// \param new_j Vector parallel to the new y-axis with magnitude equal to one unit in the new coordinate system.
625/// \param new_k Vector parallel to the new z-axis with magnitude equal to one unit in the new coordinate system.
626/// \param result The returned transformation matrix to the new coordinate system.
627template<class T>
628void FindCoordinateTransformation( const Vector& new_origin, const Vector& new_i, const Vector& new_j, const Vector& new_k, GlsMatrixAffine<T>& result )
629{
630 GlsMatrixAffine<T> transform;
631 GlsMatrixAffine<T> rotation_scaling;
632
633 // First translate to the new origin
634
635 transform.Translate( -new_origin );
636
637 // Build a matrix taking the standard basis vectors to the new basis vectors
638
639 rotation_scaling( 0, 0 ) = new_i.x;
640 rotation_scaling( 0, 1 ) = new_j.x;
641 rotation_scaling( 0, 2 ) = new_k.x;
642 rotation_scaling( 1, 0 ) = new_i.y;
643 rotation_scaling( 1, 1 ) = new_j.y;
644 rotation_scaling( 1, 2 ) = new_k.y;
645 rotation_scaling( 2, 0 ) = new_i.z;
646 rotation_scaling( 2, 1 ) = new_j.z;
647 rotation_scaling( 2, 2 ) = new_k.z;
648
649 // Invert because we want the new basis vectors to become the standard basis vectors
650 rotation_scaling.Invert();
651
652 // Combine the translation and rotation to produce the complete transformation
653 result = rotation_scaling * transform;
654}
655
656/** Gets the transformation from one DisplayObject's object coordinates to another's
657 * Note: This method uses a screen-space transformation (DisplayObject::ModelMatrix). This requires that the two objects have been PreDrawn with the same view, but they do not need to be part of the same object heirarchy.
658 * Use GetObjectCoordinatesTransform unless GetObjectCoordinatesTransformSameView is required.
659 *
660 * \sa GetObjectCoordinatesTransform
661 *
662 * \param from The DisplayObject to start at
663 * \param to The DisplayObject to end at
664 * \param outTransform Out parameter - If the function returns true, this will contain the resulting transformation.
665 * \returns true on success, false if there was an error
666 */
668
669/// \param frame The DisplayFrame to start at.
670/// \return the Topmost Display Frame.
672
673/** Gets the transformation from one DisplayObject's object coordinates to another's (if possible)
674 * This is the preferred method for determining the coordinate space relationship between two objects that have DynamicTransforms applied.
675 * Note: This method requires that the two objects are part of the same object heirarchy.
676 * Consider using GetObjectCoordinatesTransformSameView if your situation does not meet this requirement.
677 *
678 * \code
679 * // Example: Move objB to be in the same location as objA (including all DynamicTransforms)
680 * // Change Location of objB so that it's RotationPoint aligns with the RotationPoint of objA
681 * GlsMatrixType transform;
682 * if( GetObjectCoordinatesTransform( objA, objB, &transform ) )
683 * {
684 * Vector objA_rotationPoint_transformed = transform * (objA->Location() + objA->RotationPoint());
685 * objB->Location( objA_rotationPoint_transformed - objB->RotationPoint() );
686 * }
687 * else
688 * {
689 * // Error: objects are not in the same heirarchy
690 * }
691 * \endcode
692 *
693 * \sa GetObjectCoordinatesTransform
694 *
695 * \param from The DisplayObject to start at
696 * \param to The DisplayObject to end at
697 * \param outTransform Out parameter - If the function returns true, this will contain the resulting transformation.
698 * \returns true on success, false if the objects are not in the same heirarchy.
699 */
701
702/// Test if the given points are not colinear (they are not in a line).
703/// \param a The first point to check.
704/// \param b The second point to check.
705/// \param c The third point to check.
706/// \return True if the points are not colinear.
707/// \return False if the points are colinear.
708GLS_EXPORT bool NotColinear( const Vector& a, const Vector& b, const Vector& c );
709
710/// Search the given Vertex array for the first three non-colinear vertices.
711/// \param arraySize The size of vertex_array.
712/// \param array The Vertex array.
713/// \param index1 variable to receive 1st array index.
714/// \param index2 variable to receive 2nd array index.
715/// \param index3 variable to receive 3rd array index.
716/// \param isVectorArray true if array points to a Vector array, false if it
717/// points to a Vertex array.
718/// \return true If the vertices were found.
719/// \return false If there are not three non-colinear vertices in the array
720/// if this occurs, the index values are undefined.
721GLS_EXPORT bool FindNonColinearVertices( int arraySize, Vector array[],
722 int& index1, int& index2, int& index3,
723 bool isVectorArray = true );
724
725/// Vertex version of FindNonColinearVertices.
726/// \param arraySize The size of vertex_array.
727/// \param array The Vertex array.
728/// \param index1 variable to receive 1st array index.
729/// \param index2 variable to receive 2nd array index.
730/// \param index3 variable to receive 3rd array index.
731/// \return true If the vertices were found.
732/// \return false If there are not three non-colinear vertices in the array
733/// if this occurs, the index values are undefined.
734inline bool FindNonColinearVertices( int arraySize, Vertex array[], int& index1, int& index2, int& index3 )
735{
736 return FindNonColinearVertices( arraySize, array, index1, index2, index3, false );
737}
738
739/// Recalculate the texture points of a given DisplayObject based on its valid texture coordinates.
740/// \param object the object whose texture points are to be calculated
741/// \return true On success.
742/// \return false If the texture points could not be calculated.
743/// (The object doesn't have three non-colinear vertices or doesn't have texture coordinates.)
745
746/** Encodes a string such that if it contains newlines, it will be wrapped with the "#$STRING_START$#" and "#$STRING_END$#" delimiters.
747 * \param dest Destination string
748 * \param src Source string
749 * \param dest_str_length Size of the destination buffer
750 * \return The length of the encoded string.
751 */
752GLS_EXPORT int EncodeString( char* dest, const char* src, const int dest_str_length );
753
754/** Encodes a std::string such that there are no whitespace characters in the string
755 * \param src Source string
756 * \return The encoded string
757 */
758GLS_EXPORT std::string EncodeString( const std::string& src );
759
760/// \return A minimum length for a call to EncodeString.
761/// \note This is based on the clear text delimeters.
763
764/** Encodes a string using C language encoding
765 * \param dest Destination string
766 * \param src Source string
767 * \param dest_str_length Size of the destination buffer
768 * \return The length of the encoded string
769 */
770GLS_EXPORT int C_EncodeString( char* dest, const char* src, const int dest_str_length );
771
772/** Returns and encoded std::string using C language encoding
773 * \param src Source string
774 * \return The encoded string
775 */
776GLS_EXPORT std::string C_EncodeString( const std::string& src );
777
778/** Decodes a string that was encoded using EncodeString
779 * \param dest Destination string
780 * \param src Source string
781 * \param dest_str_length Size of the destination buffer
782 * \return The length of the encoded string
783 */
784GLS_EXPORT int DecodeString( char* dest, const char* src, const int dest_str_length );
785
786/** Decodes a std::string that was encoded using EncodeString
787 * \param src Encoded Source string
788 * \return The decoded string
789 */
790GLS_EXPORT std::string DecodeString( const std::string& src );
791
792/** The InlinePixmap structure */
793typedef struct
794{
795 int width; ///< The width in pixels.
796 int height; ///< The height in pixels.
797 int comprSize; ///< The size in bytes.
798 unsigned char* pixels; ///< Pointer to the underlying data buffer.
800
801/// Make the incoming path relative to another path.
802/// \param originalPath The path to make relative.
803/// \param relativePath The path to make the path relative from.
804/// \return The resulting relative path, or empty string if not possible.
805GLS_EXPORT char* MakeRelativePath( const char* originalPath, const char* relativePath );
806
807/// Converts backslashes to forward slashes in the given string.
808/// \param str A pointer to a string that is changed in place.
810
811/// Converts backslashes to forward slashes in the given string.
812/// \param str Reference to a string that is changed in place.
813GLS_EXPORT void ConvertBackslashToSlash( std::string& str );
814
815/// Determines if the given value falls in any of the ranges passed in.
816/// range_check(int number_of_ranges, double test_value,
817/// int index_0,double range_0_min,double range_0_max,
818/// ...
819/// int index_n,double range_n_min,double range_n_max);
820/// For example, to return 1 for values 0-10 and 2 for values 10-20:
821/// index = range_check(2, val,
822/// 1, 0.0, 10.0,
823/// 2, 10.0, 20.0);
824/// \param num The number of ranges.
825/// \param val The value to test.
826/// \return True if the value is within any of the ranges.
827GLS_EXPORT int range_check( int num, double val, ... );
828
829/// Attempts to open the given file. Pops up an error message box if the attempt fails.
830/// \param filename The name of the file to open.
831/// \param flags fopen style file arguments (e.g. "r").
832/// \param f Contains file pointer on success.
833/// \return True if the operation was successful.
834GLS_EXPORT int Safe_fopen( const char* filename, char* flags, FILE** f );
835
836/// Stream version.
837/// \param filename The name of the file to open.
838/// \param flags fopen style file arguments (e.g. "r").
839/// \param outstr The stream to write to.
840/// \return True if the operation was successful.
841GLS_EXPORT int Safe_fopen( const char* filename, char* flags, std::fstream& outstr );
842
843#ifdef ANDROID
844/** Sets if assets should be loaded directly from the apk (default true).
845 * This only affects Android builds.
846 * \param enableDirectAssetLoading true to allow assets to be loaded directly from the apk
847 * false to force assets to be read from the resource directory (\see SetResourcePath)
848 * \post HasAssetExtension returns false for all filetypes if direct asset loading was disabled
849 */
850GLS_EXPORT void EnableDirectAssetLoading( bool enableDirectAssetLoading );
851
852/** Returns if the filetype is one that can be loaded directly from the apk assets.
853 * This only affects Android builds.
854 * \param filename The filename with extension to check
855 * \return True if the filetype can be loaded directly from the apk assets,
856 * False if the file is loaded from internal or external storage
857 */
858GLS_EXPORT bool HasAssetExtension( const char* filename );
859
860/** Returns if the file exists in the apk assets.
861 * This only affects Android builds.
862 * \param filename The name of the file
863 * \return True if the file is an asset that can be opened.
864 * Returns false if no asset exists with filename or the pointer to the AAssetManager, set with SetAssetManager, is null.
865 */
866GLS_EXPORT bool AssetExists( const char* filename );
867
868/** Sets the Android Asset Manager to use.
869 * When the assetManager is null, apk assets cannot be loaded.
870 * This only affects Android builds.
871 * \param assetManager The pointer to the AAssetManager
872 */
873GLS_EXPORT void SetAssetManager( AAssetManager* assetManager );
874#endif
875
876#if defined( ANDROID ) || ( defined( __APPLE__ ) && defined( GLES ) && !defined( GLES_ANGLE ) ) || ( defined( LINUX ) && defined( GLES ) && !defined( GLES_ANGLE ) ) || defined( QNX ) || defined( INTEGRITY )
877/** Resolves the given path searching resource path then CWD.
878 * \param[in] filename_ The name of the file
879 * \return string containing appropriate resulting resolved path, with OS specific path.
880 * On Android, apk asset files are not prepended with a path.
881 */
882GLS_EXPORT std::string ResolvePath( const char* filename_ );
883
884/** Sets the path for locating resource files.
885 * On Android, this is the location where resources outside of apk assets are found.
886 * \param resourcePath The path where application resources will be found
887 */
888GLS_EXPORT void SetResourcePath( const char* resourcePath );
889
890/** Attempts to open the given file. Prepends the filename with the path from SetResourcePath
891 * for non-absolute paths.
892 * On Android, filenames that match an apk asset are opened. Opened assets should be closed
893 * with fclose to free resources, not with the Android Asset Manager close function (AAsset_close)
894 * \param filename The name of the file to open
895 * \param flags fopen style file arguments (e.g. "r")
896 * \pre On Android, Asset Manager != NULL, set with SetAssetManager, when opening an apk asset
897 * \return FILE pointer or NULL otherwise
898 */
899GLS_EXPORT FILE* gls_fopen( const char* filename, const char* flags );
900#else
901/** Pushes a resource search path onto the stack. The CWD is always
902 * implicitly searched first. The resource search paths are local to
903 * the calling thread only. This function should be called from the same
904 * thread as the resources are loaded from.
905 * \param resourcePath The directory path to add to the search paths
906 */
907GLS_EXPORT void PushResourcePath( const char* resourcePath );
908
909/** Remove the first search path from the stack. The resource search paths
910 * are local to the calling thread only. This function should be called from
911 * the same thread as the matching PushResourcePath.
912 */
914
915/** Pushes a function that can locate resources. The Resources finders are applied after the resource paths are searched
916 * \param finder The function that can locate resources to add to the search paths
917 */
918GLS_EXPORT void PushResourceFinder( std::string ( *finder )( const std::string& ) );
919
920/// Resolves the given path searching the resource path list.
921/// The CWD is always implicity searched first.
922/// \param path The relative path to resolve.
923/// \return The appropriate resulting resolved path, prepended with the resource path.
924GLS_EXPORT std::string ResolvePath( const char* path );
925
926/// Helper method taking a std::string.
927/// \param path The relative path to resolve
928/// \return The appropriate resulting resolved path, prepended with the resource path.
929inline std::string ResolvePath( const std::string& path )
930{
931 return ResolvePath( path.c_str() );
932}
933
934/** Attempts to open the given file. Relative file paths
935 * are resolved using ResolvePath.
936 * \param filename The name of the file to open
937 * \param flags fopen style file arguments (e.g. "r")
938 * \return FILE pointer or NULL otherwise
939 */
940GLS_EXPORT FILE* gls_fopen( const char* filename, const char* flags );
941#endif
942
943/** Attempts to unlink (delete) a file given
944 a UTF-8 encoded filename.
945 This function is especially useful on Windows platforms where the
946 standard function expects UTF-16 encoded wide character filenames.
947 \param filename The filename to unlink
948 \return Returns 0 is successful, otherwise returns -1 and sets errno.
949*/
950int gls_unlink( const char* filename );
951
952#if defined( __APPLE__ ) && defined( GLES ) && !defined( GLES_ANGLE )
953/** \return a string indicating the location of a specific file in the default resource bundle.
954 * This method is designed for runtime platforms that have a pre-defined bundle
955 * location that is not immediately known to the application until runtime.
956 * in iOS, this returns the path to the main application bundle with the file name appended.
957 * \param fileName A string referring to the file without a path.
958 */
959GLS_EXPORT std::string GetAbsolutePathAndFileNameInDefaultResourceBundle( const char* fileName );
960#endif
961
962/** Prepends the resource path to a file name.
963 * \param[in] fileName The name of the file
964 * \return string containing ResourcePath + fileName, with OS specific path.
965 * On Android, apk asset files are not prepended with a path.
966 */
967GLS_EXPORT std::string ResolveRuntimeResourcePath( const char* fileName );
968
969/// \return True if the file exists, false otherwise.
970/// \param filename The filename to check.
971GLS_EXPORT bool FileExists( const char* filename );
972
973/// \return True if the file exists, false otherwise.
974/// \param filename The filename to check.
975GLS_EXPORT bool FileExists( const std::string& filename );
976
977/// \return True if the file exists and is a directory, false otherwise.
978/// \param filename The filename to check.
979GLS_EXPORT bool IsDirectory( const char* filename );
980
981/// \return True if the file exists and is a directory, false otherwise.
982/// \param filename The filename to check.
983GLS_EXPORT bool IsDirectory( const std::string& filename );
984
985/** \return The file extension for a filepath
986 * \param filepath Filepath to get extension from
987 */
988GLS_EXPORT std::string FileExtension( const std::string& filepath );
989
990/** \return The filename from a file path by stripping off anything to the left of a slash
991 * \param filepath
992 */
993GLS_EXPORT std::string FileName( const std::string& filepath );
994
995/** \return a string containing the path portion of a filename
996 * by stripping off everything to the right of the rightmost slash
997 * \param filepath A string containing a file with a path
998 */
999GLS_EXPORT std::string FilePath( const std::string& filepath );
1000
1001/** \return a pointer to the string containing the path portion of a filename
1002 * by stripping off everything to the right of the rightmost slash
1003 * \param name A string containing a file with a path
1004 * \warning If this function is called more than once all previous values WILL CHANGE to contain the newest value
1005 * \deprecated Use FilePath instead
1006 */
1007GLS_EXPORT const char* GetFilePath( const char* name );
1008
1009/** \return The filename from a file path by stripping off anything to the left of a slash
1010 * \param name A string containing just the file name without a path
1011 * \warning If this function is called more than once all previous values WILL CHANGE to contain the newest value
1012 * \deprecated Use FileName instead
1013 */
1014GLS_EXPORT char* GetFileName( const char* name );
1015
1016/** Appends a trailing slash to a path string, if one isn't there already
1017 * \param s File path
1018 */
1020
1021/** Appends a trailing slash to a path string, if one isn't there already
1022 * \param s File path
1023 */
1024GLS_EXPORT void AppendTrailingSlash( std::string& s );
1025
1026/** Convert a directory path to have the correct OS
1027 * slashes /, or \. Also make sure that the path ends in a \, or /.
1028 * So you always have the form <name 1>\\<name 2>...<name n>\\\, or <name 1>/<name 2>...<name n>/
1029 * \param path A path to convert
1030 * \return a "new-ed" string which may be longer than the original.
1031 * It is the calling functions responsibility to free the memory.
1032 */
1033GLS_EXPORT char* PathToOS( const char* path );
1034
1035/** \return The file extension for a filename
1036 * \param filename Filename to get extension from
1037 * No longer allocates memory, you can let the returned string
1038 * be colected as it falls out of scope
1039 */
1040GLS_EXPORT std::string GetExtension( const std::string& filename );
1041
1042/// \return The file name from a filename with path.
1043/// \note This does not allocate new memory, but rather just returns a pointer inside the original string.
1044/// \param path The path to return the file (base) name from.
1045GLS_EXPORT const char* GetBaseName( const char* path );
1046
1047/// \return Pointer to a position within the given \a path where the filename starts.
1048/// \deprecated This function is not const-correct. Prefer the const-correct version.
1049/// \param path The path to return the file (base) name from.
1050/// \sa GetBaseName( const char* )
1051GLS_EXPORT char* GetBaseName( char* path );
1052
1053/** Removes and double slashes from a path.
1054 * It will look for the specified type of slash.
1055 * It will modify path, but since it can only shrink,
1056 * no allocation is done.
1057 * \param path The path to operate on.
1058 * \param slash The type of slash to search for.
1059 */
1060GLS_EXPORT void RemoveDoubleSlashes( char* path, char slash = '/' );
1061
1062/** Remove all space ' ' characters from the incoming string.
1063 * \param entry String to be manupulated.
1064 */
1065GLS_EXPORT void RemoveSpaces( std::string& entry );
1066
1067/** Remove all space ' ' characters from the beginning and end of the string.
1068 * \param entry String to be manupulated.
1069 */
1070GLS_EXPORT void TrimSpaces( std::string& entry );
1071
1072/** \return The minimum angular distance between angle1 and angle2 in degrees
1073 * \param angle1 First angle
1074 * \param angle2 Second angle
1075 */
1076GLS_EXPORT float AngularDistanceDeg( float angle1, float angle2 );
1077
1078/** \return The minimum angular distance between angle1 and angle2 in radians
1079 * \param angle1 First angle
1080 * \param angle2 Second angle
1081 */
1082GLS_EXPORT float AngularDistanceRad( float angle1, float angle2 );
1083
1084/// \return Whether or not the incoming string contains something other than whitespace.
1085/// \param val The string to check.
1086GLS_EXPORT bool ContainsNonBlank( const std::string& val );
1087
1088/// Read bytes from the incoming file, excluding spaces.
1089/// \param f The file to read from.
1090/// \param result A pointer to storage to contain the result modified in place.
1091/// \param maxLen The length of the memory allocated to result in bytes.
1092/// \return True if operation was successful.
1093GLS_EXPORT bool GetNoSpaces( FILE* f, char* result, int maxLen );
1094
1095/// Reads to the next end of line and stores the result.
1096/// \param instr The stream to read from.
1097/// \param result The string reference to write the result to.
1098/// \param decode Whether or not to decode the string.
1099/// \return True if successful.
1100GLS_EXPORT bool GetToEnd( std::istream& instr, std::string& result, bool decode );
1101
1102/// Reads a Vertex from the stream.
1103/// \param instr The stream to read from.
1104/// \param vert The Vertex pointer to write the result to.
1105/// \param getColor Whether or not to parse the color also.
1106/// \return True if successful.
1107GLS_EXPORT bool GetVertex( std::istream& instr, Vertex* vert, bool getColor );
1108
1109/// Searches the specified binary file for the specified tag, and adds what immediatly follows the tag to the nameList.
1110/// \param dllFileName The path of the binary to search.
1111/// \param nameList The returned list of relevant symbol names.
1112/// \param createClassTag The symbol prefix to search for.
1113/// \return True if at least one is found, false otherwise.
1114GLS_EXPORT bool GetComponentClassNames( const char* dllFileName, DynamicArray<std::string>& nameList, const char* createClassTag = "CreateComponent_" );
1115
1116/// Opens the shared library and attempts to run GlsDefaultClassName(), if found.
1117/// \param dllFileName The file name of the shared library to search in.
1118/// \return The located class name, or an empty string if not found.
1119GLS_EXPORT std::string GetDefaultComponentClassName( const char* dllFileName );
1120
1121/** Returns the qualified instance name of an object that is
1122 * contained within given DisplayFrame. (e.g "cockpit.altimeter.needle")
1123 * Note that names are only added for each DisplayFrame (not every Group)
1124 * and the name of the topFrame is not included in the qualified name.
1125 * \param topFrame The frame in which the qualification will make sense.
1126 * \param obj The object which is a direct child or located somewhere below topFrame.
1127 * \returns The qualified instance name or an empty string if the qualified
1128 * instance name could not be determined. */
1129GLS_EXPORT std::string GetQualifiedInstanceName( const DisplayFrame* topFrame, const DisplayObject* obj );
1130
1131#if !defined( GLES ) || defined( GLES_ANGLE )
1132/// Opens a native WIN32 open file dialog on Windows, a FLTK dialog on other platforms.
1133/// \param win The FLTK window to open the dialog on top of.
1134/// \param filePath The initially selected / returned file.
1135/// \param filePathSize The size of the filePath buffer in bytes.
1136/// \param directory The initially selected / returned directory.
1137/// \param filterStr The file type filter string.
1138/// \param defaultExt The default file extension.
1139/// \param title The window title for the dialog.
1140/// \param multiSelect Whether or not to allow multiple files to be selected.
1141/// \param createFile Whether or not the dialog will allow a new file to be created.
1142/// \param fileMustExist Whether or not the specified file must already exist.
1143/// \param pathMustExist Whether or not the specified directory must already exist.
1144/// \param noChangeDirectory Whether or not the dialog will allow the user to change CWD.
1145/// \return True if a file was located successfully.
1146GLS_EXPORT bool OpenFileDialog( Fl_Window* win, char* filePath, unsigned int filePathSize,
1147 char* directory = NULL, const char* filterStr = NULL,
1148 const char* defaultExt = NULL, const char* title = NULL,
1149 bool multiSelect = false, bool createFile = false,
1150 bool fileMustExist = false, bool pathMustExist = false,
1151 bool noChangeDirectory = false );
1152
1153/// Opens a native WIN32 save file dialog on Windows, a FLTK dialog on other platforms.
1154/// \param win The FLTK window to open the dialog on top of.
1155/// \param filePath The initially selected / returned file.
1156/// \param filePathSize The size of the filePath buffer in bytes.
1157/// \param directory The initially selected / returned directory.
1158/// \param filterStr The file type filter string.
1159/// \param defaultExt The default file extension.
1160/// \param title The window title for the dialog.
1161/// \param createFile Whether or not the dialog will allow a new file to be created.
1162/// \param fileMustExist Whether or not the specified file must already exist.
1163/// \param pathMustExist Whether or not the specified directory must already exist.
1164/// \param noChangeDirectory Whether or not the dialog will allow the user to change CWD.
1165/// \return True if a file was located successfully.
1166GLS_EXPORT bool SaveFileDialog( Fl_Window* win, char* filePath, unsigned int filePathSize,
1167 char* directory = NULL, const char* filterStr = NULL,
1168 const char* defaultExt = NULL, const char* title = NULL,
1169 bool createFile = false,
1170 bool fileMustExist = false, bool pathMustExist = false,
1171 bool noChangeDirectory = false );
1172#endif
1173
1174/// Checks the OpenGL error state, and prints to stdout if there was an error.
1176
1177//---------------------------------------------------------------------------
1178/**
1179 * Returns a string which is the uppercase version of the passed parameter.
1180 *
1181 * \param str original string to convert to Uppercase
1182 *
1183 * \return a string copy of the original but in all caps.
1184 */
1185GLS_EXPORT std::string Uppercase( const std::string& str );
1186
1187/// Substitutes environment variables for their actual values in the incoming path.
1188/// \param originalPath Path to substitute environment variables.
1189/// \return The string with environment variables replaced with their actual paths.
1190GLS_EXPORT std::string ReplaceEnvironmentVariables( const char* originalPath );
1191
1192/** A singleton used for accessing the command line arguments in generated code */
1194{
1195public:
1197
1198 /// Parses the command line and takes action accordingly.
1199 /// \param argc The number of arguments.
1200 /// \param argv The array of arguments.
1201 GLS_EXPORT void ReadCommandLine( int argc, char** argv );
1202
1203 /// Prints the usage instructions for the command line operations to stdout.
1205
1206 int _argc; ///< The number of arguments.
1207 char** _argv; ///< The array of arguments.
1208
1209 /// \return Whether or not the app should run in silent mode.
1210 bool SilentMode() const { return _silentMode; }
1211
1212 /// \return The glsCommandLine singleton instance.
1214
1215private:
1216 bool _silentMode;
1217 static ScopedPtr<glsCommandLine> _instance;
1218};
1219
1220/** Used to make interface information visible to the user at design time*/
1222{
1223 char* _code; ///< e.g. "DynamicRotate("
1224 char* _usage; ///< e.g. "void DynamicRotate(float angle, int axis)"
1225 char* _comment; ///< e.g. "Sets dynamic rotation in degrees for the specified axis"
1226
1227public:
1229
1230 /// Constructor
1231 /// \param code Method name only.
1232 /// \param usage Full method signature.
1233 /// \param comment Associated comment.
1234 GLS_EXPORT InterfaceDescriptionClass( const char* code, const char* usage, const char* comment );
1235
1237
1238 /// Copy constructor
1239 /// \param source The object to copy from.
1241
1242 /// Assignment constructor
1243 /// \param source The object to copy from.
1244 /// \return The resulting object (this).
1246
1247 /// Set the code member to a new value.
1248 GLS_EXPORT void Code( const char* );
1249
1250 /// Set the usage member to a new value.
1251 GLS_EXPORT void Usage( const char* );
1252
1253 /// Set the comment member to a new value.
1254 GLS_EXPORT void Comment( const char* );
1255
1256 /// \return The current code member.
1257 const char* Code() const { return _code; }
1258
1259 /// \return The current usage member.
1260 const char* Usage() const { return _usage; }
1261
1262 /// \return The current comment member.
1263 const char* Comment() const { return _comment; }
1264
1265#if defined( DISTI_HAS_RVAL_REFS )
1266 /// Move constructor
1267 /// \param source The object to move from.
1269 : _code( NULL )
1270 , _usage( NULL )
1271 , _comment( NULL )
1272 {
1273 StealFrom( source );
1274 }
1275
1276 /// Assignment move operator
1277 /// \param source The object to move from.
1278 /// \return The resulting object (this).
1280 {
1281 if( this != &source )
1282 {
1283 // Destroy current values
1284 delete[] _code;
1285 delete[] _usage;
1286 delete[] _comment;
1287
1288 StealFrom( source );
1289 }
1290 return *this;
1291 }
1292
1293private:
1294 void StealFrom( InterfaceDescriptionClass& source )
1295 {
1296 // Take ownership
1297 _code = source._code;
1298 _usage = source._usage;
1299 _comment = source._comment;
1300
1301 // Relieve of ownership
1302 source._code = NULL;
1303 source._usage = NULL;
1304 source._comment = NULL;
1305 }
1306#endif
1307};
1308
1309typedef DynamicArray<InterfaceDescriptionClass> InterfaceListType; ///< Typedef for a list of interface description objects.
1310
1311/** Base class for GlsMultiVal template */
1313{
1314public:
1315 virtual ~GlsMultiValBase() {}
1316
1317 // These are used to avoid template problems with VC6.0
1318 typedef std::ostream ostreamType; ///< Typedef shorthand for std::ostream.
1319 typedef std::istream istreamType; ///< Typedef shorthand for std::istream.
1320
1321 /// This function serializes itself into the provided stream object.
1322 /// \param outstr This is the object used by the GlsMultiVal class to serialize itself onto.
1323 virtual void StreamOut( ostreamType& outstr ) const = 0;
1324
1325 /// Uses the provided istream object to populate the current GlsMultiVal object.
1326 /// \param instr This is the stream object used by the GlsMultiVal instance to populate itself.
1327 virtual void StreamIn( istreamType& instr ) = 0;
1328};
1329
1330/** GlsMultiVal is used to effectivly create a structure containing up
1331 * to 10 values of varying types. An instance of the class is capable
1332 * of streaming itself to and from a text stream. The individual values
1333 * will be separated by spaces when written and read from the stream.
1334 * The types have to follow some rules:
1335 * - They must themselves have the << and >> stream operators defined.
1336 * - operator>> must read all data written by operator<< and must not consume spaces or other characters that follow it
1337 * - They must have a default constructor
1338 * - They must have a copy constructor
1339 * - They shall not be void* (it is used for determining the end of the desired types).
1340 * - If a GlsPropString is used, there must be only one, and it *must* be the
1341 * last entry in the GlsMultiVal instance.
1342 * - A GlsPropStringQuoted will work in any position.
1343 * This is intended primarily for the GL Studio end user to use as a Class Property type.
1344 */
1345template<class T1,
1346 class T2 = void*,
1347 class T3 = void*,
1348 class T4 = void*,
1349 class T5 = void*,
1350 class T6 = void*,
1351 class T7 = void*,
1352 class T8 = void*,
1353 class T9 = void*,
1354 class T10 = void*>
1356{
1357 int _numVals;
1358 void CalcNumVals()
1359 {
1360 _numVals = 1;
1361 if( typeid( T2 ) != typeid( void* ) )
1362 ++_numVals;
1363 else
1364 return;
1365 if( typeid( T3 ) != typeid( void* ) )
1366 ++_numVals;
1367 else
1368 return;
1369 if( typeid( T4 ) != typeid( void* ) )
1370 ++_numVals;
1371 else
1372 return;
1373 if( typeid( T5 ) != typeid( void* ) )
1374 ++_numVals;
1375 else
1376 return;
1377 if( typeid( T6 ) != typeid( void* ) )
1378 ++_numVals;
1379 else
1380 return;
1381 if( typeid( T7 ) != typeid( void* ) )
1382 ++_numVals;
1383 else
1384 return;
1385 if( typeid( T8 ) != typeid( void* ) )
1386 ++_numVals;
1387 else
1388 return;
1389 if( typeid( T9 ) != typeid( void* ) )
1390 ++_numVals;
1391 else
1392 return;
1393 if( typeid( T10 ) != typeid( void* ) )
1394 ++_numVals;
1395 else
1396 return;
1397 }
1398
1399public:
1400 T1 _val1; ///< The first value.
1401 T2 _val2; ///< The second value.
1402 T3 _val3; ///< The third value.
1403 T4 _val4; ///< The fourth value.
1404 T5 _val5; ///< The fifth value.
1405 T6 _val6; ///< The sixth value.
1406 T7 _val7; ///< The seventh value.
1407 T8 _val8; ///< The eighth value.
1408 T9 _val9; ///< The ninth value.
1409 T10 _val10; ///< The tenth value.
1410
1411 /** Default constructor.
1412 * The _val member types must have default constructors.
1413 */
1415 {
1416 CalcNumVals();
1417 }
1418
1419 /// Copy constructor.
1420 /// This GlsMultiVal will copy values from the src GlsMultiVal.
1421 /// \param src GlsMultiVal object to use for initialization.
1423 : _val1( src._val1 )
1424 , _val2( src._val2 )
1425 , _val3( src._val3 )
1426 , _val4( src._val4 )
1427 , _val5( src._val5 )
1428 , _val6( src._val6 )
1429 , _val7( src._val7 )
1430 , _val8( src._val8 )
1431 , _val9( src._val9 )
1432 , _val10( src._val10 )
1433 {
1434 CalcNumVals();
1435 }
1436
1437 /// Full constructor. Creates a GlsMultiVal object with the provided data.
1438 /// \param val1 First value to use for intialization of type T1.
1439 /// \param val2 Second value to use for intialization of type T2.
1440 /// \param val3 Third value to use for intialization of type T3.
1441 /// \param val4 Fourth value to use for intialization of type T4.
1442 /// \param val5 Fifth value to use for intialization of type T5.
1443 /// \param val6 Sixth value to use for intialization of type T6.
1444 /// \param val7 Seventh value to use for intialization of type T7.
1445 /// \param val8 Eighth value to use for intialization of type T8.
1446 /// \param val9 Ninth value to use for intialization of type T9.
1447 /// \param val10 Tenth value to use for intialization of type T10.
1449 const T1& val1,
1450 const T2& val2 = T2(),
1451 const T3& val3 = T3(),
1452 const T4& val4 = T4(),
1453 const T5& val5 = T5(),
1454 const T6& val6 = T6(),
1455 const T7& val7 = T7(),
1456 const T8& val8 = T8(),
1457 const T9& val9 = T9(),
1458 const T10& val10 = T10() )
1459 : _val1( val1 )
1460 , _val2( val2 )
1461 , _val3( val3 )
1462 , _val4( val4 )
1463 , _val5( val5 )
1464 , _val6( val6 )
1465 , _val7( val7 )
1466 , _val8( val8 )
1467 , _val9( val9 )
1468 , _val10( val10 )
1469 {
1470 CalcNumVals();
1471 }
1472
1473 /// Equality operator
1474 /// \param val The object to compare against.
1475 /// \return True if the objects are equal.
1476 virtual bool operator==( const GlsMultiVal& val ) const
1477 {
1478 bool rval = true;
1479 // Only compare the number of used values.
1480 switch( _numVals )
1481 {
1482 // No breaks is intentional
1483 case 10: rval &= ( _val10 == val._val10 );
1484 case 9: rval &= ( _val9 == val._val9 );
1485 case 8: rval &= ( _val8 == val._val8 );
1486 case 7: rval &= ( _val7 == val._val7 );
1487 case 6: rval &= ( _val6 == val._val6 );
1488 case 5: rval &= ( _val5 == val._val5 );
1489 case 4: rval &= ( _val4 == val._val4 );
1490 case 3: rval &= ( _val3 == val._val3 );
1491 case 2: rval &= ( _val2 == val._val2 );
1492 case 1:
1493 rval &= ( _val1 == val._val1 );
1494 break;
1495 default:
1496 rval = false;
1497 }
1498 return rval;
1499 }
1500
1501 /// Inequality operator
1502 /// \param val The object to compare against.
1503 /// \return True if the objects are not equal.
1504 virtual bool operator!=( const GlsMultiVal& val ) const
1505 {
1506 return !( *this == val );
1507 }
1508
1510 {
1511 outstr << _val1;
1512 if( _numVals >= 2 )
1513 outstr << " " << _val2;
1514 if( _numVals >= 3 )
1515 outstr << " " << _val3;
1516 if( _numVals >= 4 )
1517 outstr << " " << _val4;
1518 if( _numVals >= 5 )
1519 outstr << " " << _val5;
1520 if( _numVals >= 6 )
1521 outstr << " " << _val6;
1522 if( _numVals >= 7 )
1523 outstr << " " << _val7;
1524 if( _numVals >= 8 )
1525 outstr << " " << _val8;
1526 if( _numVals >= 9 )
1527 outstr << " " << _val9;
1528 if( _numVals >= 10 )
1529 outstr << " " << _val10;
1530 }
1531
1533 {
1534 instr >> _val1;
1535 if( _numVals >= 2 )
1536 {
1537 instr.get(); // The separating space
1538 instr >> _val2;
1539 }
1540 if( _numVals >= 3 )
1541 {
1542 instr.get();
1543 instr >> _val3;
1544 }
1545 if( _numVals >= 4 )
1546 {
1547 instr.get();
1548 instr >> _val4;
1549 }
1550 if( _numVals >= 5 )
1551 {
1552 instr.get();
1553 instr >> _val5;
1554 }
1555 if( _numVals >= 6 )
1556 {
1557 instr.get();
1558 instr >> _val6;
1559 }
1560 if( _numVals >= 7 )
1561 {
1562 instr.get();
1563 instr >> _val7;
1564 }
1565 if( _numVals >= 8 )
1566 {
1567 instr.get();
1568 instr >> _val8;
1569 }
1570 if( _numVals >= 9 )
1571 {
1572 instr.get();
1573 instr >> _val9;
1574 }
1575 if( _numVals >= 10 )
1576 {
1577 instr.get();
1578 instr >> _val10;
1579 }
1580 }
1581};
1582
1583/// Stream out operator
1584/// \param outstr The stream to write to.
1585/// \param multiVal The value to write to the stream.
1586/// \return The stream in its current state.
1587GLS_EXPORT std::ostream& operator<<( std::ostream& outstr, const GlsMultiValBase& multiVal );
1588
1589/// Stream in operator
1590/// \param instr The stream to read from.
1591/// \param multiVal The returned value read from the stream.
1592/// \return The stream in its current state.
1593GLS_EXPORT std::istream& operator>>( std::istream& instr, GlsMultiValBase& multiVal );
1594
1595/** GlsPropString is designed to be used as a string in GL Studio Class Properties.
1596 * It writes itself out as a single line, and will read in up to the next newline.
1597 * It will attempt to convert itself to and from std::strings.
1598 * If it is used in a GlsMultiVal, there must be only one, and it *must* be the
1599 * last entry in the GlsMultiVal instance.
1600 * See GlsPropStringQuoted for more usefulness in GlsMultiVal.
1601 */
1603{
1604public:
1605 std::string _string; ///< The underlying wrapped string.
1606
1607 /// Default constructor. Creates an empty GlsPropString.
1609 : _string( "" )
1610 {
1611 }
1612
1613 /// Create a new GlsPropString using the provided std string.
1614 /// \param str The std::string to use to create the GlsPropString.
1615 GlsPropString( const std::string& str )
1616 : _string( str )
1617 {
1618 }
1619
1620 /// Create a new GlsPropString using the provided C-style string.
1621 /// \param str The C-style string to use to create the GlsPropString.
1622 GlsPropString( const char* str )
1623 : _string( str ? str : "" )
1624 {
1625 }
1626
1627 /// \return The underlying string value for this object.
1628 operator std::string() const
1629 {
1630 return _string;
1631 }
1632
1633 /** Get the string value for this object.
1634 * \return std::string containing the string value for this object.
1635 */
1636 std::string& String()
1637 {
1638 return _string;
1639 }
1640
1641 /// Checks lexicographic equality of the two arguments.
1642 /// \param str1 One object to compare.
1643 /// \param str2 The other object to compare.
1644 /// \return True if the objects are equal.
1645 friend bool operator==( const GlsPropString& str1, const GlsPropString& str2 )
1646 {
1647 return str1._string == str2._string;
1648 }
1649
1650 /// Checks lexicographic inequality of the two arguments.
1651 /// \param str1 One object to compare.
1652 /// \param str2 The other object to compare.
1653 /// \return True if the objects are not equal.
1654 friend bool operator!=( const GlsPropString& str1, const GlsPropString& str2 )
1655 {
1656 return !( str1 == str2 );
1657 }
1658};
1659
1660/// Stream out operator
1661/// \param outstr The stream to write to.
1662/// \param str The value to write to the stream.
1663/// \return The stream in its current state.
1664inline std::ostream& operator<<( std::ostream& outstr, const GlsPropString& str )
1665{
1666 outstr << disti::C_EncodeString( str._string );
1667 return outstr;
1668}
1669
1670/// Stream in operator
1671/// \param instr The stream to read from.
1672/// \param str The returned value read from the stream.
1673/// \return The stream in its current state.
1674inline std::istream& operator>>( std::istream& instr, GlsPropString& str )
1675{
1676 std::string temp;
1677 disti::GetToEnd( instr, temp, false );
1678 str._string = disti::DecodeString( temp );
1679
1680 return instr;
1681}
1682
1683/** GlsPropStringQuoted is designed to be used as a string in GL Studio Class Properties.
1684 * It writes itself out as a single line surrounded with quotes (""), and will read in up to the next un-escaped quote.
1685 * It will attempt to convert itself to and from std::strings.
1686 * Use of GlsPropStringQuoted is preferred over GlsPropString for use in a GlsMultiVal.
1687 */
1689{
1690public:
1691 std::string _string; ///< The underlying wrapped string.
1692
1693 /// Default constructor, create an empty GlsPropStringQuoted object.
1695 {
1696 }
1697
1698 /// Constructor, create a new GlsPropStringQuoted object using the provided std::string object.
1699 /// \param str The std::string object to use to create the GlsPropStringQuoted object
1700 GlsPropStringQuoted( const std::string& str )
1701 : _string( str )
1702 {
1703 }
1704
1705 /// Constructor, create a new GlsPropStringQuoted object using the provided C-style string.
1706 /// \param str the C-style string to use to create the GlsPropStringQuoted object.
1707 GlsPropStringQuoted( const char* str )
1708 : _string( str )
1709 {
1710 }
1711
1712 /// \return The underlying string value for this object.
1713 operator std::string() const
1714 {
1715 return _string;
1716 }
1717
1718 /// \return The underlying string value for this object.
1719 std::string& String()
1720 {
1721 return _string;
1722 }
1723
1724 /// Equality operator
1725 /// \param str The object to compare.
1726 /// \return True if the objects are equal.
1727 bool operator==( const GlsPropStringQuoted& str ) const
1728 {
1729 return str._string == _string;
1730 }
1731};
1732
1733/// Stream out operator
1734/// \param outstr The stream to write to.
1735/// \param str The value to write to the stream.
1736/// \return The stream in its current state.
1737inline std::ostream& operator<<( std::ostream& outstr, const GlsPropStringQuoted& str )
1738{
1739 outstr << '\"' << disti::C_EncodeString( str._string ) << '\"';
1740 return outstr;
1741}
1742
1743/// Stream in operator
1744/// \param instr The stream to read from.
1745/// \param str The returned value read from the stream.
1746/// \return The stream in its current state.
1747inline std::istream& operator>>( std::istream& instr, GlsPropStringQuoted& str )
1748{
1749 std::string temp;
1750 str._string = "";
1751
1752 // The next character should be a quote.
1753 // If it is not, we will attempt to do something useful anyway.
1754 if( instr.peek() != '\"' )
1755 {
1756 disti::GetToEnd( instr, temp, false );
1757 }
1758 else // Starts with quote
1759 {
1760 // Go ahead and consume the quote
1761 instr.get();
1762
1763 int lastChar = 0;
1764 int currChar = 0;
1765 // Loop until we find an un-escaped quote or we run out of stream.
1766 while( instr.good() )
1767 {
1768 lastChar = currChar;
1769 currChar = instr.get();
1770 if( currChar != -1 )
1771 {
1772 if( currChar == '\"' && lastChar != '\\' )
1773 break; // We found the trailing quote
1774 temp += (char)currChar;
1775 }
1776 }
1777 }
1778
1779 str._string = disti::DecodeString( temp );
1780
1781 return instr;
1782}
1783
1784/// String concatenation operator
1785/// \param a First string in concatenation.
1786/// \param b Second string in concatenation.
1787/// \return Value of \p a concatenated with \p b.
1789{
1790 return GlsPropString( a._string + b._string );
1791}
1792
1793/// String concatenation operator
1794/// \param a First string in concatenation.
1795/// \param b Second string in concatenation.
1796/// \return Value of \p a concatenated with \p b.
1798{
1799 return GlsPropString( a._string + b._string );
1800}
1801
1802/// String concatenation operator
1803/// \param a First string in concatenation.
1804/// \param b Second string in concatenation.
1805/// \return Value of \p a concatenated with \p b.
1807{
1808 return GlsPropStringQuoted( a._string + b._string );
1809}
1810
1811/// String concatenation operator
1812/// \param a First string in concatenation.
1813/// \param b Second string in concatenation.
1814/// \return Value of \p a concatenated with \p b.
1816{
1817 return GlsPropStringQuoted( a._string + b._string );
1818}
1819
1820/// String concatenation operator
1821/// \param a First string in concatenation.
1822/// \param b Second string in concatenation.
1823/// \return Value of \p a concatenated with \p b.
1824inline std::string operator+( const std::string& a, const GlsPropString& b )
1825{
1826 return std::string( a + b._string );
1827}
1828
1829/// String concatenation operator
1830/// \param a First string in concatenation.
1831/// \param b Second string in concatenation.
1832/// \return Value of \p a concatenated with \p b.
1833inline std::string operator+( const std::string& a, const GlsPropStringQuoted& b )
1834{
1835 return std::string( a + b._string );
1836}
1837
1838/// String append operator
1839/// \param a String that will be appended.
1840/// \param b String that will be appended to \p a.
1841/// \return Reference to \p a after value of \p b has been appended to \p a.
1843{
1844 a._string += b._string;
1845 return a;
1846}
1847
1848/// String append operator
1849/// \param a String that will be appended.
1850/// \param b String that will be appended to \p a.
1851/// \return Reference to \p a after value of \p b has been appended to \p a.
1853{
1854 a._string += b._string;
1855 return a;
1856}
1857
1858/// String append operator
1859/// \param a String that will be appended.
1860/// \param b String that will be appended to \p a.
1861/// \return Reference to \p a after value of \p b has been appended to \p a.
1862inline GlsPropString& operator+=( GlsPropString& a, const char* b )
1863{
1864 a._string += b;
1865 return a;
1866}
1867
1868/// String append operator
1869/// \param a String that will be appended.
1870/// \param b String that will be appended to \p a.
1871/// \return Reference to \p a after value of \p b has been appended to \p a.
1872inline GlsPropString& operator+=( GlsPropString& a, const std::string& b )
1873{
1874 a._string += b;
1875 return a;
1876}
1877
1878/// String append operator
1879/// \param a String that will be appended.
1880/// \param b String that will be appended to \p a.
1881/// \return Reference to \p a after value of \p b has been appended to \p a.
1883{
1884 a._string += b._string;
1885 return a;
1886}
1887
1888/// String append operator
1889/// \param a String that will be appended.
1890/// \param b String that will be appended to \p a.
1891/// \return Reference to \p a after value of \p b has been appended to \p a.
1893{
1894 a._string += b._string;
1895 return a;
1896}
1897
1898/// String append operator
1899/// \param a String that will be appended.
1900/// \param b String that will be appended to \p a.
1901/// \return Reference to \p a after value of \p b has been appended to \p a.
1903{
1904 a._string += b;
1905 return a;
1906}
1907
1908/// String append operator
1909/// \param a String that will be appended.
1910/// \param b String that will be appended to \p a.
1911/// \return Reference to \p a after value of \p b has been appended to \p a.
1912inline GlsPropStringQuoted& operator+=( GlsPropStringQuoted& a, const std::string& b )
1913{
1914 a._string += b;
1915 return a;
1916}
1917
1918/// String append operator
1919/// \param a String that will be appended.
1920/// \param b String that will be appended to \p a.
1921/// \return Reference to \p a after value of \p b has been appended to \p a.
1922inline std::string& operator+=( std::string& a, const GlsPropString& b )
1923{
1924 a += b._string;
1925 return a;
1926}
1927
1928/// String append operator
1929/// \param a String that will be appended.
1930/// \param b String that will be appended to \p a.
1931/// \return Reference to \p a after value of \p b has been appended to \p a.
1932inline std::string& operator+=( std::string& a, const GlsPropStringQuoted& b )
1933{
1934 a += b._string;
1935 return a;
1936}
1937
1938#ifndef WIN32
1939/// Open the default web browser and go to the specified URL.
1940/// \param url The URL to navigate to.
1941void SpawnBrowser( const char* url );
1942#endif
1943
1944/// Call this to check for the availability of a DiSTI controlled license.
1945/// It does not hold the license. It only checks it out and checks it back in.
1946/// \param licenseGroupName A name for what this license allows. i.e. "GL Studio Runtime".
1947/// \param feature The specific feature that will be checked out.
1948/// \param version The specific version that will be checked out.
1949/// \param quiet When true, no popup will occur upon missing license.
1950/// \return true if the license is available
1951GLS_EXPORT bool CheckDistiLicense( const char* licenseGroupName, const char* feature, const char* version, bool quiet );
1952
1953/// This will set the m parameter to an orthographic projection.
1954/// The current value of m is ignored.
1955/// This does NOT make any OpenGL calls.
1956/// \param m The matrix to hold the resulting orthographic projection.
1957/// \param left The left side coordinate.
1958/// \param right The right side coordinate.
1959/// \param bottom The bottom side coordinate.
1960/// \param top The top side coordinate.
1961/// \param zNear The near clipping coordinate.
1962/// \param zFar The far clipping coordinate.
1964 double left,
1965 double right,
1966 double bottom,
1967 double top,
1968 double zNear,
1969 double zFar );
1970
1971/// This will set the m parameter to a perspective projection.
1972/// The current value of m is ignored.
1973/// This does NOT make any OpenGL calls.
1974/// \param m The matrix to hold the resulting perspective projection.
1975/// \param fovy The vertical FOV in degrees.
1976/// \param aspect The aspect ratio.
1977/// \param zNear The near clipping distance.
1978/// \param zFar The far clipping distance.
1980 double fovy,
1981 double aspect,
1982 double zNear,
1983 double zFar );
1984
1985// using a namespace to help avoid collisions with user code. Future functionality should prefer to go here
1986namespace Util
1987{
1988 /// Clamps a value to the range [min, max].
1989 /// \param val The value to clamp.
1990 /// \param min The minimum value in the range.
1991 /// \param max The maximum value in the range.
1992 /// \return The value clamped between min and max.
1993 template<class T>
1994 T Clamp( const T& val, const T& min, const T& max )
1995 {
1996 return std::min( max, std::max( min, val ) );
1997 }
1998
1999 /// Split a string and add to existing vector of elements with delimeters removed.
2000 /// \param s The string to split
2001 /// \param delim The delimiter to split the string on.
2002 /// \param elems The vector of elements to append each split string to.
2003 /// \param maxElems The maximum number of elements to split. Remaining elements
2004 /// are appended unsplit as the last value. If 0, it does not
2005 /// have a maximum.
2006 /// \note Adapted from http://stackoverflow.com/questions/236129/split-a-string-in-c
2007 inline void Split( const std::string& s, const char delim, std::vector<std::string>& elems, const std::size_t maxElems = 0 )
2008 {
2009 std::istringstream ss( s );
2010 std::string item;
2011 while( std::getline( ss, item, delim ) )
2012 {
2013 elems.push_back( DISTI_RVAL_MOVE( item ) );
2014 if( elems.size() == maxElems )
2015 {
2016 break;
2017 }
2018 }
2019
2020 if( maxElems > 0 && elems.size() == maxElems && ss.good() )
2021 {
2022 std::string remaining;
2023 std::getline( ss, remaining, '\0' );
2024 elems.back() += delim + remaining;
2025 }
2026 else if( s.size() && s.at( s.size() - 1 ) == delim )
2027 {
2028 // Handle the case where the last item is an empty string.
2029 elems.push_back( "" );
2030 }
2031 }
2032
2033 /// Split a string return a vector of the elements with delimeters removed.
2034 /// \param s The string to split
2035 /// \param delim The delimiter to split the string on.
2036 /// \param maxElems The maximum number of elements to split. Remaining elements
2037 /// are appended unsplit as the last value. If 0, it does not
2038 /// have a maximum.
2039 /// \return The vector of split elements.
2040 /// \note Adapted from http://stackoverflow.com/questions/236129/split-a-string-in-c
2041 inline std::vector<std::string> Split( const std::string& s, const char delim, const std::size_t maxElems = 0 )
2042 {
2043 std::vector<std::string> elems;
2044 Split( s, delim, elems, maxElems );
2045 return elems;
2046 }
2047
2048 /// Passing null to std::string is not well-defined. Creates a string safely.
2049 /// \param cStr The string to create a std::string from.
2050 /// \return A std::string created from the incoming C string.
2051 inline std::string MakeString( const char* const cStr )
2052 {
2053 return ( cStr ? cStr : "" );
2054 }
2055} // namespace Util
2056
2057///////////////////////////////////////////////////////////////////////////////////////////////////
2058// Forward declarations for globals managed by GlsGlobals.
2059class GlsFontMan;
2060class IGlsStateManager;
2061class List_c;
2062class Mutex;
2063class TextureLoaderList;
2064
2065/// Hold global objects so we can control order of destruction.
2067{
2068public:
2069 /// \return The GlsGlobals singleton instance.
2071
2072 /// \return The image list.
2073 /// \sa GetImageListMutex()
2075
2076 /// \return The mutex for protecting the image list.
2077 /// \sa GetImageList()
2079
2080 /// \return The global font manager.
2082
2083 /// \return The global state manager instance.
2085
2086 /// \return The global list of texture loaders.
2088
2089private:
2090 // Order of objects is important here since they are destroyed in the reverse order listed
2091 ScopedPtr<List_c> _imageList;
2092 ScopedPtr<Mutex> _imageListMutex;
2093 ScopedPtr<GlsFontMan> _fontMan;
2094 ScopedPtr<IGlsStateManager> _stateManager;
2095 ScopedPtr<TextureLoaderList> _textureLoaders;
2096
2097 GlsGlobals();
2099 void operator=( const GlsGlobals& ) DISTI_SPECIAL_MEM_FUN_DELETE;
2100};
2101
2102// Check that bitness matches detected value
2103namespace Detail
2104{
2105 /// We need this function because 'static_assert' replacements for pre-C++11 compilers cannot be at file scope.
2106 inline void _checkPointerSize()
2107 {
2108 // clang-format off
2109 DISTI_STATIC_ASSERT_STR( ( DISTI_IS_BITNESS( 64 ) && sizeof( void* ) == 8 )
2110 || ( DISTI_IS_BITNESS( 32 ) && sizeof( void* ) == 4 ),
2111 "Pointer size is unexpected for this bitness" );
2112 DISTI_STATIC_ASSERT_STR( DISTI_IS_BITNESS( 64 ) ^ DISTI_IS_BITNESS( 32 ), "Expected one bitness to be detected." );
2113 // clang-format on
2114 }
2115} // namespace Detail
2116} // namespace disti
2117
2118// Our own local versions of a few glu methods to avoid needing to include the GL Utility library
2119/// Set up a perspective projection. Functions the same as gluPerspective().
2120/// \param fovy The vertical FOV in degrees.
2121/// \param aspect The aspect ratio.
2122/// \param zNear The near clipping distance.
2123/// \param zFar The far clipping distance.
2124GLS_EXPORT void glsPerspective( double fovy, double aspect, double zNear, double zFar );
2125
2126/// Projects a point from object space into window space. Functions the same as gluProject().
2127/// \param objx The X coordinate to project.
2128/// \param objy The Y coordinate to project.
2129/// \param objz The Z coordinate to project.
2130/// \param modelMatrix The modelview matrix to project with.
2131/// \param projMatrix The projection matrix to project with.
2132/// \param viewport The viewport to project with.
2133/// \param winx The returned projected X coordinate.
2134/// \param winy The returned projected Y coordinate.
2135/// \param winz The returned projected Z coordinate.
2136/// \return True if the operation was successful.
2137#ifdef MATRIX_TYPE_FLOAT
2138GLS_EXPORT bool glsProject( double objx, double objy, double objz,
2139 const float modelMatrix[ 16 ],
2140 const float projMatrix[ 16 ],
2141 const int viewport[ 4 ],
2142 double* winx, double* winy, double* winz );
2143#else
2144GLS_EXPORT bool glsProject( double objx, double objy, double objz,
2145 const double modelMatrix[ 16 ],
2146 const double projMatrix[ 16 ],
2147 const int viewport[ 4 ],
2148 double* winx, double* winy, double* winz );
2149#endif
2150
2151/// Unprojects a point from window space into object space. Functions the same as gluUnproject().
2152/// \param winx The X coordinate to unproject.
2153/// \param winy The Y coordinate to unproject.
2154/// \param winz The Z coordinate to unproject.
2155/// \param modelMatrix The modelview matrix to project with.
2156/// \param projMatrix The projection matrix to project with.
2157/// \param viewport The viewport to project with.
2158/// \param objx The returned unprojected X coordinate.
2159/// \param objy The returned unprojected Y coordinate.
2160/// \param objz The returned unprojected Z coordinate.
2161/// \return True if the operation was successful.
2162#ifdef MATRIX_TYPE_FLOAT
2163GLS_EXPORT bool glsUnProject( double winx, double winy, double winz,
2164 const float modelMatrix[ 16 ],
2165 const float projMatrix[ 16 ],
2166 const int viewport[ 4 ],
2167 double* objx, double* objy, double* objz );
2168#else
2169GLS_EXPORT bool glsUnProject( double winx, double winy, double winz,
2170 const double modelMatrix[ 16 ],
2171 const double projMatrix[ 16 ],
2172 const int viewport[ 4 ],
2173 double* objx, double* objy, double* objz );
2174#endif
2175
2176#endif
Definition: display_frame.h:86
Definition: display.h:95
Definition: dynamic_array.h:79
Definition: gls_font_man.h:59
Hold global objects so we can control order of destruction.
Definition: util.h:2067
Mutex & GetImageListMutex()
IGlsStateManager & GetStateManager()
static GlsGlobals & Instance()
GlsFontMan & GetFontMan()
TextureLoaderList & GetTextureLoaders()
List_c & GetImageList()
void Translate(Type x, Type y, Type z)
Definition: gls_matrix_affine.h:204
void Invert()
Definition: gls_matrix.h:751
Definition: util.h:1313
std::ostream ostreamType
Typedef shorthand for std::ostream.
Definition: util.h:1318
virtual void StreamOut(ostreamType &outstr) const =0
virtual void StreamIn(istreamType &instr)=0
std::istream istreamType
Typedef shorthand for std::istream.
Definition: util.h:1319
Definition: util.h:1356
T6 _val6
The sixth value.
Definition: util.h:1405
GlsMultiVal()
Definition: util.h:1414
T7 _val7
The seventh value.
Definition: util.h:1406
GlsMultiVal(const GlsMultiVal &src)
Definition: util.h:1422
T5 _val5
The fifth value.
Definition: util.h:1404
T4 _val4
The fourth value.
Definition: util.h:1403
T3 _val3
The third value.
Definition: util.h:1402
virtual bool operator==(const GlsMultiVal &val) const
Definition: util.h:1476
T10 _val10
The tenth value.
Definition: util.h:1409
void StreamIn(istreamType &instr) override
Definition: util.h:1532
T2 _val2
The second value.
Definition: util.h:1401
void StreamOut(ostreamType &outstr) const override
Definition: util.h:1509
GlsMultiVal(const T1 &val1, const T2 &val2=T2(), const T3 &val3=T3(), const T4 &val4=T4(), const T5 &val5=T5(), const T6 &val6=T6(), const T7 &val7=T7(), const T8 &val8=T8(), const T9 &val9=T9(), const T10 &val10=T10())
Definition: util.h:1448
T8 _val8
The eighth value.
Definition: util.h:1407
virtual bool operator!=(const GlsMultiVal &val) const
Definition: util.h:1504
T1 _val1
The first value.
Definition: util.h:1400
T9 _val9
The ninth value.
Definition: util.h:1408
Definition: util.h:1689
GlsPropStringQuoted()
Default constructor, create an empty GlsPropStringQuoted object.
Definition: util.h:1694
GlsPropStringQuoted(const std::string &str)
Definition: util.h:1700
bool operator==(const GlsPropStringQuoted &str) const
Definition: util.h:1727
std::string _string
The underlying wrapped string.
Definition: util.h:1691
GlsPropStringQuoted(const char *str)
Definition: util.h:1707
std::string & String()
Definition: util.h:1719
Definition: util.h:1603
GlsPropString(const char *str)
Definition: util.h:1622
GlsPropString()
Default constructor. Creates an empty GlsPropString.
Definition: util.h:1608
friend bool operator==(const GlsPropString &str1, const GlsPropString &str2)
Definition: util.h:1645
GlsPropString(const std::string &str)
Definition: util.h:1615
std::string _string
The underlying wrapped string.
Definition: util.h:1605
std::string & String()
Definition: util.h:1636
friend bool operator!=(const GlsPropString &str1, const GlsPropString &str2)
Definition: util.h:1654
Definition: gls_state_manager_interface.h:65
Definition: util.h:1222
const char * Code() const
Definition: util.h:1257
InterfaceDescriptionClass & operator=(const InterfaceDescriptionClass &source)
void Comment(const char *)
Set the comment member to a new value.
InterfaceDescriptionClass(const char *code, const char *usage, const char *comment)
void Code(const char *)
Set the code member to a new value.
const char * Usage() const
Definition: util.h:1260
InterfaceDescriptionClass(const InterfaceDescriptionClass &source)
InterfaceDescriptionClass(InterfaceDescriptionClass &&source)
Definition: util.h:1268
void Usage(const char *)
Set the usage member to a new value.
InterfaceDescriptionClass & operator=(InterfaceDescriptionClass &&source)
Definition: util.h:1279
const char * Comment() const
Definition: util.h:1263
Definition: list.h:134
Definition: gls_mutex.h:51
Class to contain current OpenGL view, projection and draw matrices.
Definition: util.h:540
void GetCurrent()
Retrieves the current OpenGL Matrices from the OpenGL Subsystem.
OpenGLMatrices(int *view, GlsMatrixType *proj, GlsMatrixType *model)
GlsMatrixType * modelMatrix
The modelview matrix.
Definition: util.h:547
int * viewMatrix
The viewport matrix.
Definition: util.h:545
~OpenGLMatrices()
Destructor.
GlsMatrixType * projMatrix
The projection matrix.
Definition: util.h:546
OpenGLMatrices(const OpenGLMatrices &src)
Definition: scoped_ptr.h:53
Definition: texture_loader.h:55
Definition: vertex.h:84
float y
The Y component.
Definition: vertex.h:87
float x
The X component.
Definition: vertex.h:86
float z
The Z component.
Definition: vertex.h:88
Definition: vertex.h:419
Definition: util.h:1194
int _argc
The number of arguments.
Definition: util.h:1206
static glsCommandLine * Instance()
void ReadCommandLine(int argc, char **argv)
void Usage()
Prints the usage instructions for the command line operations to stdout.
bool SilentMode() const
Definition: util.h:1210
char ** _argv
The array of arguments.
Definition: util.h:1207
Contains the DistiAssert macro.
The disti::DynamicArray class. A templated array of objects capable of dynamically growing.
Macros and helper code to determine what subset of C++11/14/17 is available.
#define DISTI_RVAL_MOVE(x)
Macro to wrap std::move, removed on compilers that don't support it.
Definition: gls_cpp_lang_support.h:195
#define DISTI_SPECIAL_MEM_FUN_DELETE
Macro to wrap function deletion, removed on compilers that don't support it.
Definition: gls_cpp_lang_support.h:245
#define DISTI_STATIC_ASSERT_STR(expr, msg)
Uses C++11's static_assert() because it is available on this platform.
Definition: gls_cpp_lang_support.h:432
#define DISTI_FINAL
Macro to wrap the final keyword, removed on compilers that don't support it.
Definition: gls_cpp_lang_support.h:223
#define DISTI_METHOD_OVERRIDE
Macro to wrap the override keyword, removed on compilers that don't support it.
Definition: gls_cpp_lang_support.h:221
#define DISTI_FUNC_NOEXCEPT
Macro to wrap the noexcept keyword, removed on compilers that don't support it.
Definition: gls_cpp_lang_support.h:239
A file for all GL Studio files to include.
#define GLS_EXPORT
Macro denoting which functions should be visible from the runtime library.
Definition: gls_include.h:50
#define DISTI_IS_BITNESS(X)
Macro for checking bitness (safer macros borrowed from https://www.fluentcpp.com/2019/05/28/better-ma...
Definition: gls_include.h:205
The GlsMatrixAffine class.
Definition: bmpimage.h:46
std::string ResolvePath(const char *path)
bool VeryCloseToZero(X x)
Definition: util.h:160
std::ostream UTF16Outstream
A cross platform UTF-16 encoded ostream.
Definition: util.h:427
void ConvertBackslashToSlash(char *str)
const char PARSER_CLEARSTRING_DELIMETER_END[]
Used for parsing lines of clear (multiline otherwise unencoded) text.
Definition: util.h:118
bool Equal(T1 x, T2 y, float precision=0.001f)
Definition: util.h:491
const char * GetBaseName(const char *path)
std::ofstream UnicodeOutfilestream
A cross platform UTF-8 encoded ofstream.
Definition: util.h:429
void PopResourcePath()
bool IsNearZero(X x)
Definition: util.h:166
int EncodeString(char *dest, const char *src, const int dest_str_length)
int Safe_fopen(const char *filename, char *flags, FILE **f)
bool gltIsExtSupported(const char *extension)
bool GetNoSpaces(FILE *f, char *result, int maxLen)
bool BETWEEN(const X &x, const X1 &x1, const X2 &x2)
Definition: util.h:128
const int INLINE_TEXTURE_LINE_LENGTH
Definition: util.h:115
const double HIT_TOLERANCE
The hit tolerance in logical units for selecting objects in the editor.
Definition: util.h:120
void AppendTrailingSlash(char *s)
std::string ResolveRuntimeResourcePath(const char *fileName)
DynamicArray< InterfaceDescriptionClass > InterfaceListType
Typedef for a list of interface description objects.
Definition: util.h:1309
bool FileExists(const char *filename)
int EncodedStringMinLength()
bool GetObjectCoordinatesTransformSameView(DisplayObject *from, DisplayObject *to, GlsMatrixType *outTransform)
bool CheckDistiLicense(const char *licenseGroupName, const char *feature, const char *version, bool quiet)
std::ostream & operator<<(std::ostream &outstr, const AttributeName &name)
void PushResourceFinder(std::string(*finder)(const std::string &))
char * GetFileName(const char *name)
std::string FileName(const std::string &filepath)
void RemoveSpaces(std::string &entry)
std::ofstream UTF16Outfilestream
A cross platform UTF-16 encoded ofstream.
Definition: util.h:426
bool CalculateTexPointsFromTexCoords(DisplayObject *object)
bool CloseToZero(const X x, const X threshold=X(1e-1))
Definition: util.h:151
bool GetVertex(std::istream &instr, Vertex *vert, bool getColor)
const char * GetFilePath(const char *name)
void GlsGetOrtho(GlsMatrixType &m, double left, double right, double bottom, double top, double zNear, double zFar)
float AngularDistanceRad(float angle1, float angle2)
unsigned char * GlsDefinedColor(GlsDefinedColorEnum index)
Definition: util.h:226
std::string FileExtension(const std::string &filepath)
char * PathToOS(const char *path)
std::string Uppercase(const std::string &str)
char * MakeRelativePath(const char *originalPath, const char *relativePath)
UTF16String ConvertUTF8ToWide(const std::string &src)
Definition: util.h:446
std::string GetQualifiedInstanceName(const DisplayFrame *topFrame, const DisplayObject *obj)
bool GetToEnd(std::istream &instr, std::string &result, bool decode)
bool IS_ZERO(X x)
Definition: util.h:172
const char PARSER_CLEARSTRING_DELIMETER_START[]
Used for parsing lines of clear (multiline otherwise unencoded) text.
Definition: util.h:117
void SpawnBrowser(const char *url)
bool FindNonColinearVertices(int arraySize, Vector array[], int &index1, int &index2, int &index3, bool isVectorArray=true)
void RemoveDoubleSlashes(char *path, char slash='/')
void CheckGLError()
Checks the OpenGL error state, and prints to stdout if there was an error.
const T & Max(const T &x, const T &y)
Definition: util.h:511
const T & Min(const T &x, const T &y)
Definition: util.h:501
bool IS_NEGATIVE(const X &x)
Definition: util.h:138
int DecodeString(char *dest, const char *src, const int dest_str_length)
void PushResourcePath(const char *resourcePath)
std::string UnicodeString
A cross platform UTF-8 encoded string.
Definition: util.h:428
void TrimSpaces(std::string &entry)
bool ContainsNonBlank(const std::string &val)
GlsPropString operator+(const GlsPropString &a, GlsPropString &b)
Definition: util.h:1788
float AngularDistanceDeg(float angle1, float angle2)
int range_check(int num, double val,...)
bool SaveFileDialog(Fl_Window *win, char *filePath, unsigned int filePathSize, char *directory=NULL, const char *filterStr=NULL, const char *defaultExt=NULL, const char *title=NULL, bool createFile=false, bool fileMustExist=false, bool pathMustExist=false, bool noChangeDirectory=false)
std::istream & operator>>(std::istream &instr, GlsColor &color)
std::basic_string< unsigned short, CharTraitsUnsignedShort > UTF16String
A cross platform UTF-16 encoded string.
Definition: util.h:425
FILE * gls_fopen(const char *filename, const char *flags)
float OpenGLVersion()
bool IsDirectory(const char *filename)
bool OpenFileDialog(Fl_Window *win, char *filePath, unsigned int filePathSize, char *directory=NULL, const char *filterStr=NULL, const char *defaultExt=NULL, const char *title=NULL, bool multiSelect=false, bool createFile=false, bool fileMustExist=false, bool pathMustExist=false, bool noChangeDirectory=false)
bool NotColinear(const Vector &a, const Vector &b, const Vector &c)
void GlsGetPerspective(GlsMatrixType &m, double fovy, double aspect, double zNear, double zFar)
void ChangeGlsDefinedColor(GlsDefinedColorEnum index, unsigned char red, unsigned char green, unsigned char blue, unsigned char alpha)
Definition: util.h:240
std::string GetExtension(const std::string &filename)
std::ostream UnicodeOutstream
A cross platform UTF-8 encoded string.
Definition: util.h:430
bool GetObjectCoordinatesTransform(DisplayObject *from, DisplayObject *to, GlsMatrixType *outTransform)
std::string ReplaceEnvironmentVariables(const char *originalPath)
unsigned char glsDefinedColors[GLS_COLOR_MAX][4]
std::string GetDefaultComponentClassName(const char *dllFileName)
GlsPropString & operator+=(GlsPropString &a, const GlsPropString &b)
Definition: util.h:1842
GlsMatrixAffine< T > FindCoordinateTransformation(const Vector &new_origin, const Vector &new_i, const Vector &new_j, const Vector &new_k)
Definition: util.h:586
bool IS_POSITIVE(const X &x)
Definition: util.h:144
GlsDefinedColorEnum
Definition: util.h:206
DisplayFrame * GetTopLevelDisplayFrame(DisplayFrame *frame)
int gls_unlink(const char *filename)
int C_EncodeString(char *dest, const char *src, const int dest_str_length)
bool GetComponentClassNames(const char *dllFileName, DynamicArray< std::string > &nameList, const char *createClassTag="CreateComponent_")
std::string FilePath(const std::string &filepath)
A smart pointer with unique ownership – poor man's std::unique_ptr.
Definition: util.h:261
static bool lt(const char_type &c1, const char_type &c2)
Definition: util.h:289
static void assign(char_type &c1, const char_type &c2)
Definition: util.h:271
static int_type to_int_type(const char_type &c)
Definition: util.h:395
static char_type * move(char_type *s1, const char_type *s2, size_t n)
Definition: util.h:355
std::mbstate_t state_type
Typedef for the underlying multibyte conversion state type.
Definition: util.h:266
static const char_type * find(const char_type *s, size_t n, const char_type &a)
Definition: util.h:337
static bool eq(const char_type &c1, const char_type &c2)
Definition: util.h:280
static int compare(const char_type *s1, const char_type *s2, size_t n)
Definition: util.h:299
static char_type to_char_type(const int_type &c)
Definition: util.h:387
static char_type * copy(char_type *s1, const char_type *s2, size_t n)
Definition: util.h:365
static int_type eof()
Definition: util.h:411
std::streampos pos_type
Typedef for the underlying stream position type.
Definition: util.h:264
unsigned short char_type
Typedef for the underlying char type.
Definition: util.h:262
static int_type not_eof(const int_type &c)
Definition: util.h:419
int int_type
Typedef for the underlying int type.
Definition: util.h:263
static size_t length(const char_type *s)
Definition: util.h:322
static bool eq_int_type(const int_type &c1, const int_type &c2)
Definition: util.h:404
std::streamoff off_type
Typedef for the underlying stream offset type.
Definition: util.h:265
static char_type * assign(char_type *s, size_t n, char_type a)
Definition: util.h:375
Definition: util.h:794
int width
The width in pixels.
Definition: util.h:795
unsigned char * pixels
Pointer to the underlying data buffer.
Definition: util.h:798
int height
The height in pixels.
Definition: util.h:796
int comprSize
The size in bytes.
Definition: util.h:797
The DistiUnhideGlobalsDummyClass class.
void _checkPointerSize()
We need this function because 'static_assert' replacements for pre-C++11 compilers cannot be at file ...
Definition: util.h:2106
std::string MakeString(const char *const cStr)
Definition: util.h:2051
void Split(const std::string &s, const char delim, std::vector< std::string > &elems, const std::size_t maxElems=0)
Definition: util.h:2007
T Clamp(const T &val, const T &min, const T &max)
Definition: util.h:1994
bool glsUnProject(double winx, double winy, double winz, const double modelMatrix[16], const double projMatrix[16], const int viewport[4], double *objx, double *objy, double *objz)
void glsPerspective(double fovy, double aspect, double zNear, double zFar)
bool glsProject(double objx, double objy, double objz, const double modelMatrix[16], const double projMatrix[16], const int viewport[4], double *winx, double *winy, double *winz)
const int DIALOG_MAX_DIRECTORY_LENGTH
Limited by FLTK FileBrowser.
Definition: util.h:82
The disti::Vertex class. A class for manipulating 3D vertices.