diff --git a/SConscript.q3map2.urt b/SConscript.q3map2.urt index db5d4a7..4aa5486 100644 --- a/SConscript.q3map2.urt +++ b/SConscript.q3map2.urt @@ -9,7 +9,7 @@ Import( [ 'utils', 'config', 'settings', 'lib_objects' ] ) env = Environment() settings.SetupEnvironment( env, config['name'] ) -env.Prepend( CPPPATH = [ '#tools/urt/tools/quake3/common', '#tools/urt/libs' ] ) +env.Prepend( CPPPATH = [ '#tools/quake3/common', ] ) env.Append( LIBS = [ 'm', 'pthread', 'png', 'jpeg' ] ) proj = utils.vcproj( os.path.join( GetLaunchDir(), 'tools/urt/tools/quake3/q3map2/q3map2.vcproj' ) ) objects = lib_objects diff --git a/include/version.h b/include/version.h index 52bc65e..408d675 100644 --- a/include/version.h +++ b/include/version.h @@ -1,4 +1,4 @@ // generated header, see makeversion.py -#define RADIANT_VERSION "1.6.2" -#define RADIANT_MINOR_VERSION "2" +#define RADIANT_VERSION "1.6.3" +#define RADIANT_MINOR_VERSION "3" #define RADIANT_MAJOR_VERSION "6" diff --git a/tools/urt/libs/archivelib.cpp b/tools/urt/libs/archivelib.cpp deleted file mode 100644 index 048968f..0000000 --- a/tools/urt/libs/archivelib.cpp +++ /dev/null @@ -1,2 +0,0 @@ - -#include "archivelib.h" diff --git a/tools/urt/libs/archivelib.h b/tools/urt/libs/archivelib.h deleted file mode 100644 index e705448..0000000 --- a/tools/urt/libs/archivelib.h +++ /dev/null @@ -1,205 +0,0 @@ - -#if !defined ( INCLUDED_ARCHIVELIB_H ) -#define INCLUDED_ARCHIVELIB_H - -#include "debugging/debugging.h" -#include "iarchive.h" -#include "stream/filestream.h" -#include "stream/textfilestream.h" -#include "memory/allocator.h" -#include "string/string.h" - -/// \brief A single-byte-reader wrapper around an InputStream. -/// Optimised for reading one byte at a time. -/// Uses a buffer to reduce the number of times the wrapped stream must be read. -template -class SingleByteInputStream -{ -typedef typename InputStreamType::byte_type byte_type; -enum { c_bufferSize = SIZE }; - -InputStreamType& m_inputStream; -byte_type m_buffer[c_bufferSize]; -byte_type* m_cur; -byte_type* m_end; - -public: - -SingleByteInputStream( InputStreamType& inputStream ) : m_inputStream( inputStream ), m_cur( m_buffer + c_bufferSize ), m_end( m_cur ){ -} -bool readByte( byte_type& b ){ - if ( m_cur == m_end ) { - if ( m_end != m_buffer + c_bufferSize ) { - return false; - } - - m_end = m_buffer + m_inputStream.read( m_buffer, c_bufferSize ); - m_cur = m_buffer; - - if ( m_end == m_buffer ) { - return false; - } - } - - b = *m_cur++; - - return true; -} -}; - -/// \brief A binary-to-text wrapper around an InputStream. -/// Converts CRLF or LFCR line-endings to LF line-endings. -template -class BinaryToTextInputStream : public TextInputStream -{ -SingleByteInputStream m_inputStream; -public: -BinaryToTextInputStream( BinaryInputStreamType& inputStream ) : m_inputStream( inputStream ){ -} -std::size_t read( char* buffer, std::size_t length ){ - char* p = buffer; - for (;; ) - { - if ( length != 0 && m_inputStream.readByte( *reinterpret_cast( p ) ) ) { - if ( *p != '\r' ) { - ++p; - --length; - } - } - else - { - return p - buffer; - } - } -} -}; - -/// \brief An ArchiveFile which is stored uncompressed as part of a larger archive file. -class StoredArchiveFile : public ArchiveFile -{ -CopiedString m_name; -FileInputStream m_filestream; -SubFileInputStream m_substream; -FileInputStream::size_type m_size; -public: -typedef FileInputStream::size_type size_type; -typedef FileInputStream::position_type position_type; - -StoredArchiveFile( const char* name, const char* archiveName, position_type position, size_type stream_size, size_type file_size ) - : m_name( name ), m_filestream( archiveName ), m_substream( m_filestream, position, stream_size ), m_size( file_size ){ -} - -static StoredArchiveFile* create( const char* name, const char* archiveName, position_type position, size_type stream_size, size_type file_size ){ - return New().scalar( name, archiveName, position, stream_size, file_size ); -} - -void release(){ - Delete().scalar( this ); -} -size_type size() const { - return m_size; -} -const char* getName() const { - return m_name.c_str(); -} -InputStream& getInputStream(){ - return m_substream; -} -}; - -/// \brief An ArchiveTextFile which is stored uncompressed as part of a larger archive file. -class StoredArchiveTextFile : public ArchiveTextFile -{ -CopiedString m_name; -FileInputStream m_filestream; -SubFileInputStream m_substream; -BinaryToTextInputStream m_textStream; -public: -typedef FileInputStream::size_type size_type; -typedef FileInputStream::position_type position_type; - -StoredArchiveTextFile( const char* name, const char* archiveName, position_type position, size_type stream_size ) - : m_name( name ), m_filestream( archiveName ), m_substream( m_filestream, position, stream_size ), m_textStream( m_substream ){ -} - -static StoredArchiveTextFile* create( const char* name, const char* archiveName, position_type position, size_type stream_size ){ - return New().scalar( name, archiveName, position, stream_size ); -} - -void release(){ - Delete().scalar( this ); -} -const char* getName() const { - return m_name.c_str(); -} -TextInputStream& getInputStream(){ - return m_textStream; -} -}; - -/// \brief An ArchiveFile which is stored as a single file on disk. -class DirectoryArchiveFile : public ArchiveFile -{ -CopiedString m_name; -FileInputStream m_istream; -FileInputStream::size_type m_size; -public: -typedef FileInputStream::size_type size_type; - -DirectoryArchiveFile( const char* name, const char* filename ) - : m_name( name ), m_istream( filename ){ - if ( !failed() ) { - m_istream.seek( 0, FileInputStream::end ); - m_size = m_istream.tell(); - m_istream.seek( 0 ); - } - else - { - m_size = 0; - } -} -bool failed() const { - return m_istream.failed(); -} - -void release(){ - delete this; -} -size_type size() const { - return m_size; -} -const char* getName() const { - return m_name.c_str(); -} -InputStream& getInputStream(){ - return m_istream; -} -}; - -/// \brief An ArchiveTextFile which is stored as a single file on disk. -class DirectoryArchiveTextFile : public ArchiveTextFile -{ -CopiedString m_name; -TextFileInputStream m_inputStream; -public: - -DirectoryArchiveTextFile( const char* name, const char* filename ) - : m_name( name ), m_inputStream( filename ){ -} -bool failed() const { - return m_inputStream.failed(); -} - -void release(){ - delete this; -} -const char* getName() const { - return m_name.c_str(); -} -TextInputStream& getInputStream(){ - return m_inputStream; -} -}; - - -#endif diff --git a/tools/urt/libs/bytebool.cpp b/tools/urt/libs/bytebool.cpp deleted file mode 100644 index 1e9579a..0000000 --- a/tools/urt/libs/bytebool.cpp +++ /dev/null @@ -1,2 +0,0 @@ - -#include "bytebool.h" diff --git a/tools/urt/libs/bytebool.h b/tools/urt/libs/bytebool.h deleted file mode 100644 index 3a64a94..0000000 --- a/tools/urt/libs/bytebool.h +++ /dev/null @@ -1,11 +0,0 @@ -#ifndef __BYTEBOOL__ -#define __BYTEBOOL__ - -// defines boolean and byte types usable in both c and c++ code -// this header is not really meant for direct inclusion, -// it is used by mathlib and cmdlib - -typedef enum { qfalse, qtrue } qboolean; -typedef unsigned char byte; - -#endif diff --git a/tools/urt/libs/bytestreamutils.cpp b/tools/urt/libs/bytestreamutils.cpp deleted file mode 100644 index 88c2046..0000000 --- a/tools/urt/libs/bytestreamutils.cpp +++ /dev/null @@ -1,2 +0,0 @@ - -#include "bytestreamutils.h" diff --git a/tools/urt/libs/bytestreamutils.h b/tools/urt/libs/bytestreamutils.h deleted file mode 100644 index 832a0ca..0000000 --- a/tools/urt/libs/bytestreamutils.h +++ /dev/null @@ -1,91 +0,0 @@ - -#if !defined( INCLUDED_BYTESTREAMUTILS_H ) -#define INCLUDED_BYTESTREAMUTILS_H - -#include - -#if defined( _MSC_VER ) - -typedef signed short int16_t; -typedef unsigned short uint16_t; -typedef signed int int32_t; -typedef unsigned int uint32_t; - -#else - -#define _ISOC9X_SOURCE 1 -#define _ISOC99_SOURCE 1 - -#define __USE_ISOC9X 1 -#define __USE_ISOC99 1 - -#include - -#endif - - -template -inline void istream_read_little_endian( InputStreamType& istream, Type& value ){ - istream.read( reinterpret_cast( &value ), sizeof( Type ) ); -#if defined( __BIG_ENDIAN__ ) - std::reverse( reinterpret_cast( &value ), reinterpret_cast( &value ) + sizeof( Type ) ); -#endif -} - -template -inline void istream_read_big_endian( InputStreamType& istream, Type& value ){ - istream.read( reinterpret_cast( &value ), sizeof( Type ) ); -#if !defined( __BIG_ENDIAN__ ) - std::reverse( reinterpret_cast( &value ), reinterpret_cast( &value ) + sizeof( Type ) ); -#endif -} - -template -inline void istream_read_byte( InputStreamType& istream, typename InputStreamType::byte_type& b ){ - istream.read( &b, 1 ); -} - - -template -inline int16_t istream_read_int16_le( InputStreamType& istream ){ - int16_t value; - istream_read_little_endian( istream, value ); - return value; -} - -template -inline uint16_t istream_read_uint16_le( InputStreamType& istream ){ - uint16_t value; - istream_read_little_endian( istream, value ); - return value; -} - -template -inline int32_t istream_read_int32_le( InputStreamType& istream ){ - int32_t value; - istream_read_little_endian( istream, value ); - return value; -} - -template -inline uint32_t istream_read_uint32_le( InputStreamType& istream ){ - uint32_t value; - istream_read_little_endian( istream, value ); - return value; -} - -template -inline float istream_read_float32_le( InputStreamType& istream ){ - float value; - istream_read_little_endian( istream, value ); - return value; -} - -template -inline typename InputStreamType::byte_type istream_read_byte( InputStreamType& istream ){ - typename InputStreamType::byte_type b; - istream.read( &b, sizeof( typename InputStreamType::byte_type ) ); - return b; -} - -#endif diff --git a/tools/urt/libs/character.cpp b/tools/urt/libs/character.cpp deleted file mode 100644 index 7d1431c..0000000 --- a/tools/urt/libs/character.cpp +++ /dev/null @@ -1,2 +0,0 @@ - -#include "character.h" diff --git a/tools/urt/libs/character.h b/tools/urt/libs/character.h deleted file mode 100644 index 5c4c04a..0000000 --- a/tools/urt/libs/character.h +++ /dev/null @@ -1,24 +0,0 @@ - -#if !defined( INCLUDED_CHARACTER_H ) -#define INCLUDED_CHARACTER_H - -/// \file -/// \brief Character encoding. - -/// \brief Returns true if \p c is an ASCII character that can be represented with 7 bits. -inline bool char_is_ascii( char c ){ - return ( c & 0x80 ) == 0; -} - -/// \brief Returns true if \p string consists entirely of ASCII characters. -inline bool string_is_ascii( const char* string ){ - while ( *string != '\0' ) - { - if ( !char_is_ascii( *string++ ) ) { - return false; - } - } - return true; -} - -#endif diff --git a/tools/urt/libs/cmdlib.h b/tools/urt/libs/cmdlib.h deleted file mode 100644 index 43e74fb..0000000 --- a/tools/urt/libs/cmdlib.h +++ /dev/null @@ -1,100 +0,0 @@ -/* - Copyright (C) 1999-2007 id Software, Inc. and contributors. - For a list of contributors, see the accompanying CONTRIBUTORS file. - - This file is part of GtkRadiant. - - GtkRadiant is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - GtkRadiant is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with GtkRadiant; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - */ - -// -// start of shared cmdlib stuff -// - -#ifndef __CMDLIB__ -#define __CMDLIB__ - -#include - - -// TTimo started adding portability code: -// return true if spawning was successful, false otherwise -// on win32 we have a bCreateConsole flag to create a new console or run inside the current one -//boolean Q_Exec(const char* pCmd, boolean bCreateConsole); -// execute a system command: -// cmd: the command to run -// cmdline: the command line -// NOTE TTimo following are win32 specific: -// execdir: the directory to execute in -// bCreateConsole: spawn a new console or not -// return values; -// if the spawn was fine -// TODO TTimo add functionality to track the process until it dies - -bool Q_Exec( const char *cmd, char *cmdline, const char *execdir, bool bCreateConsole ); - -// some easy portability crap - - -#define access_owner_read 0400 -#define access_owner_write 0200 -#define access_owner_execute 0100 -#define access_owner_rw_ 0600 -#define access_owner_r_x 0500 -#define access_owner__wx 0300 -#define access_owner_rwx 0700 - -#define access_group_read 0040 -#define access_group_write 0020 -#define access_group_execute 0010 -#define access_group_rw_ 0060 -#define access_group_r_x 0050 -#define access_group__wx 0030 -#define access_group_rwx 0070 - -#define access_others_read 0004 -#define access_others_write 0002 -#define access_others_execute 0001 -#define access_others_rw_ 0006 -#define access_others_r_x 0005 -#define access_others__wx 0003 -#define access_others_rwx 0007 - - -#define access_rwxrwxr_x ( access_owner_rwx | access_group_rwx | access_others_r_x ) -#define access_rwxrwxrwx ( access_owner_rwx | access_group_rwx | access_others_rwx ) - -// Q_mkdir -// returns true if succeeded in creating directory -#ifdef WIN32 -#include -inline bool Q_mkdir( const char* name ){ - return _mkdir( name ) != -1; -} -#else -#include -inline bool Q_mkdir( const char* name ){ - return mkdir( name, access_rwxrwxr_x ) != -1; -} -#endif - - -inline double Sys_DoubleTime( void ){ - return clock() / 1000.0; -} - - - -#endif diff --git a/tools/urt/libs/cmdlib/cmdlib.cpp b/tools/urt/libs/cmdlib/cmdlib.cpp deleted file mode 100644 index caeea43..0000000 --- a/tools/urt/libs/cmdlib/cmdlib.cpp +++ /dev/null @@ -1,127 +0,0 @@ -/* - Copyright (C) 1999-2007 id Software, Inc. and contributors. - For a list of contributors, see the accompanying CONTRIBUTORS file. - - This file is part of GtkRadiant. - - GtkRadiant is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - GtkRadiant is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with GtkRadiant; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - */ - -// -// start of shared cmdlib stuff -// - -#include "cmdlib.h" - -#include -#include - -#include "string/string.h" -#include "os/path.h" -#include "container/array.h" - -#ifdef WIN32 - #include -#endif -#if defined ( __linux__ ) || defined ( __APPLE__ ) - #include -#endif - - -#if defined ( __linux__ ) || defined ( __APPLE__ ) -bool Q_Exec( const char *cmd, char *cmdline, const char *, bool ){ - char fullcmd[2048]; - char *pCmd; -#ifdef _DEBUG - printf( "Q_Exec damnit\n" ); -#endif - switch ( fork() ) - { - case -1: - return true; - break; - case 0: - // always concat the command on linux - if ( cmd ) { - strcpy( fullcmd, cmd ); - } - else{ - fullcmd[0] = '\0'; - } - if ( cmdline ) { - strcat( fullcmd, " " ); - strcat( fullcmd, cmdline ); - } - pCmd = fullcmd; - while ( *pCmd == ' ' ) - pCmd++; -#ifdef _DEBUG - printf( "Running system...\n" ); - printf( "Command: %s\n", pCmd ); -#endif - system( pCmd ); -#ifdef _DEBUG - printf( "system() returned\n" ); -#endif - _exit( 0 ); - break; - } - return true; -} -#endif - -#ifdef WIN32 -// NOTE TTimo windows is VERY nitpicky about the syntax in CreateProcess -bool Q_Exec( const char *cmd, char *cmdline, const char *execdir, bool bCreateConsole ){ - PROCESS_INFORMATION ProcessInformation; - STARTUPINFO startupinfo = {0}; - DWORD dwCreationFlags; - GetStartupInfo( &startupinfo ); - if ( bCreateConsole ) { - dwCreationFlags = CREATE_NEW_CONSOLE | NORMAL_PRIORITY_CLASS; - } - else{ - dwCreationFlags = DETACHED_PROCESS | NORMAL_PRIORITY_CLASS; - } - const char *pCmd; - char *pCmdline; - pCmd = cmd; - if ( pCmd ) { - while ( *pCmd == ' ' ) - pCmd++; - } - pCmdline = cmdline; - if ( pCmdline ) { - while ( *pCmdline == ' ' ) - pCmdline++; - } - - if ( CreateProcess( - pCmd, - pCmdline, - NULL, - NULL, - FALSE, - dwCreationFlags, - NULL, - execdir, - &startupinfo, - &ProcessInformation - ) ) { - return true; - } - return false; -} -#endif diff --git a/tools/urt/libs/cmdlib/cmdlib.dsp b/tools/urt/libs/cmdlib/cmdlib.dsp deleted file mode 100644 index ee229aa..0000000 --- a/tools/urt/libs/cmdlib/cmdlib.dsp +++ /dev/null @@ -1,101 +0,0 @@ -# Microsoft Developer Studio Project File - Name="cmdlib" - Package Owner=<4> -# Microsoft Developer Studio Generated Build File, Format Version 6.00 -# ** DO NOT EDIT ** - -# TARGTYPE "Win32 (x86) Static Library" 0x0104 - -CFG=cmdlib - Win32 Debug -!MESSAGE This is not a valid makefile. To build this project using NMAKE, -!MESSAGE use the Export Makefile command and run -!MESSAGE -!MESSAGE NMAKE /f "cmdlib.mak". -!MESSAGE -!MESSAGE You can specify a configuration when running NMAKE -!MESSAGE by defining the macro CFG on the command line. For example: -!MESSAGE -!MESSAGE NMAKE /f "cmdlib.mak" CFG="cmdlib - Win32 Debug" -!MESSAGE -!MESSAGE Possible choices for configuration are: -!MESSAGE -!MESSAGE "cmdlib - Win32 Release" (based on "Win32 (x86) Static Library") -!MESSAGE "cmdlib - Win32 Debug" (based on "Win32 (x86) Static Library") -!MESSAGE - -# Begin Project -# PROP AllowPerConfigDependencies 0 -# PROP Scc_ProjName "cmdlib" -# PROP Scc_LocalPath ".." -CPP=cl.exe -RSC=rc.exe - -!IF "$(CFG)" == "cmdlib - Win32 Release" - -# PROP BASE Use_MFC 0 -# PROP BASE Use_Debug_Libraries 0 -# PROP BASE Output_Dir "Release" -# PROP BASE Intermediate_Dir "Release" -# PROP BASE Target_Dir "" -# PROP Use_MFC 0 -# PROP Use_Debug_Libraries 0 -# PROP Output_Dir "Release" -# PROP Intermediate_Dir "Release" -# PROP Target_Dir "" -MTL=midl.exe -F90=df.exe -# ADD BASE F90 /include:"Release/" -# ADD F90 /include:"Release/" -# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /YX /FD /c -# ADD CPP /nologo /MD /W3 /O2 /I "..\\" /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /FD /c -# SUBTRACT CPP /YX -# ADD BASE RSC /l 0x409 -# ADD RSC /l 0x409 -BSC32=bscmake.exe -# ADD BASE BSC32 /nologo -# ADD BSC32 /nologo -LIB32=link.exe -lib -# ADD BASE LIB32 /nologo -# ADD LIB32 /nologo - -!ELSEIF "$(CFG)" == "cmdlib - Win32 Debug" - -# PROP BASE Use_MFC 0 -# PROP BASE Use_Debug_Libraries 1 -# PROP BASE Output_Dir "Debug" -# PROP BASE Intermediate_Dir "Debug" -# PROP BASE Target_Dir "" -# PROP Use_MFC 0 -# PROP Use_Debug_Libraries 1 -# PROP Output_Dir "Debug" -# PROP Intermediate_Dir "Debug" -# PROP Target_Dir "" -MTL=midl.exe -F90=df.exe -# ADD BASE F90 /include:"Debug/" -# ADD F90 /include:"Debug/" -# ADD BASE CPP /nologo /W3 /GX /Z7 /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /YX /FD /c -# ADD CPP /nologo /MDd /W3 /Z7 /Od /I "..\\" /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /YX /FD /c -# ADD BASE RSC /l 0x409 -# ADD RSC /l 0x409 -BSC32=bscmake.exe -# ADD BASE BSC32 /nologo -# ADD BSC32 /nologo -LIB32=link.exe -lib -# ADD BASE LIB32 /nologo -# ADD LIB32 /nologo - -!ENDIF - -# Begin Target - -# Name "cmdlib - Win32 Release" -# Name "cmdlib - Win32 Debug" -# Begin Source File - -SOURCE=.\CMDLIB.cpp -# End Source File -# Begin Source File - -SOURCE=..\cmdlib.h -# End Source File -# End Target -# End Project diff --git a/tools/urt/libs/cmdlib/cmdlib.vcproj b/tools/urt/libs/cmdlib/cmdlib.vcproj deleted file mode 100644 index 2bd36f2..0000000 --- a/tools/urt/libs/cmdlib/cmdlib.vcproj +++ /dev/null @@ -1,122 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/tools/urt/libs/container/array.cpp b/tools/urt/libs/container/array.cpp deleted file mode 100644 index 6225b57..0000000 --- a/tools/urt/libs/container/array.cpp +++ /dev/null @@ -1,17 +0,0 @@ - -#include "array.h" - -namespace -{ -class Bleh -{ -Array m_array; -public: -Bleh() : m_array( 16 ){ -} -}; - -void testAutoArray(){ - Array array( 32 ); -} -} \ No newline at end of file diff --git a/tools/urt/libs/container/array.h b/tools/urt/libs/container/array.h deleted file mode 100644 index b79e36a..0000000 --- a/tools/urt/libs/container/array.h +++ /dev/null @@ -1,144 +0,0 @@ - -#if !defined( INCLUDED_CONTAINER_ARRAY_H ) -#define INCLUDED_CONTAINER_ARRAY_H - -#include -#include - -#include "memory/allocator.h" - -/// \brief An array whose size is variable at run-time. -/// -/// - Resizing the array destroys all the existing elements and invalidates all iterators. -/// - Default-Constructible, Copyable, Assignable. -/// - Compatible with the containers and algorithms in the Standard Template Library (STL) - http://www.sgi.com/tech/stl/ -/// -/// \param Element The type to be stored in the array. Must provide a default-constructor and a copy-constructor. -/// \param Allocator A custom memory-allocator, conforming to the std::allocator interface. -template > -class Array : public Allocator -{ -std::size_t m_size; -Element* m_data; - -Element* construct( std::size_t size ){ -#if 1 - return New( *this ).vector( size ); -#else - return new Element[size]; -#endif -} -template -Element* construct( std::size_t size, const T1& value ){ - return New( *this ).vector( size, value ); -} -void destroy( Element* data, std::size_t size ){ -#if 1 - Delete( *this ).vector( data, size ); -#else - delete[] data; -#endif -} - -public: -typedef Element value_type; -typedef value_type* iterator; -typedef const value_type* const_iterator; - -Array() - : m_size( 0 ), m_data( 0 ){ -} -Array( std::size_t size ) - : m_size( size ), m_data( construct( size ) ){ -} -template -Array( std::size_t size, const T1& value ) - : m_size( size ), m_data( construct( size, value ) ){ -} -Array( const Array& other ) - : Allocator( other ), m_size( other.size() ), m_data( construct( m_size ) ){ - std::copy( other.begin(), other.end(), begin() ); -} -template -Array( Iterator start, Iterator finish ) - : m_size( std::distance( start, finish ) ), m_data( construct( m_size ) ){ - std::copy( start, finish, begin() ); -} -~Array(){ - destroy( m_data, m_size ); -} - -Array& operator=( const Array& other ){ - Array temp( other ); - temp.swap( *this ); - return *this; -} - -void swap( Array& other ){ - std::swap( m_size, other.m_size ); - std::swap( m_data, other.m_data ); -} - -iterator begin(){ - return m_data; -} -const_iterator begin() const { - return m_data; -} -iterator end(){ - return m_data + m_size; -} -const_iterator end() const { - return m_data + m_size; -} - -value_type& operator[]( std::size_t index ){ -#if defined( _DEBUG ) - ASSERT_MESSAGE( index < size(), "array index out of bounds" ); -#endif - return m_data[index]; -} -const value_type& operator[]( std::size_t index ) const { -#if defined( _DEBUG ) - ASSERT_MESSAGE( index < size(), "array index out of bounds" ); -#endif - return m_data[index]; -} -value_type* data(){ - return m_data; -} -const value_type* data() const { - return m_data; -} -std::size_t size() const { - return m_size; -} -bool empty() const { - return m_size == 0; -} - -void resize( std::size_t count ){ - if ( count != size() ) { - Array temp( count ); - temp.swap( *this ); - } -} -void resize( std::size_t count, const value_type& value ){ - if ( count != size() ) { - Array temp( count, value ); - temp.swap( *this ); - } -} -}; - -namespace std -{ -/// \brief Swaps the values of \p self and \p other. -/// Overloads std::swap. -template -inline void swap( Array& self, Array& other ){ - self.swap( other ); -} -} - -#endif diff --git a/tools/urt/libs/container/cache.cpp b/tools/urt/libs/container/cache.cpp deleted file mode 100644 index ed3db63..0000000 --- a/tools/urt/libs/container/cache.cpp +++ /dev/null @@ -1,2 +0,0 @@ - -#include "cache.h" diff --git a/tools/urt/libs/container/cache.h b/tools/urt/libs/container/cache.h deleted file mode 100644 index 66fbd3c..0000000 --- a/tools/urt/libs/container/cache.h +++ /dev/null @@ -1,150 +0,0 @@ - -#if !defined( INCLUDED_CONTAINER_CACHE_H ) -#define INCLUDED_CONTAINER_CACHE_H - -#include -#include "container/hashtable.h" -#include "memory/allocator.h" - -template -class DefaultCreationPolicy -{ -public: -Type* construct( const Parameter& parameter ){ - return New().scalar( parameter ); -} -void destroy( Type* p ){ - Delete().scalar( p ); -} -}; - -template -class SharedValue -{ -typedef Type value_type; -typedef value_type* pointer; -typedef value_type& reference; - -std::size_t m_count; -pointer m_value; - -public: -SharedValue() - : m_count( 0 ), m_value( 0 ){ -} -~SharedValue(){ - ASSERT_MESSAGE( m_count == 0, "destroying a referenced object\n" ); -} -void set( pointer value ){ - m_value = value; -} -pointer get(){ - return m_value; -} -std::size_t increment(){ - return ++m_count; -} -std::size_t decrement(){ - ASSERT_MESSAGE( !empty(), "destroying a non-existent object\n" ); - return --m_count; -} -std::size_t count(){ - return m_count; -} -bool empty(){ - return m_count == 0; -} -reference operator*() const { - ASSERT_NOTNULL( m_value ); - return *m_value; -} -pointer operator->() const { - return &( operator*() ); -} -}; - - - -/// \brief Caches values that are uniquely identified by a key. -/// -/// - Automatically removes objects that are no longer referenced. -/// -/// \param Key Uniquely identifies each element. -/// \param Cached The type to be cached. Must define a constructor that accepts \c Key. -template, typename CreationPolicy = DefaultCreationPolicy > -class HashedCache : public CreationPolicy -{ -typedef SharedValue Element; -typedef HashTable map_type; - -map_type m_map; - -public: -explicit HashedCache( const CreationPolicy& creation = CreationPolicy() ) - : CreationPolicy( creation ), m_map( 256 ){ -} -~HashedCache(){ - ASSERT_MESSAGE( empty(), "HashedCache::~HashedCache: not empty" ); -} - -typedef typename map_type::iterator iterator; -typedef typename map_type::value_type value_type; - -iterator begin(){ - return m_map.begin(); -} -iterator end(){ - return m_map.end(); -} - -bool empty() const { - return m_map.empty(); -} - -iterator find( const Key& key ){ - return m_map.find( key ); -} - -void capture( iterator i ){ - ( *i ).value.increment(); -} -void release( iterator i ){ - if ( ( *i ).value.decrement() == 0 ) { - CreationPolicy::destroy( ( *i ).value.get() ); - m_map.erase( i ); - } -} - -#if 1 -Element& capture( const Key& key ){ - Element& elem = m_map[key]; - if ( elem.increment() == 1 ) { - elem.set( CreationPolicy::construct( key ) ); - } - return elem; -} -#else -value_type& capture( const Key& key ){ - iterator i = m_map.find( key ); - if ( i == m_map.end() ) { - Element element; - element.set( CreationPolicy::construct( key ) ); - i = m_map.insert( key, element ); - } - ( *i ).value.increment(); - return ( *i ); -} -#endif -void release( const Key& key ){ - iterator i = m_map.find( key ); - ASSERT_MESSAGE( i != m_map.end(), "releasing a non-existent object\n" ); - release( i ); -} - -void clear(){ - m_map.clear(); -} -}; - - -#endif diff --git a/tools/urt/libs/container/container.cpp b/tools/urt/libs/container/container.cpp deleted file mode 100644 index 1a241cc..0000000 --- a/tools/urt/libs/container/container.cpp +++ /dev/null @@ -1,2 +0,0 @@ - -#include "container.h" diff --git a/tools/urt/libs/container/container.h b/tools/urt/libs/container/container.h deleted file mode 100644 index 39239ad..0000000 --- a/tools/urt/libs/container/container.h +++ /dev/null @@ -1,272 +0,0 @@ - -#if !defined( INCLUDED_CONTAINER_CONTAINER_H ) -#define INCLUDED_CONTAINER_CONTAINER_H - -#include -#include - -#include "generic/static.h" - -/// \brief A single-value container, which can either be empty or full. -template -class Single -{ -Type* m_value; -public: -Single() : m_value( 0 ){ -} -bool empty(){ - return m_value == 0; -} -Type* insert( const Type& other ){ - m_value = new Type( other ); - return m_value; -} -void clear(){ - delete m_value; - m_value = 0; -} -Type& get(){ - //ASSERT_MESSAGE(!empty(), "Single: must be initialised before being accessed"); - return *m_value; -} -const Type& get() const { - //ASSERT_MESSAGE(!empty(), "Single: must be initialised before being accessed"); - return *m_value; -} -}; - - -/// \brief An adaptor to make std::list into a Unique Sequence - which cannot contain the same value more than once. -/// \param Value Uniquely identifies itself. Must provide a copy-constructor and an equality operator. -template -class UnsortedSet -{ -typedef typename std::list Values; -Values m_values; -public: -typedef typename Values::iterator iterator; -typedef typename Values::const_iterator const_iterator; -typedef typename Values::reverse_iterator reverse_iterator; -typedef typename Values::const_reverse_iterator const_reverse_iterator; - -iterator begin(){ - return m_values.begin(); -} -const_iterator begin() const { - return m_values.begin(); -} -iterator end(){ - return m_values.end(); -} -const_iterator end() const { - return m_values.end(); -} -reverse_iterator rbegin(){ - return m_values.rbegin(); -} -const_reverse_iterator rbegin() const { - return m_values.rbegin(); -} -reverse_iterator rend(){ - return m_values.rend(); -} -const_reverse_iterator rend() const { - return m_values.rend(); -} - -bool empty() const { - return m_values.empty(); -} -std::size_t size() const { - return m_values.size(); -} -void clear(){ - m_values.clear(); -} - -void swap( UnsortedSet& other ){ - std::swap( m_values, other.m_values ); -} -iterator insert( const Value& value ){ - ASSERT_MESSAGE( find( value ) == end(), "UnsortedSet::insert: already added" ); - m_values.push_back( value ); - return --end(); -} -void erase( const Value& value ){ - iterator i = find( value ); - ASSERT_MESSAGE( i != end(), "UnsortedSet::erase: not found" ); - m_values.erase( i ); -} -iterator find( const Value& value ){ - return std::find( begin(), end(), value ); -} -}; - -namespace std -{ -/// \brief Swaps the values of \p self and \p other. -/// Overloads std::swap. -template -inline void swap( UnsortedSet& self, UnsortedSet& other ){ - self.swap( other ); -} -} - -/// An adaptor to make std::list into a Unique Associative Sequence - which cannot contain the same value more than once. -/// Key: Uniquely identifies a value. Must provide a copy-constructor and an equality operator. -/// Value: Must provide a copy-constructor. -template -class UnsortedMap -{ -typedef typename std::list< std::pair > Values; -Values m_values; -public: -typedef typename Values::value_type value_type; -typedef typename Values::iterator iterator; -typedef typename Values::const_iterator const_iterator; - -iterator begin(){ - return m_values.begin(); -} -const_iterator begin() const { - return m_values.begin(); -} -iterator end(){ - return m_values.end(); -} -const_iterator end() const { - return m_values.end(); -} - -bool empty() const { - return m_values.empty(); -} -std::size_t size() const { - return m_values.size(); -} -void clear(){ - m_values.clear(); -} - -iterator insert( const value_type& value ){ - ASSERT_MESSAGE( find( value.first ) == end(), "UnsortedMap::insert: already added" ); - m_values.push_back( value ); - return --m_values.end(); -} -void erase( const Key& key ){ - iterator i = find( key ); - ASSERT_MESSAGE( i != end(), "UnsortedMap::erase: not found" ); - erase( i ); -} -void erase( iterator i ){ - m_values.erase( i ); -} -iterator find( const Key& key ){ - for ( iterator i = m_values.begin(); i != m_values.end(); ++i ) - { - if ( ( *i ).first == key ) { - return i; - } - } - return m_values.end(); -} -const_iterator find( const Key& key ) const { - for ( const_iterator i = m_values.begin(); i != m_values.end(); ++i ) - { - if ( ( *i ).first == key ) { - return i; - } - } - return m_values.end(); -} - -Value& operator[]( const Key& key ){ - iterator i = find( key ); - if ( i != end() ) { - return ( *i ).second; - } - - m_values.push_back( Values::value_type( key, Value() ) ); - return m_values.back().second; -} -}; - -/// An adaptor to assert when duplicate values are added, or non-existent values removed from a std::set. -template -class UniqueSet -{ -typedef std::set Values; -Values m_values; -public: -typedef typename Values::iterator iterator; -typedef typename Values::const_iterator const_iterator; -typedef typename Values::reverse_iterator reverse_iterator; -typedef typename Values::const_reverse_iterator const_reverse_iterator; - - -iterator begin(){ - return m_values.begin(); -} -const_iterator begin() const { - return m_values.begin(); -} -iterator end(){ - return m_values.end(); -} -const_iterator end() const { - return m_values.end(); -} -reverse_iterator rbegin(){ - return m_values.rbegin(); -} -const_reverse_iterator rbegin() const { - return m_values.rbegin(); -} -reverse_iterator rend(){ - return m_values.rend(); -} -const_reverse_iterator rend() const { - return m_values.rend(); -} - -bool empty() const { - return m_values.empty(); -} -std::size_t size() const { - return m_values.size(); -} -void clear(){ - m_values.clear(); -} - -void swap( UniqueSet& other ){ - std::swap( m_values, other.m_values ); -} -iterator insert( const Value& value ){ - std::pair result = m_values.insert( value ); - ASSERT_MESSAGE( result.second, "UniqueSet::insert: already added" ); - return result.first; -} -void erase( const Value& value ){ - iterator i = find( value ); - ASSERT_MESSAGE( i != end(), "UniqueSet::erase: not found" ); - m_values.erase( i ); -} -iterator find( const Value& value ){ - return std::find( begin(), end(), value ); -} -}; - -namespace std -{ -/// \brief Swaps the values of \p self and \p other. -/// Overloads std::swap. -template -inline void swap( UniqueSet& self, UniqueSet& other ){ - self.swap( other ); -} -} - - -#endif diff --git a/tools/urt/libs/container/hashfunc.cpp b/tools/urt/libs/container/hashfunc.cpp deleted file mode 100644 index a141ee4..0000000 --- a/tools/urt/libs/container/hashfunc.cpp +++ /dev/null @@ -1,2 +0,0 @@ - -#include "hashfunc.h" diff --git a/tools/urt/libs/container/hashfunc.h b/tools/urt/libs/container/hashfunc.h deleted file mode 100644 index f174330..0000000 --- a/tools/urt/libs/container/hashfunc.h +++ /dev/null @@ -1,382 +0,0 @@ - -#if !defined( INCLUDED_CONTAINER_HASHFUNC_H ) -#define INCLUDED_CONTAINER_HASHFUNC_H - -/* - -------------------------------------------------------------------- - lookup2.c, by Bob Jenkins, December 1996, Public Domain. - hash(), hash2(), hash3, and mix() are externally useful functions. - Routines to test the hash are included if SELF_TEST is defined. - You can use this free for any purpose. It has no warranty. - -------------------------------------------------------------------- - */ - -#include -#include "string/string.h" -#include "container/array.h" -typedef unsigned long int ub4; /* unsigned 4-byte quantities */ -typedef unsigned char ub1; - -inline ub1 ub1_as_ub1_nocase( ub1 byte ){ - return std::tolower( byte ); -} - -inline ub4 ub1x4_as_ub4_nocase( const ub1 bytes[4] ){ - ub4 result; - reinterpret_cast( &result )[0] = ub1_as_ub1_nocase( bytes[0] ); - reinterpret_cast( &result )[1] = ub1_as_ub1_nocase( bytes[1] ); - reinterpret_cast( &result )[2] = ub1_as_ub1_nocase( bytes[2] ); - reinterpret_cast( &result )[3] = ub1_as_ub1_nocase( bytes[3] ); - return result; -} - -class ub1_default_traits -{ -public: -static ub1 as_ub1( ub1 byte ){ - return byte; -} -}; - -class ub1_nocase_traits -{ -public: -static ub1 as_ub1( ub1 byte ){ - return ub1_as_ub1_nocase( byte ); -} -}; - -class ub1x4_default_traits -{ -public: -static ub4 as_ub4( const ub1 bytes[4] ){ - return *reinterpret_cast( bytes ); -} -}; - -class ub1x4_nocase_traits -{ -public: -static ub4 as_ub4( const ub1 bytes[4] ){ - return ub1x4_as_ub4_nocase( bytes ); -} -}; - -class ub4_default_traits -{ -public: -static ub4 as_ub4( ub4 i ){ - return i; -} -}; - -class ub4_nocase_traits -{ -public: -static ub4 as_ub4( ub4 i ){ - return ub1x4_as_ub4_nocase( reinterpret_cast( &i ) ); -} -}; - -#define hashsize( n ) ( (ub4)1 << ( n ) ) -#define hashmask( n ) ( hashsize( n ) - 1 ) - -/* - -------------------------------------------------------------------- - mix -- mix 3 32-bit values reversibly. - For every delta with one or two bit set, and the deltas of all three - high bits or all three low bits, whether the original value of a,b,c - is almost all zero or is uniformly distributed, - * If mix() is run forward or backward, at least 32 bits in a,b,c - have at least 1/4 probability of changing. - * If mix() is run forward, every bit of c will change between 1/3 and - 2/3 of the time. (Well, 22/100 and 78/100 for some 2-bit deltas.) - mix() was built out of 36 single-cycle latency instructions in a - structure that could supported 2x parallelism, like so: - a -= b; - a -= c; x = (c>>13); - b -= c; a ^= x; - b -= a; x = (a<<8); - c -= a; b ^= x; - c -= b; x = (b>>13); - ... - Unfortunately, superscalar Pentiums and Sparcs can't take advantage - of that parallelism. They've also turned some of those single-cycle - latency instructions into multi-cycle latency instructions. Still, - this is the fastest good hash I could find. There were about 2^^68 - to choose from. I only looked at a billion or so. - -------------------------------------------------------------------- - */ -#define mix( a,b,c ) \ - { \ - a -= b; a -= c; a ^= ( c >> 13 ); \ - b -= c; b -= a; b ^= ( a << 8 ); \ - c -= a; c -= b; c ^= ( b >> 13 ); \ - a -= b; a -= c; a ^= ( c >> 12 ); \ - b -= c; b -= a; b ^= ( a << 16 ); \ - c -= a; c -= b; c ^= ( b >> 5 ); \ - a -= b; a -= c; a ^= ( c >> 3 ); \ - b -= c; b -= a; b ^= ( a << 10 ); \ - c -= a; c -= b; c ^= ( b >> 15 ); \ - } - -/* same, but slower, works on systems that might have 8 byte ub4's */ -#define mix2( a,b,c ) \ - { \ - a -= b; a -= c; a ^= ( c >> 13 ); \ - b -= c; b -= a; b ^= ( a << 8 ); \ - c -= a; c -= b; c ^= ( ( b & 0xffffffff ) >> 13 ); \ - a -= b; a -= c; a ^= ( ( c & 0xffffffff ) >> 12 ); \ - b -= c; b -= a; b = ( b ^ ( a << 16 ) ) & 0xffffffff; \ - c -= a; c -= b; c = ( c ^ ( b >> 5 ) ) & 0xffffffff; \ - a -= b; a -= c; a = ( a ^ ( c >> 3 ) ) & 0xffffffff; \ - b -= c; b -= a; b = ( b ^ ( a << 10 ) ) & 0xffffffff; \ - c -= a; c -= b; c = ( c ^ ( b >> 15 ) ) & 0xffffffff; \ - } - -/* - -------------------------------------------------------------------- - hash() -- hash a variable-length key into a 32-bit value - k : the key (the unaligned variable-length array of bytes) - len : the length of the key, counting by bytes - level : can be any 4-byte value - Returns a 32-bit value. Every bit of the key affects every bit of - the return value. Every 1-bit and 2-bit delta achieves avalanche. - About 36+6len instructions. - - The best hash table sizes are powers of 2. There is no need to do - mod a prime (mod is sooo slow!). If you need less than 32 bits, - use a bitmask. For example, if you need only 10 bits, do - h = (h & hashmask(10)); - In which case, the hash table should have hashsize(10) elements. - - If you are hashing n strings (ub1 **)k, do it like this: - for (i=0, h=0; i -inline ub4 hash( - const ub1 *k, /* the key */ - ub4 length, /* the length of the key */ - ub4 initval, /* the previous hash, or an arbitrary value */ - const UB1Traits& ub1traits, - const UB4x1Traits& ub4x1traits - ){ - register ub4 a,b,c,len; - - /* Set up the internal state */ - len = length; - a = b = 0x9e3779b9; /* the golden ratio; an arbitrary value */ - c = initval; /* the previous hash value */ - - /*---------------------------------------- handle most of the key */ - while ( len >= 12 ) - { - a += ( k[0] + ( ( ub4 ) UB1Traits::as_ub1( k[1] ) << 8 ) + ( ( ub4 ) UB1Traits::as_ub1( k[2] ) << 16 ) + ( ( ub4 ) UB1Traits::as_ub1( k[3] ) << 24 ) ); - b += ( k[4] + ( ( ub4 ) UB1Traits::as_ub1( k[5] ) << 8 ) + ( ( ub4 ) UB1Traits::as_ub1( k[6] ) << 16 ) + ( ( ub4 ) UB1Traits::as_ub1( k[7] ) << 24 ) ); - c += ( k[8] + ( ( ub4 ) UB1Traits::as_ub1( k[9] ) << 8 ) + ( ( ub4 ) UB1Traits::as_ub1( k[10] ) << 16 ) + ( ( ub4 ) UB1Traits::as_ub1( k[11] ) << 24 ) ); - mix( a,b,c ); - k += 12; len -= 12; - } - - /*------------------------------------- handle the last 11 bytes */ - c += length; - switch ( len ) /* all the case statements fall through */ - { - case 11: c += ( ( ub4 ) UB1Traits::as_ub1( k[10] ) << 24 ); - case 10: c += ( ( ub4 ) UB1Traits::as_ub1( k[9] ) << 16 ); - case 9: c += ( ( ub4 ) UB1Traits::as_ub1( k[8] ) << 8 ); - /* the first byte of c is reserved for the length */ - case 8: b += ( ( ub4 ) UB1Traits::as_ub1( k[7] ) << 24 ); - case 7: b += ( ( ub4 ) UB1Traits::as_ub1( k[6] ) << 16 ); - case 6: b += ( ( ub4 ) UB1Traits::as_ub1( k[5] ) << 8 ); - case 5: b += UB1Traits::as_ub1( k[4] ); - case 4: a += ( ( ub4 ) UB1Traits::as_ub1( k[3] ) << 24 ); - case 3: a += ( ( ub4 ) UB1Traits::as_ub1( k[2] ) << 16 ); - case 2: a += ( ( ub4 ) UB1Traits::as_ub1( k[1] ) << 8 ); - case 1: a += UB1Traits::as_ub1( k[0] ); - /* case 0: nothing left to add */ - } - mix( a,b,c ); - /*-------------------------------------------- report the result */ - return c; -} - -/* - -------------------------------------------------------------------- - This works on all machines. hash2() is identical to hash() on - little-endian machines, except that the length has to be measured - in ub4s instead of bytes. It is much faster than hash(). It - requires - -- that the key be an array of ub4's, and - -- that all your machines have the same endianness, and - -- that the length be the number of ub4's in the key - -------------------------------------------------------------------- - */ -template -inline ub4 hash2( - const ub4 *k, /* the key */ - ub4 length, /* the length of the key, in ub4s */ - ub4 initval, /* the previous hash, or an arbitrary value */ - const UB4Traits& ub4traits - ){ - register ub4 a,b,c,len; - - /* Set up the internal state */ - len = length; - a = b = 0x9e3779b9; /* the golden ratio; an arbitrary value */ - c = initval; /* the previous hash value */ - - /*---------------------------------------- handle most of the key */ - while ( len >= 3 ) - { - a += UB4Traits::as_ub4( k[0] ); - b += UB4Traits::as_ub4( k[1] ); - c += UB4Traits::as_ub4( k[2] ); - mix( a,b,c ); - k += 3; len -= 3; - } - - /*-------------------------------------- handle the last 2 ub4's */ - c += length; - switch ( len ) /* all the case statements fall through */ - { - /* c is reserved for the length */ - case 2: b += UB4Traits::as_ub4( k[1] ); - case 1: a += UB4Traits::as_ub4( k[0] ); - /* case 0: nothing left to add */ - } - mix( a,b,c ); - /*-------------------------------------------- report the result */ - return c; -} - -typedef ub4 hash_t; - -inline hash_t hash_ub1( const ub1* key, std::size_t len, hash_t previous = 0 ){ - return hash( key, ub4( len ), previous, ub1_default_traits(), ub1x4_default_traits() ); -} - -inline hash_t hash_ub1_nocase( const ub1* key, std::size_t len, hash_t previous = 0 ){ - return hash( key, ub4( len ), previous, ub1_nocase_traits(), ub1x4_nocase_traits() ); -} - -template -inline hash_t hash_ub4( const ub4* key, std::size_t len, const UB4Traits& traits, hash_t previous = 0 ){ - return hash2( key,ub4( len ), previous, traits ); -} - -inline ub4 hash_combine( ub4 left, ub4 right ){ - return hash_ub1( reinterpret_cast( &left ), 4, right ); -} - -template -inline hash_t pod_hash( const POD& pod ){ - return hash_ub1( reinterpret_cast( &pod ), sizeof( POD ) ); -} - -inline hash_t string_hash( const char* string, hash_t previous = 0 ){ - return hash_ub1( reinterpret_cast( string ), string_length( string ), previous ); -} - -inline hash_t string_hash_nocase( const char* string, hash_t previous = 0 ){ - return hash_ub1_nocase( reinterpret_cast( string ), string_length( string ), previous ); -} - -struct HashString -{ - typedef hash_t hash_type; - hash_type operator()( const CopiedString& string ) const { - return string_hash( string.c_str() ); - } -}; - -struct HashStringNoCase -{ - typedef hash_t hash_type; - hash_type operator()( const CopiedString& string ) const { - return string_hash_nocase( string.c_str() ); - } -}; - -/// \brief Length of a string in ub4. -/// "wibble" (6) gives 2, -/// "and" (3) gives 1, -/// "bleh" (4) gives 2 -inline std::size_t string_length_ub4( const char* string ){ - return ( ( string_length( string ) >> 2 ) + 1 ) << 2; -} - -/// \brief Hashable key type that stores a string as an array of ub4 - making hashing faster. -/// Also caches the 32-bit result of the hash to speed up comparison of keys. -template -class HashKey -{ -Array m_key; -hash_t m_hash; - -void copy( const HashKey& other ){ - std::copy( other.m_key.begin(), other.m_key.end(), m_key.begin() ); - m_hash = other.m_hash; -} -void copy( const char* string ){ - strncpy( reinterpret_cast( m_key.data() ), string, m_key.size() ); - for ( Array::iterator i = m_key.begin(); i != m_key.end(); ++i ) - { - *i = UB4Traits::as_ub4( *i ); - } - m_hash = hash_ub4( m_key.data(), m_key.size(), ub4_default_traits() ); -} -bool equal( const HashKey& other ) const { - return m_hash == other.m_hash && m_key.size() == other.m_key.size() - && std::equal( m_key.begin(), m_key.end(), other.m_key.begin() ); -} - -public: -HashKey( const HashKey& other ) : m_key( other.m_key.size() ){ - copy( other ); -} -HashKey( const char* string ) : m_key( string_length_ub4( string ) ){ - copy( string ); -} -HashKey& operator=( const char* string ){ - m_key.resize( string_length_ub4( string ) ); - copy( string ); - return *this; -} -bool operator==( const HashKey& other ) const { - return equal( other ); -} -bool operator!=( const HashKey& other ) const { - return !equal( other ); -} -hash_t hash() const { - return m_hash; -} -#if 0 -const char* c_str() const { - return reinterpret_cast( m_key.data() ); -} -#endif -}; - -/// \brief Hash function to use with HashKey. -struct HashKeyHasher -{ - typedef hash_t hash_type; - hash_type operator()( const HashKey& key ) const { - return key.hash(); - } -}; - - - -#endif diff --git a/tools/urt/libs/container/hashtable.cpp b/tools/urt/libs/container/hashtable.cpp deleted file mode 100644 index cb7ba70..0000000 --- a/tools/urt/libs/container/hashtable.cpp +++ /dev/null @@ -1,42 +0,0 @@ - -#include "hashtable.h" - -#if defined( _DEBUG ) || defined( DOXYGEN ) - -#include "hashfunc.h" - -namespace ExampleHashTable -{ -void testStuff(){ - // HashTable example - typedef HashTable MyHashTable; - MyHashTable hashtable; - hashtable["bleh"] = 5; - hashtable.insert( "blah", 17 ); - hashtable["foo"] = 99; - hashtable.insert( "bar", 23 ); - - int bleh = ( *hashtable.find( "bleh" ) ).value; // 5 - int blah = hashtable["blah"]; // 17 - hashtable.erase( "foo" ); - MyHashTable::iterator barIter = hashtable.find( "bar" ); - hashtable.erase( barIter ); - - for ( MyHashTable::iterator i = hashtable.begin(); i != hashtable.end(); ++i ) - { - if ( ( *i ).key != "bleh" ) { - ++hashtable["count"]; // insertion does not invalidate iterators - } - } - // end example -} - -struct Always -{ - Always(){ - testStuff(); - } -} always; -} - -#endif diff --git a/tools/urt/libs/container/hashtable.h b/tools/urt/libs/container/hashtable.h deleted file mode 100644 index 10d9be8..0000000 --- a/tools/urt/libs/container/hashtable.h +++ /dev/null @@ -1,391 +0,0 @@ - -#if !defined( INCLUDED_CONTAINER_HASHTABLE_H ) -#define INCLUDED_CONTAINER_HASHTABLE_H - -#include -#include -#include -#include "debugging/debugging.h" - - -namespace HashTableDetail -{ -inline std::size_t next_power_of_two( std::size_t size ){ - std::size_t result = 1; - while ( result < size ) - { - result <<= 1; - } - return result; -} - -struct BucketNodeBase -{ - BucketNodeBase* next; - BucketNodeBase* prev; -}; - -inline void list_initialise( BucketNodeBase& self ){ - self.next = self.prev = &self; -} - -inline void list_swap( BucketNodeBase& self, BucketNodeBase& other ){ - BucketNodeBase tmp( self ); - if ( other.next == &other ) { - list_initialise( self ); - } - else - { - self = other; - self.next->prev = self.prev->next = &self; - } - if ( tmp.next == &self ) { - list_initialise( other ); - } - else - { - other = tmp; - other.next->prev = other.prev->next = &other; - } -} - -inline void node_link( BucketNodeBase* node, BucketNodeBase* next ){ - node->next = next; - node->prev = next->prev; - next->prev = node; - node->prev->next = node; -} -inline void node_unlink( BucketNodeBase* node ){ - node->prev->next = node->next; - node->next->prev = node->prev; -} - -template -struct KeyValue -{ - const Key key; - Value value; - - KeyValue( const Key& key_, const Value& value_ ) - : key( key_ ), value( value_ ){ - } -}; - -template -struct BucketNode : public BucketNodeBase -{ - Hash m_hash; - KeyValue m_value; - - BucketNode( Hash hash, const Key& key, const Value& value ) - : m_hash( hash ), m_value( key, value ){ - } - BucketNode* getNext(){ - return static_cast( next ); - } - BucketNode* getPrev(){ - return static_cast( prev ); - } -}; - -template -class BucketIterator -{ -typedef BucketNode Node; -Node* m_node; - -void increment(){ - m_node = m_node->getNext(); -} - -public: -typedef std::forward_iterator_tag iterator_category; -typedef std::ptrdiff_t difference_type; -typedef difference_type distance_type; -typedef KeyValue value_type; -typedef value_type* pointer; -typedef value_type& reference; - -BucketIterator( Node* node ) : m_node( node ){ -} - -Node* node(){ - return m_node; -} - -bool operator==( const BucketIterator& other ) const { - return m_node == other.m_node; -} -bool operator!=( const BucketIterator& other ) const { - return !operator==( other ); -} -BucketIterator& operator++(){ - increment(); - return *this; -} -BucketIterator operator++( int ){ - BucketIterator tmp = *this; - increment(); - return tmp; -} -value_type& operator*(){ - return m_node->m_value; -} -value_type* operator->(){ - return &( operator*() ); -} -}; -} - - -/// A hash-table container which maps keys to values. -/// -/// - Inserting or removing elements does not invalidate iterators. -/// - Inserting or retrieving an element for a given key takes O(1) time on average. -/// - Elements are stored in no particular order. -/// -/// \param Key Uniquely identifies a value. Must provide a copy-constructor. -/// \param Value The value to be stored . Must provide a default-constructor and a copy-constructor. -/// \param Hasher Must provide 'std::size_t operator()(const Key&) const' which always returns the same result if the same argument is given. -/// \param KeyEqual Must provide 'bool operator==(const Key&, const Key&) const' which returns true only if both arguments are equal. -/// -/// \dontinclude container/hashtable.cpp -/// \skipline HashTable example -/// \until end example -template > -class HashTable : private KeyEqual, private Hasher -{ -typedef typename Hasher::hash_type hash_type; -typedef HashTableDetail::KeyValue KeyValue; -typedef HashTableDetail::BucketNode BucketNode; - -inline BucketNode* node_create( hash_type hash, const Key& key, const Value& value ){ - return new BucketNode( hash, key, value ); -} -inline void node_destroy( BucketNode* node ){ - delete node; -} - -typedef BucketNode* Bucket; - -static Bucket* buckets_new( std::size_t count ){ - Bucket* buckets = new Bucket[count]; - std::uninitialized_fill( buckets, buckets + count, Bucket( 0 ) ); - return buckets; -} -static void buckets_delete( Bucket* buckets ){ - delete[] buckets; -} - -std::size_t m_bucketCount; -Bucket* m_buckets; -std::size_t m_size; -HashTableDetail::BucketNodeBase m_list; - -BucketNode* getFirst(){ - return static_cast( m_list.next ); -} -BucketNode* getLast(){ - return static_cast( &m_list ); -} - -public: - -typedef KeyValue value_type; -typedef HashTableDetail::BucketIterator iterator; - -private: - -void initialise(){ - list_initialise( m_list ); -} -hash_type hashKey( const Key& key ){ - return Hasher::operator()( key ); -} - -std::size_t getBucketId( hash_type hash ) const { - return hash & ( m_bucketCount - 1 ); -} -Bucket& getBucket( hash_type hash ){ - return m_buckets[getBucketId( hash )]; -} -BucketNode* bucket_find( Bucket bucket, hash_type hash, const Key& key ){ - std::size_t bucketId = getBucketId( hash ); - for ( iterator i( bucket ); i != end(); ++i ) - { - hash_type nodeHash = i.node()->m_hash; - - if ( getBucketId( nodeHash ) != bucketId ) { - return 0; - } - - if ( nodeHash == hash && KeyEqual::operator()( ( *i ).key, key ) ) { - return i.node(); - } - } - return 0; -} -BucketNode* bucket_insert( Bucket& bucket, BucketNode* node ){ - // link node into list - node_link( node, bucket_next( bucket ) ); - bucket = node; - return node; -} -BucketNode* bucket_next( Bucket& bucket ){ - Bucket* end = m_buckets + m_bucketCount; - for ( Bucket* i = &bucket; i != end; ++i ) - { - if ( *i != 0 ) { - return *i; - } - } - return getLast(); -} - -void buckets_resize( std::size_t count ){ - BucketNode* first = getFirst(); - BucketNode* last = getLast(); - - buckets_delete( m_buckets ); - - m_bucketCount = count; - - m_buckets = buckets_new( m_bucketCount ); - initialise(); - - for ( BucketNode* i = first; i != last; ) - { - BucketNode* node = i; - i = i->getNext(); - bucket_insert( getBucket( ( *node ).m_hash ), node ); - } -} -void size_increment(){ - if ( m_size == m_bucketCount ) { - buckets_resize( m_bucketCount == 0 ? 8 : m_bucketCount << 1 ); - } - ++m_size; -} -void size_decrement(){ - --m_size; -} - -HashTable( const HashTable& other ); -HashTable& operator=( const HashTable& other ); -public: -HashTable() : m_bucketCount( 0 ), m_buckets( 0 ), m_size( 0 ){ - initialise(); -} -HashTable( std::size_t bucketCount ) : m_bucketCount( HashTableDetail::next_power_of_two( bucketCount ) ), m_buckets( buckets_new( m_bucketCount ) ), m_size( 0 ){ - initialise(); -} -~HashTable(){ - for ( BucketNode* i = getFirst(); i != getLast(); ) - { - BucketNode* node = i; - i = i->getNext(); - node_destroy( node ); - } - buckets_delete( m_buckets ); -} - -iterator begin(){ - return iterator( getFirst() ); -} -iterator end(){ - return iterator( getLast() ); -} - -bool empty() const { - return m_size == 0; -} -std::size_t size() const { - return m_size; -} - -/// \brief Returns an iterator pointing to the value associated with \p key if it is contained by the hash-table, else \c end(). -iterator find( const Key& key ){ - hash_type hash = hashKey( key ); - if ( m_bucketCount != 0 ) { - Bucket bucket = getBucket( hash ); - if ( bucket != 0 ) { - BucketNode* node = bucket_find( bucket, hash, key ); - if ( node != 0 ) { - return iterator( node ); - } - } - } - - return end(); -} -/// \brief Adds \p value to the hash-table associated with \p key if it does not exist, or replaces the current value associated with \p key. -iterator insert( const Key& key, const Value& value ){ - hash_type hash = hashKey( key ); - if ( m_bucketCount != 0 ) { - Bucket& bucket = getBucket( hash ); - if ( bucket != 0 ) { - BucketNode* node = bucket_find( bucket, hash, key ); - if ( node != 0 ) { - node->m_value.value = value; - return iterator( node ); - } - } - } - - size_increment(); - return iterator( bucket_insert( getBucket( hash ), node_create( hash, key, value ) ) ); -} - -/// \brief Removes the value pointed to by \p i from the hash-table. -/// -/// \p i must be a deferenceable iterator into the hash-table. -void erase( iterator i ){ - Bucket& bucket = getBucket( i.node()->m_hash ); - BucketNode* node = i.node(); - - // if this was the last node in the bucket - if ( bucket == node ) { - bucket = ( node->getNext() == getLast() || &getBucket( node->getNext()->m_hash ) != &bucket ) ? 0 : node->getNext(); - } - - node_unlink( node ); - ASSERT_MESSAGE( node != 0, "tried to erase a non-existent key/value" ); - node_destroy( node ); - - size_decrement(); -} - -/// \brief Returns the value identified by \p key if it is contained by the hash-table, else inserts and returns a new default-constructed value associated with \p key. -Value& operator[]( const Key& key ){ - hash_type hash = hashKey( key ); - if ( m_bucketCount != 0 ) { - Bucket& bucket = getBucket( hash ); - if ( bucket != 0 ) { - BucketNode* node = bucket_find( bucket, hash, key ); - if ( node != 0 ) { - return node->m_value.value; - } - } - } - size_increment(); - return bucket_insert( getBucket( hash ), node_create( hash, key, Value() ) )->m_value.value; -} -/// \brief Removes the value associated with \p key from the hash-table. -void erase( const Key& key ){ - erase( find( key ) ); -} -/// \brief Swaps the contents of the hash-table with \p other. -void swap( HashTable& other ){ - std::swap( m_buckets, other.m_buckets ); - std::swap( m_bucketCount, other.m_bucketCount ); - std::swap( m_size, other.m_size ); - HashTableDetail::list_swap( m_list, other.m_list ); -} -/// \brief Removes all values from the hash-table. -void clear(){ - HashTable tmp; - tmp.swap( *this ); -} -}; - -#endif diff --git a/tools/urt/libs/container/stack.cpp b/tools/urt/libs/container/stack.cpp deleted file mode 100644 index 9a9030f..0000000 --- a/tools/urt/libs/container/stack.cpp +++ /dev/null @@ -1,2 +0,0 @@ - -#include "stack.h" diff --git a/tools/urt/libs/container/stack.h b/tools/urt/libs/container/stack.h deleted file mode 100644 index 5fbd3aa..0000000 --- a/tools/urt/libs/container/stack.h +++ /dev/null @@ -1,191 +0,0 @@ - -#if !defined( INCLUDED_CONTAINER_STACK_H ) -#define INCLUDED_CONTAINER_STACK_H - -#include "memory/allocator.h" -#include - -/// \brief A stack whose storage capacity is variable at run-time. Similar to std::vector. -/// -/// - Pushing or popping elements is a constant-time operation (on average). -/// - The storage capacity of the stack will grow when a new element is added beyond the current capacity. Iterators are invalidated when the storage capacity grows. -/// - DefaultConstructible, Copyable, Assignable. -/// - Compatible with the containers and algorithms in the Standard Template Library (STL) - http://www.sgi.com/tech/stl/ -/// -/// \param Type: The type to be stored in the stack. Must provide a copy-constructor. -template -class Stack : public DefaultAllocator -{ -typedef DefaultAllocator Allocator; - -enum -{ - DEFAULT_CAPACITY = 4, -}; - -typedef Type* pointer; -typedef const Type* const_pointer; - -public: -typedef const_pointer const_iterator; -private: - -pointer m_data; -pointer m_end; -std::size_t m_capacity; - - -void insert( const Type& value ){ - Allocator::construct( m_end++, value ); -} -void insert_overflow( const Type& value ){ - const std::size_t new_capacity = ( m_capacity ) ? m_capacity + m_capacity : std::size_t( DEFAULT_CAPACITY ); - const pointer new_data = Allocator::allocate( new_capacity ); - const pointer new_end = std::copy( m_data, m_end, new_data ); - - destroy(); - Allocator::deallocate( m_data, m_capacity ); - - m_capacity = new_capacity; - m_data = new_data; - m_end = new_end; - insert( value ); -} -void destroy(){ - for ( pointer p = m_data; p != m_end; ++p ) - { - Allocator::destroy( p ); - } -} -void construct( const Stack& other ){ - pointer p = m_data; - for ( const_iterator i = other.begin(); i != other.end(); ++i ) - { - Allocator::construct( p++, *i ); - } -} - -public: - -Stack() : - m_data( 0 ), - m_end( 0 ), - m_capacity( 0 ){ -} -Stack( const Type& value ) : - m_data( 0 ), - m_end( 0 ), - m_capacity( 0 ){ - push( value ); -} -Stack( const Stack& other ) : - DefaultAllocator( other ){ - m_capacity = other.m_capacity; - m_data = Allocator::allocate( m_capacity ); - construct( other ); - m_end = m_data + other.size(); -} -~Stack(){ - destroy(); - Allocator::deallocate( m_data, m_capacity ); -} - -const_iterator begin() const { - return m_data; -} -const_iterator end() const { - return m_end; -} - -bool empty() const { - return end() == begin(); -} -void clear(){ - destroy(); - m_end = m_data; -} - -std::size_t size() const { - return m_end - m_data; -} -Type operator[]( const std::size_t i ) const { - return m_data[i]; -} -/// \brief Pushes \p value onto the stack at the top element. If reserved storage is insufficient for the new element, this will invalidate all iterators. -void push( const Type& value ){ - if ( size() == m_capacity ) { - insert_overflow( value ); - } - else - { - insert( value ); - } -} -/// \brief Removes the top element of the stack. -void pop(){ - Allocator::destroy( --m_end ); -} -/// \brief Returns the top element of the mutable stack. -Type& top(){ - return *( m_end - 1 ); -} -/// \brief Returns the top element of the non-mutable stack. -const Type& top() const { - return *( m_end - 1 ); -} -/// \brief Returns the element below the top element of the mutable stack. -Type& parent(){ - return *( m_end - 2 ); -} -/// \brief Returns the element below the top element of the non-mutable stack. -const Type& parent() const { - return *( m_end - 2 ); -} -/// \brief Swaps the values of this stack and \p other. -void swap( Stack& other ){ - std::swap( m_data, other.m_data ); - std::swap( m_end, other.m_end ); - std::swap( m_capacity, other.m_capacity ); -} -#if 1 // use copy-swap technique -Stack& operator=( const Stack& other ){ - Stack temp( other ); - temp.swap( *this ); - return *this; -} -#else // avoids memory allocation if capacity is already sufficient. -Stack& operator=( const Stack& other ){ - if ( &other != this ) { - destroy(); - - if ( other.size() > m_capacity ) { - Allocator::deallocate( m_data, m_capacity ); - m_capacity = other.m_capacity; - m_data = Allocator::allocate( m_capacity ); - } - m_end = m_data + other.size(); - - construct( other ); - } - return *this; -} -#endif -}; - -/// \brief Returns true if \p self is lexicographically less than \p other. -template -inline bool operator<( const Stack& self, const Stack& other ){ - return std::lexicographical_compare( self.begin(), self.end(), other.begin(), other.end() ); -} - -namespace std -{ -/// \brief Swaps the values of \p self and \p other. -/// Overloads std::swap(). -template -inline void swap( Stack& self, Stack& other ){ - self.swap( other ); -} -} - -#endif diff --git a/tools/urt/libs/convert.cpp b/tools/urt/libs/convert.cpp deleted file mode 100644 index b58d7cb..0000000 --- a/tools/urt/libs/convert.cpp +++ /dev/null @@ -1,2 +0,0 @@ - -#include "convert.h" diff --git a/tools/urt/libs/convert.h b/tools/urt/libs/convert.h deleted file mode 100644 index 6387c25..0000000 --- a/tools/urt/libs/convert.h +++ /dev/null @@ -1,247 +0,0 @@ - -#if !defined( INCLUDED_CONVERT_H ) -#define INCLUDED_CONVERT_H - -/// \file -/// \brief Character encoding conversion. - -#include "debugging/debugging.h" -#include -#include -#include - -#include "character.h" - -/// \brief Returns the number of bytes required to represent \p character in UTF-8 encoding. -inline std::size_t utf8_character_length( const char* character ){ - if ( ( *character & 0xE0 ) == 0xC0 ) { // 110xxxxx - return 2; - } - else if ( ( *character & 0xF0 ) == 0xE0 ) { // 1110xxxx - return 3; - } - else if ( ( *character & 0xF8 ) == 0xF0 ) { // 11110xxx - return 4; - } - else if ( ( *character & 0xFC ) == 0xF8 ) { // 111110xx - return 5; - } - else if ( ( *character & 0xFE ) == 0xFC ) { // 1111110x - return 6; - } - ERROR_MESSAGE( "" ); - return 0; -} - -struct UTF8Character -{ - const char* buffer; - std::size_t length; - UTF8Character() : buffer( 0 ), length( 0 ){ - } - UTF8Character( const char* bytes ) : buffer( bytes ), length( utf8_character_length( bytes ) ){ - } -}; - -inline bool operator<( const UTF8Character& self, const UTF8Character& other ){ - return std::lexicographical_compare( self.buffer, self.buffer + self.length, other.buffer, other.buffer + other.length ); -} - -/// \brief Writes \p c to \p ostream in Hex form. Useful for debugging. -template -inline TextOutputStreamType& ostream_write( TextOutputStreamType& ostream, const UTF8Character& c ){ - for ( const char* p = c.buffer; p != c.buffer + c.length; ++p ) - { - ostream << HexChar( *p ); - } - return ostream; -} - - - -/// \brief The character-set encoding for the current C locale. -/// -/// Obtain the global instance with globalCharacterSet(). -class CharacterSet -{ -const char* m_charSet; -public: -CharacterSet(){ - if ( g_get_charset( &m_charSet ) != FALSE ) { - m_charSet = 0; - } -} -bool isUTF8() const { - return m_charSet == 0; -} -const char* get() const { - return m_charSet; -} -}; - -typedef LazyStatic GlobalCharacterSet; - -/// \brief Returns the global instance of CharacterSet. -inline CharacterSet& globalCharacterSet(){ - return GlobalCharacterSet::instance(); -} - - -class UTF8CharacterToExtendedASCII -{ -public: -UTF8Character m_utf8; -char m_c; -UTF8CharacterToExtendedASCII() : m_c( '\0' ){ -} -UTF8CharacterToExtendedASCII( const UTF8Character& utf8, char c ) : m_utf8( utf8 ), m_c( c ){ -} -}; - -inline bool operator<( const UTF8CharacterToExtendedASCII& self, const UTF8CharacterToExtendedASCII& other ){ - return self.m_utf8 < other.m_utf8; -} - -inline std::size_t extended_ascii_to_index( char c ){ - return static_cast( c & 0x7F ); -} - -inline char extended_ascii_for_index( std::size_t i ){ - return static_cast( i | 0x80 ); -} - -/// \brief The active extended-ascii character set encoding. -/// Performs UTF-8 encoding and decoding of extended-ascii characters. -/// -/// Obtain the global instance with globalExtendedASCIICharacterSet(). -class ExtendedASCIICharacterSet -{ -typedef char UTF8CharBuffer[6]; -UTF8CharBuffer m_converted[128]; -UTF8Character m_decodeMap[128]; -UTF8CharacterToExtendedASCII m_encodeMap[128]; -public: -ExtendedASCIICharacterSet(){ - if ( !globalCharacterSet().isUTF8() ) { - GIConv descriptor = g_iconv_open( "UTF-8", globalCharacterSet().get() ); - for ( std::size_t i = 1; i < 128; ++i ) - { - char c = extended_ascii_for_index( i ); - char* inbuf = &c; - std::size_t inbytesleft = 1; - char* outbuf = m_converted[i]; - std::size_t outbytesleft = 6; - if ( g_iconv( descriptor, &inbuf, &inbytesleft, &outbuf, &outbytesleft ) != (size_t)( -1 ) ) { - UTF8Character utf8( m_converted[i] ); - m_decodeMap[i] = utf8; - m_encodeMap[i] = UTF8CharacterToExtendedASCII( utf8, c ); - } - } - g_iconv_close( descriptor ); - std::sort( m_encodeMap, m_encodeMap + 128 ); - } -} -/// \brief Prints the (up to) 128 characters in the current extended-ascii character set. -/// Useful for debugging. -void print() const { - globalOutputStream() << "UTF-8 conversion required from charset: " << globalCharacterSet().get() << "\n"; - for ( std::size_t i = 1; i < 128; ++i ) - { - if ( m_decodeMap[i].buffer != 0 ) { - globalOutputStream() << extended_ascii_for_index( i ) << " = " << m_decodeMap[i] << "\n"; - } - } -} -/// \brief Returns \p c decoded from extended-ascii to UTF-8. -/// \p c must be an extended-ascii character. -const UTF8Character& decode( char c ) const { - ASSERT_MESSAGE( !globalCharacterSet().isUTF8(), "locale is utf8, no conversion required" ); - ASSERT_MESSAGE( !char_is_ascii( c ), "decode: ascii character" ); - ASSERT_MESSAGE( m_decodeMap[extended_ascii_to_index( c )].buffer != 0, "decode: invalid character: " << HexChar( c ) ); - return m_decodeMap[extended_ascii_to_index( c )]; -} -/// \brief Returns \p c encoded to extended-ascii from UTF-8. -/// \p c must map to an extended-ascii character. -char encode( const UTF8Character& c ) const { - ASSERT_MESSAGE( !globalCharacterSet().isUTF8(), "locale is utf8, no conversion required" ); - ASSERT_MESSAGE( !char_is_ascii( *c.buffer ), "encode: ascii character" ); - std::pair range - = std::equal_range( m_encodeMap, m_encodeMap + 128, UTF8CharacterToExtendedASCII( c, 0 ) ); - ASSERT_MESSAGE( range.first != range.second, "encode: invalid character: " << c ); - return ( *range.first ).m_c; -} -}; - -typedef LazyStatic GlobalExtendedASCIICharacterSet; - -/// \brief Returns the global instance of ExtendedASCIICharacterSet. -inline ExtendedASCIICharacterSet& globalExtendedASCIICharacterSet(){ - return GlobalExtendedASCIICharacterSet::instance(); -} - -class ConvertUTF8ToLocale -{ -public: -StringRange m_range; -ConvertUTF8ToLocale( const char* string ) : m_range( StringRange( string, string + strlen( string ) ) ){ -} -ConvertUTF8ToLocale( const StringRange& range ) : m_range( range ){ -} -}; - -/// \brief Writes \p convert to \p ostream after encoding each character to extended-ascii from UTF-8. -template -inline TextOutputStreamType& ostream_write( TextOutputStreamType& ostream, const ConvertUTF8ToLocale& convert ){ - if ( globalCharacterSet().isUTF8() ) { - return ostream << convert.m_range; - } - - for ( const char* p = convert.m_range.begin; p != convert.m_range.end; ) - { - if ( !char_is_ascii( *p ) ) { - UTF8Character c( p ); - ostream << globalExtendedASCIICharacterSet().encode( c ); - p += c.length; - } - else - { - ostream << *p++; - } - } - return ostream; -} - - -class ConvertLocaleToUTF8 -{ -public: -StringRange m_range; -ConvertLocaleToUTF8( const char* string ) : m_range( StringRange( string, string + strlen( string ) ) ){ -} -ConvertLocaleToUTF8( const StringRange& range ) : m_range( range ){ -} -}; - -/// \brief Writes \p convert to \p ostream after decoding each character from extended-ascii to UTF-8. -template -inline TextOutputStreamType& ostream_write( TextOutputStreamType& ostream, const ConvertLocaleToUTF8& convert ){ - if ( globalCharacterSet().isUTF8() ) { - return ostream << convert.m_range; - } - - for ( const char* p = convert.m_range.begin; p != convert.m_range.end; ++p ) - { - if ( !char_is_ascii( *p ) ) { - UTF8Character c( globalExtendedASCIICharacterSet().decode( *p ) ); - ostream.write( c.buffer, c.length ); - } - else - { - ostream << *p; - } - } - return ostream; -} - - -#endif diff --git a/tools/urt/libs/ddslib.h b/tools/urt/libs/ddslib.h deleted file mode 100644 index 4961f6e..0000000 --- a/tools/urt/libs/ddslib.h +++ /dev/null @@ -1,250 +0,0 @@ -/* ----------------------------------------------------------------------------- - - DDS Library - - Based on code from Nvidia's DDS example: - http://www.nvidia.com/object/dxtc_decompression_code.html - - Copyright (c) 2003 Randy Reddig - All rights reserved. - - Redistribution and use in source and binary forms, with or without modification, - are permitted provided that the following conditions are met: - - Redistributions of source code must retain the above copyright notice, this list - of conditions and the following disclaimer. - - Redistributions in binary form must reproduce the above copyright notice, this - list of conditions and the following disclaimer in the documentation and/or - other materials provided with the distribution. - - Neither the names of the copyright holders nor the names of its contributors may - be used to endorse or promote products derived from this software without - specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR - ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - ----------------------------------------------------------------------------- */ - - - -/* marker */ -#ifndef DDSLIB_H -#define DDSLIB_H - - - -/* dependencies */ -#include -#include - - - -/* c++ marker */ -#ifdef __cplusplus -extern "C" -{ -#endif - - - -/* dds definition */ -typedef enum -{ - DDS_PF_ARGB8888, - DDS_PF_DXT1, - DDS_PF_DXT2, - DDS_PF_DXT3, - DDS_PF_DXT4, - DDS_PF_DXT5, - DDS_PF_UNKNOWN -} -ddsPF_t; - - -/* 16bpp stuff */ -#define DDS_LOW_5 0x001F; -#define DDS_MID_6 0x07E0; -#define DDS_HIGH_5 0xF800; -#define DDS_MID_555 0x03E0; -#define DDS_HI_555 0x7C00; - - -/* structures */ -typedef struct ddsColorKey_s -{ - unsigned int colorSpaceLowValue; - unsigned int colorSpaceHighValue; -} -ddsColorKey_t; - - -typedef struct ddsCaps_s -{ - unsigned int caps1; - unsigned int caps2; - unsigned int caps3; - unsigned int caps4; -} -ddsCaps_t; - - -typedef struct ddsMultiSampleCaps_s -{ - unsigned short flipMSTypes; - unsigned short bltMSTypes; -} -ddsMultiSampleCaps_t; - - -typedef struct ddsPixelFormat_s -{ - unsigned int size; - unsigned int flags; - unsigned int fourCC; - union - { - unsigned int rgbBitCount; - unsigned int yuvBitCount; - unsigned int zBufferBitDepth; - unsigned int alphaBitDepth; - unsigned int luminanceBitCount; - unsigned int bumpBitCount; - unsigned int privateFormatBitCount; - }; - union - { - unsigned int rBitMask; - unsigned int yBitMask; - unsigned int stencilBitDepth; - unsigned int luminanceBitMask; - unsigned int bumpDuBitMask; - unsigned int operations; - }; - union - { - unsigned int gBitMask; - unsigned int uBitMask; - unsigned int zBitMask; - unsigned int bumpDvBitMask; - ddsMultiSampleCaps_t multiSampleCaps; - }; - union - { - unsigned int bBitMask; - unsigned int vBitMask; - unsigned int stencilBitMask; - unsigned int bumpLuminanceBitMask; - }; - union - { - unsigned int rgbAlphaBitMask; - unsigned int yuvAlphaBitMask; - unsigned int luminanceAlphaBitMask; - unsigned int rgbZBitMask; - unsigned int yuvZBitMask; - }; -} -ddsPixelFormat_t; - - -typedef struct ddsBuffer_s -{ - /* magic: 'dds ' */ - char magic[ 4 ]; - - /* directdraw surface */ - unsigned int size; - unsigned int flags; - unsigned int height; - unsigned int width; - union - { - int pitch; - unsigned int linearSize; - }; - unsigned int backBufferCount; - union - { - unsigned int mipMapCount; - unsigned int refreshRate; - unsigned int srcVBHandle; - }; - unsigned int alphaBitDepth; - unsigned int reserved; - void *surface; - union - { - ddsColorKey_t ckDestOverlay; - unsigned int emptyFaceColor; - }; - ddsColorKey_t ckDestBlt; - ddsColorKey_t ckSrcOverlay; - ddsColorKey_t ckSrcBlt; - union - { - ddsPixelFormat_t pixelFormat; - unsigned int fvf; - }; - ddsCaps_t ddsCaps; - unsigned int textureStage; - - /* data (Varying size) */ - unsigned char data[ 4 ]; -} -ddsBuffer_t; - - -typedef struct ddsColorBlock_s -{ - unsigned short colors[ 2 ]; - unsigned char row[ 4 ]; -} -ddsColorBlock_t; - - -typedef struct ddsAlphaBlockExplicit_s -{ - unsigned short row[ 4 ]; -} -ddsAlphaBlockExplicit_t; - - -typedef struct ddsAlphaBlock3BitLinear_s -{ - unsigned char alpha0; - unsigned char alpha1; - unsigned char stuff[ 6 ]; -} -ddsAlphaBlock3BitLinear_t; - - -typedef struct ddsColor_s -{ - unsigned char r, g, b, a; -} -ddsColor_t; - - - -/* public functions */ -int DDSGetInfo( ddsBuffer_t *dds, int *width, int *height, ddsPF_t *pf ); -int DDSDecompress( ddsBuffer_t *dds, unsigned char *pixels ); - - - -/* end marker */ -#ifdef __cplusplus -} -#endif - -#endif diff --git a/tools/urt/libs/ddslib/ddslib.c b/tools/urt/libs/ddslib/ddslib.c deleted file mode 100644 index 6ef8edf..0000000 --- a/tools/urt/libs/ddslib/ddslib.c +++ /dev/null @@ -1,773 +0,0 @@ -/* ----------------------------------------------------------------------------- - - DDS Library - - Based on code from Nvidia's DDS example: - http://www.nvidia.com/object/dxtc_decompression_code.html - - Copyright (c) 2003 Randy Reddig - All rights reserved. - - Redistribution and use in source and binary forms, with or without modification, - are permitted provided that the following conditions are met: - - Redistributions of source code must retain the above copyright notice, this list - of conditions and the following disclaimer. - - Redistributions in binary form must reproduce the above copyright notice, this - list of conditions and the following disclaimer in the documentation and/or - other materials provided with the distribution. - - Neither the names of the copyright holders nor the names of its contributors may - be used to endorse or promote products derived from this software without - specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR - ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - ----------------------------------------------------------------------------- */ - - - -/* marker */ -#define DDSLIB_C - - - -/* dependencies */ -#include "ddslib.h" - - - -/* endian tomfoolery */ -typedef union -{ - float f; - char c[ 4 ]; -} -floatSwapUnion; - - -#ifndef __BIG_ENDIAN__ - #ifdef _SGI_SOURCE - #define __BIG_ENDIAN__ - #endif -#endif - - -#ifdef __BIG_ENDIAN__ - -int DDSBigLong( int src ) { return src; } -short DDSBigShort( short src ) { return src; } -float DDSBigFloat( float src ) { return src; } - -int DDSLittleLong( int src ){ - return ( ( src & 0xFF000000 ) >> 24 ) | - ( ( src & 0x00FF0000 ) >> 8 ) | - ( ( src & 0x0000FF00 ) << 8 ) | - ( ( src & 0x000000FF ) << 24 ); -} - -short DDSLittleShort( short src ){ - return ( ( src & 0xFF00 ) >> 8 ) | - ( ( src & 0x00FF ) << 8 ); -} - -float DDSLittleFloat( float src ){ - floatSwapUnion in,out; - in.f = src; - out.c[ 0 ] = in.c[ 3 ]; - out.c[ 1 ] = in.c[ 2 ]; - out.c[ 2 ] = in.c[ 1 ]; - out.c[ 3 ] = in.c[ 0 ]; - return out.f; -} - -#else /*__BIG_ENDIAN__*/ - -int DDSLittleLong( int src ) { return src; } -short DDSLittleShort( short src ) { return src; } -float DDSLittleFloat( float src ) { return src; } - -int DDSBigLong( int src ){ - return ( ( src & 0xFF000000 ) >> 24 ) | - ( ( src & 0x00FF0000 ) >> 8 ) | - ( ( src & 0x0000FF00 ) << 8 ) | - ( ( src & 0x000000FF ) << 24 ); -} - -short DDSBigShort( short src ){ - return ( ( src & 0xFF00 ) >> 8 ) | - ( ( src & 0x00FF ) << 8 ); -} - -float DDSBigFloat( float src ){ - floatSwapUnion in,out; - in.f = src; - out.c[ 0 ] = in.c[ 3 ]; - out.c[ 1 ] = in.c[ 2 ]; - out.c[ 2 ] = in.c[ 1 ]; - out.c[ 3 ] = in.c[ 0 ]; - return out.f; -} - -#endif /*__BIG_ENDIAN__*/ - - - -/* - DDSDecodePixelFormat() - determines which pixel format the dds texture is in - */ - -static void DDSDecodePixelFormat( ddsBuffer_t *dds, ddsPF_t *pf ){ - unsigned int fourCC; - - - /* dummy check */ - if ( dds == NULL || pf == NULL ) { - return; - } - - /* extract fourCC */ - fourCC = dds->pixelFormat.fourCC; - - /* test it */ - if ( fourCC == 0 ) { - *pf = DDS_PF_ARGB8888; - } - else if ( fourCC == *( (unsigned int*) "DXT1" ) ) { - *pf = DDS_PF_DXT1; - } - else if ( fourCC == *( (unsigned int*) "DXT2" ) ) { - *pf = DDS_PF_DXT2; - } - else if ( fourCC == *( (unsigned int*) "DXT3" ) ) { - *pf = DDS_PF_DXT3; - } - else if ( fourCC == *( (unsigned int*) "DXT4" ) ) { - *pf = DDS_PF_DXT4; - } - else if ( fourCC == *( (unsigned int*) "DXT5" ) ) { - *pf = DDS_PF_DXT5; - } - else{ - *pf = DDS_PF_UNKNOWN; - } -} - - - -/* - DDSGetInfo() - extracts relevant info from a dds texture, returns 0 on success - */ - -int DDSGetInfo( ddsBuffer_t *dds, int *width, int *height, ddsPF_t *pf ){ - /* dummy test */ - if ( dds == NULL ) { - return -1; - } - - /* test dds header */ - if ( *( (int*) dds->magic ) != *( (int*) "DDS " ) ) { - return -1; - } - if ( DDSLittleLong( dds->size ) != 124 ) { - return -1; - } - - /* extract width and height */ - if ( width != NULL ) { - *width = DDSLittleLong( dds->width ); - } - if ( height != NULL ) { - *height = DDSLittleLong( dds->height ); - } - - /* get pixel format */ - DDSDecodePixelFormat( dds, pf ); - - /* return ok */ - return 0; -} - - - -/* - DDSGetColorBlockColors() - extracts colors from a dds color block - */ - -static void DDSGetColorBlockColors( ddsColorBlock_t *block, ddsColor_t colors[ 4 ] ){ - unsigned short word; - - - /* color 0 */ - word = DDSLittleShort( block->colors[ 0 ] ); - colors[ 0 ].a = 0xff; - - /* extract rgb bits */ - colors[ 0 ].b = (unsigned char) word; - colors[ 0 ].b <<= 3; - colors[ 0 ].b |= ( colors[ 0 ].b >> 5 ); - word >>= 5; - colors[ 0 ].g = (unsigned char) word; - colors[ 0 ].g <<= 2; - colors[ 0 ].g |= ( colors[ 0 ].g >> 5 ); - word >>= 6; - colors[ 0 ].r = (unsigned char) word; - colors[ 0 ].r <<= 3; - colors[ 0 ].r |= ( colors[ 0 ].r >> 5 ); - - /* same for color 1 */ - word = DDSLittleShort( block->colors[ 1 ] ); - colors[ 1 ].a = 0xff; - - /* extract rgb bits */ - colors[ 1 ].b = (unsigned char) word; - colors[ 1 ].b <<= 3; - colors[ 1 ].b |= ( colors[ 1 ].b >> 5 ); - word >>= 5; - colors[ 1 ].g = (unsigned char) word; - colors[ 1 ].g <<= 2; - colors[ 1 ].g |= ( colors[ 1 ].g >> 5 ); - word >>= 6; - colors[ 1 ].r = (unsigned char) word; - colors[ 1 ].r <<= 3; - colors[ 1 ].r |= ( colors[ 1 ].r >> 5 ); - - /* use this for all but the super-freak math method */ - if ( block->colors[ 0 ] > block->colors[ 1 ] ) { - /* four-color block: derive the other two colors. - 00 = color 0, 01 = color 1, 10 = color 2, 11 = color 3 - these two bit codes correspond to the 2-bit fields - stored in the 64-bit block. */ - - word = ( (unsigned short) colors[ 0 ].r * 2 + (unsigned short) colors[ 1 ].r ) / 3; - /* no +1 for rounding */ - /* as bits have been shifted to 888 */ - colors[ 2 ].r = (unsigned char) word; - word = ( (unsigned short) colors[ 0 ].g * 2 + (unsigned short) colors[ 1 ].g ) / 3; - colors[ 2 ].g = (unsigned char) word; - word = ( (unsigned short) colors[ 0 ].b * 2 + (unsigned short) colors[ 1 ].b ) / 3; - colors[ 2 ].b = (unsigned char) word; - colors[ 2 ].a = 0xff; - - word = ( (unsigned short) colors[ 0 ].r + (unsigned short) colors[ 1 ].r * 2 ) / 3; - colors[ 3 ].r = (unsigned char) word; - word = ( (unsigned short) colors[ 0 ].g + (unsigned short) colors[ 1 ].g * 2 ) / 3; - colors[ 3 ].g = (unsigned char) word; - word = ( (unsigned short) colors[ 0 ].b + (unsigned short) colors[ 1 ].b * 2 ) / 3; - colors[ 3 ].b = (unsigned char) word; - colors[ 3 ].a = 0xff; - } - else - { - /* three-color block: derive the other color. - 00 = color 0, 01 = color 1, 10 = color 2, - 11 = transparent. - These two bit codes correspond to the 2-bit fields - stored in the 64-bit block */ - - word = ( (unsigned short) colors[ 0 ].r + (unsigned short) colors[ 1 ].r ) / 2; - colors[ 2 ].r = (unsigned char) word; - word = ( (unsigned short) colors[ 0 ].g + (unsigned short) colors[ 1 ].g ) / 2; - colors[ 2 ].g = (unsigned char) word; - word = ( (unsigned short) colors[ 0 ].b + (unsigned short) colors[ 1 ].b ) / 2; - colors[ 2 ].b = (unsigned char) word; - colors[ 2 ].a = 0xff; - - /* random color to indicate alpha */ - colors[ 3 ].r = 0x00; - colors[ 3 ].g = 0xff; - colors[ 3 ].b = 0xff; - colors[ 3 ].a = 0x00; - } -} - - - -/* - DDSDecodeColorBlock() - decodes a dds color block - fixme: make endian-safe - */ - -static void DDSDecodeColorBlock( unsigned int *pixel, ddsColorBlock_t *block, int width, unsigned int colors[ 4 ] ){ - int r, n; - unsigned int bits; - unsigned int masks[] = { 3, 12, 3 << 4, 3 << 6 }; /* bit masks = 00000011, 00001100, 00110000, 11000000 */ - int shift[] = { 0, 2, 4, 6 }; - - - /* r steps through lines in y */ - for ( r = 0; r < 4; r++, pixel += ( width - 4 ) ) /* no width * 4 as unsigned int ptr inc will * 4 */ - { - /* width * 4 bytes per pixel per line, each j dxtc row is 4 lines of pixels */ - - /* n steps through pixels */ - for ( n = 0; n < 4; n++ ) - { - bits = block->row[ r ] & masks[ n ]; - bits >>= shift[ n ]; - - switch ( bits ) - { - case 0: - *pixel = colors[ 0 ]; - pixel++; - break; - - case 1: - *pixel = colors[ 1 ]; - pixel++; - break; - - case 2: - *pixel = colors[ 2 ]; - pixel++; - break; - - case 3: - *pixel = colors[ 3 ]; - pixel++; - break; - - default: - /* invalid */ - pixel++; - break; - } - } - } -} - - - -/* - DDSDecodeAlphaExplicit() - decodes a dds explicit alpha block - */ - -static void DDSDecodeAlphaExplicit( unsigned int *pixel, ddsAlphaBlockExplicit_t *alphaBlock, int width, unsigned int alphaZero ){ - int row, pix; - unsigned short word; - ddsColor_t color; - - - /* clear color */ - color.r = 0; - color.g = 0; - color.b = 0; - - /* walk rows */ - for ( row = 0; row < 4; row++, pixel += ( width - 4 ) ) - { - word = DDSLittleShort( alphaBlock->row[ row ] ); - - /* walk pixels */ - for ( pix = 0; pix < 4; pix++ ) - { - /* zero the alpha bits of image pixel */ - *pixel &= alphaZero; - color.a = word & 0x000F; - color.a = color.a | ( color.a << 4 ); - *pixel |= *( (unsigned int*) &color ); - word >>= 4; /* move next bits to lowest 4 */ - pixel++; /* move to next pixel in the row */ - - } - } -} - - - -/* - DDSDecodeAlpha3BitLinear() - decodes interpolated alpha block - */ - -static void DDSDecodeAlpha3BitLinear( unsigned int *pixel, ddsAlphaBlock3BitLinear_t *alphaBlock, int width, unsigned int alphaZero ){ - - int row, pix; - unsigned int stuff; - unsigned char bits[ 4 ][ 4 ]; - unsigned short alphas[ 8 ]; - ddsColor_t aColors[ 4 ][ 4 ]; - - - /* get initial alphas */ - alphas[ 0 ] = alphaBlock->alpha0; - alphas[ 1 ] = alphaBlock->alpha1; - - /* 8-alpha block */ - if ( alphas[ 0 ] > alphas[ 1 ] ) { - /* 000 = alpha_0, 001 = alpha_1, others are interpolated */ - alphas[ 2 ] = ( 6 * alphas[ 0 ] + alphas[ 1 ] ) / 7; /* bit code 010 */ - alphas[ 3 ] = ( 5 * alphas[ 0 ] + 2 * alphas[ 1 ] ) / 7; /* bit code 011 */ - alphas[ 4 ] = ( 4 * alphas[ 0 ] + 3 * alphas[ 1 ] ) / 7; /* bit code 100 */ - alphas[ 5 ] = ( 3 * alphas[ 0 ] + 4 * alphas[ 1 ] ) / 7; /* bit code 101 */ - alphas[ 6 ] = ( 2 * alphas[ 0 ] + 5 * alphas[ 1 ] ) / 7; /* bit code 110 */ - alphas[ 7 ] = ( alphas[ 0 ] + 6 * alphas[ 1 ] ) / 7; /* bit code 111 */ - } - - /* 6-alpha block */ - else - { - /* 000 = alpha_0, 001 = alpha_1, others are interpolated */ - alphas[ 2 ] = ( 4 * alphas[ 0 ] + alphas[ 1 ] ) / 5; /* bit code 010 */ - alphas[ 3 ] = ( 3 * alphas[ 0 ] + 2 * alphas[ 1 ] ) / 5; /* bit code 011 */ - alphas[ 4 ] = ( 2 * alphas[ 0 ] + 3 * alphas[ 1 ] ) / 5; /* bit code 100 */ - alphas[ 5 ] = ( alphas[ 0 ] + 4 * alphas[ 1 ] ) / 5; /* bit code 101 */ - alphas[ 6 ] = 0; /* bit code 110 */ - alphas[ 7 ] = 255; /* bit code 111 */ - } - - /* decode 3-bit fields into array of 16 bytes with same value */ - - /* first two rows of 4 pixels each */ - stuff = *( (unsigned int*) &( alphaBlock->stuff[ 0 ] ) ); - - bits[ 0 ][ 0 ] = (unsigned char) ( stuff & 0x00000007 ); - stuff >>= 3; - bits[ 0 ][ 1 ] = (unsigned char) ( stuff & 0x00000007 ); - stuff >>= 3; - bits[ 0 ][ 2 ] = (unsigned char) ( stuff & 0x00000007 ); - stuff >>= 3; - bits[ 0 ][ 3 ] = (unsigned char) ( stuff & 0x00000007 ); - stuff >>= 3; - bits[ 1 ][ 0 ] = (unsigned char) ( stuff & 0x00000007 ); - stuff >>= 3; - bits[ 1 ][ 1 ] = (unsigned char) ( stuff & 0x00000007 ); - stuff >>= 3; - bits[ 1 ][ 2 ] = (unsigned char) ( stuff & 0x00000007 ); - stuff >>= 3; - bits[ 1 ][ 3 ] = (unsigned char) ( stuff & 0x00000007 ); - - /* last two rows */ - stuff = *( (unsigned int*) &( alphaBlock->stuff[ 3 ] ) ); /* last 3 bytes */ - - bits[ 2 ][ 0 ] = (unsigned char) ( stuff & 0x00000007 ); - stuff >>= 3; - bits[ 2 ][ 1 ] = (unsigned char) ( stuff & 0x00000007 ); - stuff >>= 3; - bits[ 2 ][ 2 ] = (unsigned char) ( stuff & 0x00000007 ); - stuff >>= 3; - bits[ 2 ][ 3 ] = (unsigned char) ( stuff & 0x00000007 ); - stuff >>= 3; - bits[ 3 ][ 0 ] = (unsigned char) ( stuff & 0x00000007 ); - stuff >>= 3; - bits[ 3 ][ 1 ] = (unsigned char) ( stuff & 0x00000007 ); - stuff >>= 3; - bits[ 3 ][ 2 ] = (unsigned char) ( stuff & 0x00000007 ); - stuff >>= 3; - bits[ 3 ][ 3 ] = (unsigned char) ( stuff & 0x00000007 ); - - /* decode the codes into alpha values */ - for ( row = 0; row < 4; row++ ) - { - for ( pix = 0; pix < 4; pix++ ) - { - aColors[ row ][ pix ].r = 0; - aColors[ row ][ pix ].g = 0; - aColors[ row ][ pix ].b = 0; - aColors[ row ][ pix ].a = (unsigned char) alphas[ bits[ row ][ pix ] ]; - } - } - - /* write out alpha values to the image bits */ - for ( row = 0; row < 4; row++, pixel += width - 4 ) - { - for ( pix = 0; pix < 4; pix++ ) - { - /* zero the alpha bits of image pixel */ - *pixel &= alphaZero; - - /* or the bits into the prev. nulled alpha */ - *pixel |= *( (unsigned int*) &( aColors[ row ][ pix ] ) ); - pixel++; - } - } -} - - - -/* - DDSDecompressDXT1() - decompresses a dxt1 format texture - */ - -static int DDSDecompressDXT1( ddsBuffer_t *dds, int width, int height, unsigned char *pixels ){ - int x, y, xBlocks, yBlocks; - unsigned int *pixel; - ddsColorBlock_t *block; - ddsColor_t colors[ 4 ]; - - - /* setup */ - xBlocks = width / 4; - yBlocks = height / 4; - - /* walk y */ - for ( y = 0; y < yBlocks; y++ ) - { - /* 8 bytes per block */ - block = (ddsColorBlock_t*) ( (unsigned int) dds->data + y * xBlocks * 8 ); - - /* walk x */ - for ( x = 0; x < xBlocks; x++, block++ ) - { - DDSGetColorBlockColors( block, colors ); - pixel = (unsigned int*) ( pixels + x * 16 + ( y * 4 ) * width * 4 ); - DDSDecodeColorBlock( pixel, block, width, (unsigned int*) colors ); - } - } - - /* return ok */ - return 0; -} - - - -/* - DDSDecompressDXT3() - decompresses a dxt3 format texture - */ - -static int DDSDecompressDXT3( ddsBuffer_t *dds, int width, int height, unsigned char *pixels ){ - int x, y, xBlocks, yBlocks; - unsigned int *pixel, alphaZero; - ddsColorBlock_t *block; - ddsAlphaBlockExplicit_t *alphaBlock; - ddsColor_t colors[ 4 ]; - - - /* setup */ - xBlocks = width / 4; - yBlocks = height / 4; - - /* create zero alpha */ - colors[ 0 ].a = 0; - colors[ 0 ].r = 0xFF; - colors[ 0 ].g = 0xFF; - colors[ 0 ].b = 0xFF; - alphaZero = *( (unsigned int*) &colors[ 0 ] ); - - /* walk y */ - for ( y = 0; y < yBlocks; y++ ) - { - /* 8 bytes per block, 1 block for alpha, 1 block for color */ - block = (ddsColorBlock_t*) ( (unsigned int) dds->data + y * xBlocks * 16 ); - - /* walk x */ - for ( x = 0; x < xBlocks; x++, block++ ) - { - /* get alpha block */ - alphaBlock = (ddsAlphaBlockExplicit_t*) block; - - /* get color block */ - block++; - DDSGetColorBlockColors( block, colors ); - - /* decode color block */ - pixel = (unsigned int*) ( pixels + x * 16 + ( y * 4 ) * width * 4 ); - DDSDecodeColorBlock( pixel, block, width, (unsigned int*) colors ); - - /* overwrite alpha bits with alpha block */ - DDSDecodeAlphaExplicit( pixel, alphaBlock, width, alphaZero ); - } - } - - /* return ok */ - return 0; -} - - - -/* - DDSDecompressDXT5() - decompresses a dxt5 format texture - */ - -static int DDSDecompressDXT5( ddsBuffer_t *dds, int width, int height, unsigned char *pixels ){ - int x, y, xBlocks, yBlocks; - unsigned int *pixel, alphaZero; - ddsColorBlock_t *block; - ddsAlphaBlock3BitLinear_t *alphaBlock; - ddsColor_t colors[ 4 ]; - - - /* setup */ - xBlocks = width / 4; - yBlocks = height / 4; - - /* create zero alpha */ - colors[ 0 ].a = 0; - colors[ 0 ].r = 0xFF; - colors[ 0 ].g = 0xFF; - colors[ 0 ].b = 0xFF; - alphaZero = *( (unsigned int*) &colors[ 0 ] ); - - /* walk y */ - for ( y = 0; y < yBlocks; y++ ) - { - /* 8 bytes per block, 1 block for alpha, 1 block for color */ - block = (ddsColorBlock_t*) ( (unsigned int) dds->data + y * xBlocks * 16 ); - - /* walk x */ - for ( x = 0; x < xBlocks; x++, block++ ) - { - /* get alpha block */ - alphaBlock = (ddsAlphaBlock3BitLinear_t*) block; - - /* get color block */ - block++; - DDSGetColorBlockColors( block, colors ); - - /* decode color block */ - pixel = (unsigned int*) ( pixels + x * 16 + ( y * 4 ) * width * 4 ); - DDSDecodeColorBlock( pixel, block, width, (unsigned int*) colors ); - - /* overwrite alpha bits with alpha block */ - DDSDecodeAlpha3BitLinear( pixel, alphaBlock, width, alphaZero ); - } - } - - /* return ok */ - return 0; -} - - - -/* - DDSDecompressDXT2() - decompresses a dxt2 format texture (fixme: un-premultiply alpha) - */ - -static int DDSDecompressDXT2( ddsBuffer_t *dds, int width, int height, unsigned char *pixels ){ - int r; - - - /* decompress dxt3 first */ - r = DDSDecompressDXT3( dds, width, height, pixels ); - - /* return to sender */ - return r; -} - - - -/* - DDSDecompressDXT4() - decompresses a dxt4 format texture (fixme: un-premultiply alpha) - */ - -static int DDSDecompressDXT4( ddsBuffer_t *dds, int width, int height, unsigned char *pixels ){ - int r; - - - /* decompress dxt5 first */ - r = DDSDecompressDXT5( dds, width, height, pixels ); - - /* return to sender */ - return r; -} - - - -/* - DDSDecompressARGB8888() - decompresses an argb 8888 format texture - */ - -static int DDSDecompressARGB8888( ddsBuffer_t *dds, int width, int height, unsigned char *pixels ){ - int x, y; - unsigned char *in, *out; - - - /* setup */ - in = dds->data; - out = pixels; - - /* walk y */ - for ( y = 0; y < height; y++ ) - { - /* walk x */ - for ( x = 0; x < width; x++ ) - { - *out++ = *in++; - *out++ = *in++; - *out++ = *in++; - *out++ = *in++; - } - } - - /* return ok */ - return 0; -} - - - -/* - DDSDecompress() - decompresses a dds texture into an rgba image buffer, returns 0 on success - */ - -int DDSDecompress( ddsBuffer_t *dds, unsigned char *pixels ){ - int width, height, r; - ddsPF_t pf; - - - /* get dds info */ - r = DDSGetInfo( dds, &width, &height, &pf ); - if ( r ) { - return r; - } - - /* decompress */ - switch ( pf ) - { - case DDS_PF_ARGB8888: - /* fixme: support other [a]rgb formats */ - r = DDSDecompressARGB8888( dds, width, height, pixels ); - break; - - case DDS_PF_DXT1: - r = DDSDecompressDXT1( dds, width, height, pixels ); - break; - - case DDS_PF_DXT2: - r = DDSDecompressDXT2( dds, width, height, pixels ); - break; - - case DDS_PF_DXT3: - r = DDSDecompressDXT3( dds, width, height, pixels ); - break; - - case DDS_PF_DXT4: - r = DDSDecompressDXT4( dds, width, height, pixels ); - break; - - case DDS_PF_DXT5: - r = DDSDecompressDXT5( dds, width, height, pixels ); - break; - - default: - case DDS_PF_UNKNOWN: - memset( pixels, 0xFF, width * height * 4 ); - r = -1; - break; - } - - /* return to sender */ - return r; -} diff --git a/tools/urt/libs/ddslib/ddslib.dsp b/tools/urt/libs/ddslib/ddslib.dsp deleted file mode 100644 index 1b684d9..0000000 --- a/tools/urt/libs/ddslib/ddslib.dsp +++ /dev/null @@ -1,106 +0,0 @@ -# Microsoft Developer Studio Project File - Name="ddslib" - Package Owner=<4> -# Microsoft Developer Studio Generated Build File, Format Version 6.00 -# ** DO NOT EDIT ** - -# TARGTYPE "Win32 (x86) Static Library" 0x0104 - -CFG=ddslib - Win32 Debug -!MESSAGE This is not a valid makefile. To build this project using NMAKE, -!MESSAGE use the Export Makefile command and run -!MESSAGE -!MESSAGE NMAKE /f "ddslib.mak". -!MESSAGE -!MESSAGE You can specify a configuration when running NMAKE -!MESSAGE by defining the macro CFG on the command line. For example: -!MESSAGE -!MESSAGE NMAKE /f "ddslib.mak" CFG="ddslib - Win32 Debug" -!MESSAGE -!MESSAGE Possible choices for configuration are: -!MESSAGE -!MESSAGE "ddslib - Win32 Release" (based on "Win32 (x86) Static Library") -!MESSAGE "ddslib - Win32 Debug" (based on "Win32 (x86) Static Library") -!MESSAGE - -# Begin Project -# PROP AllowPerConfigDependencies 0 -# PROP Scc_ProjName "Perforce Project" -# PROP Scc_LocalPath ".." -CPP=cl.exe -RSC=rc.exe - -!IF "$(CFG)" == "ddslib - Win32 Release" - -# PROP BASE Use_MFC 0 -# PROP BASE Use_Debug_Libraries 0 -# PROP BASE Output_Dir "Release" -# PROP BASE Intermediate_Dir "Release" -# PROP BASE Target_Dir "" -# PROP Use_MFC 0 -# PROP Use_Debug_Libraries 0 -# PROP Output_Dir "Release" -# PROP Intermediate_Dir "Release" -# PROP Target_Dir "" -F90=df.exe -MTL=midl.exe -# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /YX /FD /c -# ADD CPP /nologo /MD /W3 /O2 /I ".." /D "WIN32" /D "NDEBUG" /D "_MBCS" /D "_LIB" /FR /FD /c -# SUBTRACT CPP /YX -# ADD BASE RSC /l 0x409 /d "NDEBUG" -# ADD RSC /l 0x409 /d "NDEBUG" -BSC32=bscmake.exe -# ADD BASE BSC32 /nologo -# ADD BSC32 /nologo -LIB32=link.exe -lib -# ADD BASE LIB32 /nologo -# ADD LIB32 /nologo - -!ELSEIF "$(CFG)" == "ddslib - Win32 Debug" - -# PROP BASE Use_MFC 0 -# PROP BASE Use_Debug_Libraries 1 -# PROP BASE Output_Dir "Debug" -# PROP BASE Intermediate_Dir "Debug" -# PROP BASE Target_Dir "" -# PROP Use_MFC 0 -# PROP Use_Debug_Libraries 1 -# PROP Output_Dir "Debug" -# PROP Intermediate_Dir "Debug" -# PROP Target_Dir "" -F90=df.exe -MTL=midl.exe -# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /YX /FD /GZ /c -# ADD CPP /nologo /MDd /W3 /Gm /ZI /Od /I ".." /D "WIN32" /D "_DEBUG" /D "_MBCS" /D "_LIB" /FR /FD /GZ /c -# SUBTRACT CPP /YX -# ADD BASE RSC /l 0x409 /d "_DEBUG" -# ADD RSC /l 0x409 /d "_DEBUG" -BSC32=bscmake.exe -# ADD BASE BSC32 /nologo -# ADD BSC32 /nologo -LIB32=link.exe -lib -# ADD BASE LIB32 /nologo -# ADD LIB32 /nologo - -!ENDIF - -# Begin Target - -# Name "ddslib - Win32 Release" -# Name "ddslib - Win32 Debug" -# Begin Group "src" - -# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat" -# Begin Source File - -SOURCE=.\ddslib.c -# End Source File -# End Group -# Begin Group "include" - -# PROP Default_Filter "h;hpp;hxx;hm;inl" -# Begin Source File - -SOURCE=..\ddslib.h -# End Source File -# End Group -# End Target -# End Project diff --git a/tools/urt/libs/ddslib/ddslib.plg b/tools/urt/libs/ddslib/ddslib.plg deleted file mode 100644 index d6ec3b9..0000000 --- a/tools/urt/libs/ddslib/ddslib.plg +++ /dev/null @@ -1,27 +0,0 @@ - - -
-

Build Log

-

---------------------Configuration: ddslib - Win32 Debug-------------------- -

-

Command Lines

-Creating temporary file "C:\DOCUME~1\TWENTY~1\LOCALS~1\Temp\RSP5F1.tmp" with contents -[ -/nologo /MDd /W3 /Gm /ZI /Od /I ".." /D "WIN32" /D "_DEBUG" /D "_MBCS" /D "_LIB" /FR"Debug/" /Fo"Debug/" /Fd"Debug/" /FD /GZ /c -"C:\Program Files\Subversion\GtkRadiant\libs\ddslib\ddslib.c" -] -Creating command line "cl.exe @C:\DOCUME~1\TWENTY~1\LOCALS~1\Temp\RSP5F1.tmp" -Creating command line "link.exe -lib /nologo /out:"Debug\ddslib.lib" ".\Debug\ddslib.obj" " -

Output Window

-Compiling... -ddslib.c -Creating library... - - - -

Results

-ddslib.lib - 0 error(s), 0 warning(s) -
- - diff --git a/tools/urt/libs/ddslib/ddslib.vcproj b/tools/urt/libs/ddslib/ddslib.vcproj deleted file mode 100644 index 6668373..0000000 --- a/tools/urt/libs/ddslib/ddslib.vcproj +++ /dev/null @@ -1,211 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/tools/urt/libs/debugging/debugging.cpp b/tools/urt/libs/debugging/debugging.cpp deleted file mode 100644 index ce56e89..0000000 --- a/tools/urt/libs/debugging/debugging.cpp +++ /dev/null @@ -1,7 +0,0 @@ - -#include "debugging.h" - -void TEST_ASSERT(){ - ERROR_MESSAGE( "test" ); - ASSERT_NOTNULL( 0 ); -} diff --git a/tools/urt/libs/debugging/debugging.h b/tools/urt/libs/debugging/debugging.h deleted file mode 100644 index 9a606ba..0000000 --- a/tools/urt/libs/debugging/debugging.h +++ /dev/null @@ -1,107 +0,0 @@ - -#if !defined( INCLUDED_DEBUGGING_DEBUGGING_H ) -#define INCLUDED_DEBUGGING_DEBUGGING_H - -/// \file -/// \brief Debugging macros for fatal error/assert messages. - -#include "stream/textstream.h" -#include "warnings.h" -#include "generic/static.h" - -#if defined( _MSC_VER ) && defined( _M_IX86 ) -#define DEBUGGER_BREAKPOINT() __asm { int 3 } -#elif defined ( __i386__ ) && defined ( __GNUC__ ) && __GNUC__ >= 2 -#define DEBUGGER_BREAKPOINT() __asm__ __volatile__ ( "int $03" ) -#else -#include - -#define DEBUGGER_BREAKPOINT() raise( SIGTRAP ); -#endif - - -#define FILE_LINE __FILE__ ":" << __LINE__ - -#if defined( _DEBUG ) || 1 -#define DEBUG_ASSERTS -#endif - -class DebugMessageHandler -{ -public: -virtual TextOutputStream& getOutputStream() = 0; -virtual bool handleMessage() = 0; -}; - -class NullDebugMessageHandler : public NullOutputStream, public DebugMessageHandler -{ -public: -virtual TextOutputStream& getOutputStream(){ - return *this; -} -virtual bool handleMessage(){ - return false; -} -}; - -class DefaultDebugMessageHandler : public DebugMessageHandler -{ -public: -virtual TextOutputStream& getOutputStream(){ - return globalErrorStream(); -} -virtual bool handleMessage(){ -#if defined( _DEBUG ) - return false; // send debug-break -#else - return true; -#endif -} -}; - -class DebugMessageHandlerRef : public DefaultDebugMessageHandler -{ -DebugMessageHandler* m_handler; -public: -DebugMessageHandlerRef() - : m_handler( this ){ -} -void setHandler( DebugMessageHandler& handler ){ - m_handler = &handler; -} -DebugMessageHandler& getHandler(){ - return *m_handler; -} -}; - -typedef Static GlobalDebugMessageHandler; - -inline DebugMessageHandler& globalDebugMessageHandler(){ - return GlobalDebugMessageHandler::instance().getHandler(); -} - -#if defined( DEBUG_ASSERTS ) - -/// \brief Sends a \p message to the current debug-message-handler text-output-stream if \p condition evaluates to false. -#define ASSERT_MESSAGE( condition, message ) \ - if ( !( condition ) ) \ - { \ - globalDebugMessageHandler().getOutputStream() << FILE_LINE << "\nassertion failure: " << message << "\n"; \ - if ( !globalDebugMessageHandler().handleMessage() ) { DEBUGGER_BREAKPOINT(); } \ - } else \ - -/// \brief Sends a \p message to the current debug-message-handler text-output-stream. -#define ERROR_MESSAGE( message ) \ - globalDebugMessageHandler().getOutputStream() << FILE_LINE << "\nruntime error: " << message << "\n"; \ - if ( !globalDebugMessageHandler().handleMessage() ) { DEBUGGER_BREAKPOINT(); } else \ - -#define ASSERT_NOTNULL( ptr ) ASSERT_MESSAGE( ptr != 0, "pointer \"" # ptr "\" is null" ) - -#else - -#define ASSERT_MESSAGE( condition, message ) -#define ASSERT_NOTNULL( ptr ) - -#endif - -#endif diff --git a/tools/urt/libs/dragplanes.cpp b/tools/urt/libs/dragplanes.cpp deleted file mode 100644 index 495cf91..0000000 --- a/tools/urt/libs/dragplanes.cpp +++ /dev/null @@ -1,2 +0,0 @@ - -#include "dragplanes.h" diff --git a/tools/urt/libs/dragplanes.h b/tools/urt/libs/dragplanes.h deleted file mode 100644 index 8eef270..0000000 --- a/tools/urt/libs/dragplanes.h +++ /dev/null @@ -1,202 +0,0 @@ - -#if !defined( INCLUDED_DRAGPLANES_H ) -#define INCLUDED_DRAGPLANES_H - -#include "selectable.h" -#include "selectionlib.h" -#include "math/aabb.h" -#include "math/line.h" - -class DragPlanes -{ -public: -ObservedSelectable m_selectable_right; // +x -ObservedSelectable m_selectable_left; // -x -ObservedSelectable m_selectable_front; // +y -ObservedSelectable m_selectable_back; // -y -ObservedSelectable m_selectable_top; // +z -ObservedSelectable m_selectable_bottom; // -z -Vector3 m_dragPlanesMin; -Vector3 m_dragPlanesMax; -Vector3 m_dragPlanesOrigin; -Vector3 m_dragPlanesExtents; - -DragPlanes( const SelectionChangeCallback& onchanged ) : - m_selectable_right( onchanged ), - m_selectable_left( onchanged ), - m_selectable_front( onchanged ), - m_selectable_back( onchanged ), - m_selectable_top( onchanged ), - m_selectable_bottom( onchanged ){ -} -bool isSelected() const { - return m_selectable_right.isSelected() - || m_selectable_left.isSelected() - || m_selectable_front.isSelected() - || m_selectable_back.isSelected() - || m_selectable_top.isSelected() - || m_selectable_bottom.isSelected(); -} -void setSelected( bool selected ){ - m_selectable_right.setSelected( selected ); - m_selectable_left.setSelected( selected ); - m_selectable_front.setSelected( selected ); - m_selectable_back.setSelected( selected ); - m_selectable_top.setSelected( selected ); - m_selectable_bottom.setSelected( selected ); -} -void selectPlanes( const AABB& aabb, Selector& selector, SelectionTest& test, const PlaneCallback& selectedPlaneCallback ){ - Line line( test.getNear(), test.getFar() ); - Vector3 corners[8]; - aabb_corners( aabb, corners ); - Plane3 planes[6]; - aabb_planes( aabb, planes ); - - for ( Vector3* i = corners; i != corners + 8; ++i ) - { - *i = vector3_subtracted( line_closest_point( line, *i ), *i ); - } - - if ( vector3_dot( planes[0].normal(), corners[1] ) > 0 - && vector3_dot( planes[0].normal(), corners[2] ) > 0 - && vector3_dot( planes[0].normal(), corners[5] ) > 0 - && vector3_dot( planes[0].normal(), corners[6] ) > 0 ) { - Selector_add( selector, m_selectable_right ); - selectedPlaneCallback( planes[0] ); - //globalOutputStream() << "right\n"; - } - if ( vector3_dot( planes[1].normal(), corners[0] ) > 0 - && vector3_dot( planes[1].normal(), corners[3] ) > 0 - && vector3_dot( planes[1].normal(), corners[4] ) > 0 - && vector3_dot( planes[1].normal(), corners[7] ) > 0 ) { - Selector_add( selector, m_selectable_left ); - selectedPlaneCallback( planes[1] ); - //globalOutputStream() << "left\n"; - } - if ( vector3_dot( planes[2].normal(), corners[0] ) > 0 - && vector3_dot( planes[2].normal(), corners[1] ) > 0 - && vector3_dot( planes[2].normal(), corners[4] ) > 0 - && vector3_dot( planes[2].normal(), corners[5] ) > 0 ) { - Selector_add( selector, m_selectable_front ); - selectedPlaneCallback( planes[2] ); - //globalOutputStream() << "front\n"; - } - if ( vector3_dot( planes[3].normal(), corners[2] ) > 0 - && vector3_dot( planes[3].normal(), corners[3] ) > 0 - && vector3_dot( planes[3].normal(), corners[6] ) > 0 - && vector3_dot( planes[3].normal(), corners[7] ) > 0 ) { - Selector_add( selector, m_selectable_back ); - selectedPlaneCallback( planes[3] ); - //globalOutputStream() << "back\n"; - } - if ( vector3_dot( planes[4].normal(), corners[0] ) > 0 - && vector3_dot( planes[4].normal(), corners[1] ) > 0 - && vector3_dot( planes[4].normal(), corners[2] ) > 0 - && vector3_dot( planes[4].normal(), corners[3] ) > 0 ) { - Selector_add( selector, m_selectable_top ); - selectedPlaneCallback( planes[4] ); - //globalOutputStream() << "top\n"; - } - if ( vector3_dot( planes[5].normal(), corners[4] ) > 0 - && vector3_dot( planes[5].normal(), corners[5] ) > 0 - && vector3_dot( planes[5].normal(), corners[6] ) > 0 - && vector3_dot( planes[5].normal(), corners[7] ) > 0 ) { - Selector_add( selector, m_selectable_bottom ); - //globalOutputStream() << "bottom\n"; - selectedPlaneCallback( planes[5] ); - } - - m_dragPlanesMin = aabb.origin - aabb.extents; - m_dragPlanesMax = aabb.origin + aabb.extents; - m_dragPlanesOrigin = aabb.origin; - m_dragPlanesExtents = aabb.extents; -} -void selectReversedPlanes( const AABB& aabb, Selector& selector, const SelectedPlanes& selectedPlanes ){ - Plane3 planes[6]; - aabb_planes( aabb, planes ); - - if ( selectedPlanes.contains( plane3_flipped( planes[0] ) ) ) { - Selector_add( selector, m_selectable_right ); - } - if ( selectedPlanes.contains( plane3_flipped( planes[1] ) ) ) { - Selector_add( selector, m_selectable_left ); - } - if ( selectedPlanes.contains( plane3_flipped( planes[2] ) ) ) { - Selector_add( selector, m_selectable_front ); - } - if ( selectedPlanes.contains( plane3_flipped( planes[3] ) ) ) { - Selector_add( selector, m_selectable_back ); - } - if ( selectedPlanes.contains( plane3_flipped( planes[4] ) ) ) { - Selector_add( selector, m_selectable_top ); - } - if ( selectedPlanes.contains( plane3_flipped( planes[5] ) ) ) { - Selector_add( selector, m_selectable_bottom ); - } -} -void translate( const Vector3& translation ){ - if ( m_dragPlanesExtents[0] != 0 ) { - if ( m_selectable_right.isSelected() ) { - m_dragPlanesMax[0] += translation[0]; - //globalOutputStream() << "moving right\n"; - } - if ( m_selectable_left.isSelected() ) { - m_dragPlanesMin[0] += translation[0]; - //globalOutputStream() << "moving left\n"; - } - } - if ( m_dragPlanesExtents[1] != 0 ) { - if ( m_selectable_front.isSelected() ) { - m_dragPlanesMax[1] += translation[1]; - //globalOutputStream() << "moving front\n"; - } - if ( m_selectable_back.isSelected() ) { - m_dragPlanesMin[1] += translation[1]; - //globalOutputStream() << "moving back\n"; - } - } - if ( m_dragPlanesExtents[2] != 0 ) { - if ( m_selectable_top.isSelected() ) { - m_dragPlanesMax[2] += translation[2]; - //globalOutputStream() << "moving top\n"; - } - if ( m_selectable_bottom.isSelected() ) { - m_dragPlanesMin[2] += translation[2]; - //globalOutputStream() << "moving bottom\n"; - } - } -} -Matrix4 evaluateTransform() const { - Vector3 originTransformed( vector3_mid( m_dragPlanesMin, m_dragPlanesMax ) ); - Vector3 scale( vector3_scaled( vector3_subtracted( m_dragPlanesMax, m_dragPlanesMin ), 0.5 ) ); - - if ( m_dragPlanesExtents[0] != 0 ) { - scale[0] /= m_dragPlanesExtents[0]; - } - else - { - scale[0] = 1; - } - if ( m_dragPlanesExtents[1] != 0 ) { - scale[1] /= m_dragPlanesExtents[1]; - } - else - { - scale[1] = 1; - } - if ( m_dragPlanesExtents[2] != 0 ) { - scale[2] /= m_dragPlanesExtents[2]; - } - else - { - scale[2] = 1; - } - - Matrix4 matrix( matrix4_translation_for_vec3( originTransformed - m_dragPlanesOrigin ) ); - matrix4_pivoted_scale_by_vec3( matrix, scale, m_dragPlanesOrigin ); - - return matrix; -} -}; - -#endif diff --git a/tools/urt/libs/eclasslib.cpp b/tools/urt/libs/eclasslib.cpp deleted file mode 100644 index 860a888..0000000 --- a/tools/urt/libs/eclasslib.cpp +++ /dev/null @@ -1,2 +0,0 @@ - -#include "eclasslib.h" diff --git a/tools/urt/libs/eclasslib.h b/tools/urt/libs/eclasslib.h deleted file mode 100644 index e7d8788..0000000 --- a/tools/urt/libs/eclasslib.h +++ /dev/null @@ -1,286 +0,0 @@ - -#if !defined ( INCLUDED_ECLASSLIB_H ) -#define INCLUDED_ECLASSLIB_H - -#include -#include -#include -#include -#include - -#include "ieclass.h" -#include "irender.h" - -#include "math/vector.h" -#include "string/string.h" - -typedef Vector3 Colour3; - -class ListAttributeType -{ -typedef std::pair ListItem; -typedef std::vector ListItems; -ListItems m_items; -public: - -typedef ListItems::const_iterator const_iterator; -const_iterator begin() const { - return m_items.begin(); -} -const_iterator end() const { - return m_items.end(); -} - -const ListItem& operator[]( std::size_t i ) const { - return m_items[i]; -} -const_iterator findValue( const char* value ) const { - for ( ListItems::const_iterator i = m_items.begin(); i != m_items.end(); ++i ) - { - if ( string_equal( value, ( *i ).second.c_str() ) ) { - return i; - } - } - return m_items.end(); -} - -void push_back( const char* name, const char* value ){ - m_items.push_back( ListItems::value_type( name, value ) ); -} -}; - -class EntityClassAttribute -{ -public: -CopiedString m_type; -CopiedString m_name; -CopiedString m_value; -CopiedString m_description; -EntityClassAttribute(){ -} -EntityClassAttribute( const char* type, const char* name, const char* value = "", const char* description = "" ) : m_type( type ), m_name( name ), m_value( value ), m_description( description ){ -} -}; - -typedef std::pair EntityClassAttributePair; -typedef std::list EntityClassAttributes; -typedef std::list StringList; - -inline const char* EntityClassAttributePair_getName( const EntityClassAttributePair& attributePair ){ - if ( !string_empty( attributePair.second.m_name.c_str() ) ) { - return attributePair.second.m_name.c_str(); - } - return attributePair.first.c_str(); -} - -inline const char* EntityClassAttributePair_getDescription( const EntityClassAttributePair& attributePair ){ - if ( !string_empty( attributePair.second.m_description.c_str() ) ) { - return attributePair.second.m_description.c_str(); - } - return EntityClassAttributePair_getName( attributePair ); -} - -class EntityClass -{ -public: -CopiedString m_name; -StringList m_parent; -bool fixedsize; -bool unknown; // wasn't found in source -Vector3 mins; -Vector3 maxs; - -Colour3 color; -Shader* m_state_fill; -Shader* m_state_wire; -Shader* m_state_blend; - -CopiedString m_comments; -char flagnames[MAX_FLAGS][32]; - -CopiedString m_modelpath; -CopiedString m_skin; - -void ( *free )( EntityClass* ); - -EntityClassAttributes m_attributes; - -bool inheritanceResolved; -bool sizeSpecified; -bool colorSpecified; - -const char* name() const { - return m_name.c_str(); -} -const char* comments() const { - return m_comments.c_str(); -} -const char* modelpath() const { - return m_modelpath.c_str(); -} -const char* skin() const { - return m_skin.c_str(); -} -}; - -inline const char* EntityClass_valueForKey( const EntityClass& entityClass, const char* key ){ - for ( EntityClassAttributes::const_iterator i = entityClass.m_attributes.begin(); i != entityClass.m_attributes.end(); ++i ) - { - if ( string_equal( key, ( *i ).first.c_str() ) ) { - return ( *i ).second.m_value.c_str(); - } - } - return ""; -} - -inline EntityClassAttributePair& EntityClass_insertAttribute( EntityClass& entityClass, const char* key, const EntityClassAttribute& attribute = EntityClassAttribute() ){ - entityClass.m_attributes.push_back( EntityClassAttributePair( key, attribute ) ); - return entityClass.m_attributes.back(); -} - - -inline void buffer_write_colour_fill( char buffer[128], const Colour3& colour ){ - sprintf( buffer, "(%g %g %g)", colour[0], colour[1], colour[2] ); -} - -inline void buffer_write_colour_wire( char buffer[128], const Colour3& colour ){ - sprintf( buffer, "<%g %g %g>", colour[0], colour[1], colour[2] ); -} - -inline void buffer_write_colour_blend( char buffer[128], const Colour3& colour ){ - sprintf( buffer, "[%g %g %g]", colour[0], colour[1], colour[2] ); -} - -inline Shader* colour_capture_state_fill( const Colour3& colour ){ - char buffer[128]; - buffer_write_colour_fill( buffer, colour ); - return GlobalShaderCache().capture( buffer ); -} - -inline void colour_release_state_fill( const Colour3& colour ){ - char buffer[128]; - buffer_write_colour_fill( buffer, colour ); - GlobalShaderCache().release( buffer ); -} - -inline Shader* colour_capture_state_wire( const Colour3& colour ){ - char buffer[128]; - buffer_write_colour_wire( buffer, colour ); - return GlobalShaderCache().capture( buffer ); -} - -inline void colour_release_state_wire( const Colour3& colour ){ - char buffer[128]; - buffer_write_colour_wire( buffer, colour ); - GlobalShaderCache().release( buffer ); -} - -inline Shader* colour_capture_state_blend( const Colour3& colour ){ - char buffer[128]; - buffer_write_colour_blend( buffer, colour ); - return GlobalShaderCache().capture( buffer ); -} - -inline void colour_release_state_blend( const Colour3& colour ){ - char buffer[128]; - buffer_write_colour_blend( buffer, colour ); - GlobalShaderCache().release( buffer ); -} - -inline void eclass_capture_state( EntityClass* eclass ){ - eclass->m_state_fill = colour_capture_state_fill( eclass->color ); - eclass->m_state_wire = colour_capture_state_wire( eclass->color ); - eclass->m_state_blend = colour_capture_state_blend( eclass->color ); -} - -inline void eclass_release_state( EntityClass* eclass ){ - colour_release_state_fill( eclass->color ); - colour_release_state_wire( eclass->color ); - colour_release_state_blend( eclass->color ); -} - -// eclass constructor -inline EntityClass* Eclass_Alloc(){ - EntityClass* e = new EntityClass; - - e->fixedsize = false; - e->unknown = false; - memset( e->flagnames, 0, MAX_FLAGS * 32 ); - - e->maxs = Vector3( -1,-1,-1 ); - e->mins = Vector3( 1, 1, 1 ); - - e->free = 0; - - e->inheritanceResolved = true; - e->sizeSpecified = false; - e->colorSpecified = false; - - return e; -} - -// eclass destructor -inline void Eclass_Free( EntityClass* e ){ - eclass_release_state( e ); - - delete e; -} - -inline bool classname_equal( const char* classname, const char* other ){ - return string_equal( classname, other ); -} - -inline EntityClass* EClass_Create( const char* name, const Vector3& colour, const char* comments ){ - EntityClass *e = Eclass_Alloc(); - e->free = &Eclass_Free; - - e->m_name = name; - - e->color = colour; - eclass_capture_state( e ); - - if ( comments ) { - e->m_comments = comments; - } - - return e; -} - -inline EntityClass* EClass_Create_FixedSize( const char* name, const Vector3& colour, const Vector3& mins, const Vector3& maxs, const char* comments ){ - EntityClass *e = Eclass_Alloc(); - e->free = &Eclass_Free; - - e->m_name = name; - - e->color = colour; - eclass_capture_state( e ); - - e->fixedsize = true; - - e->mins = mins; - e->maxs = maxs; - - if ( comments ) { - e->m_comments = comments; - } - - return e; -} - -const Vector3 smallbox[2] = { - Vector3( -8,-8,-8 ), - Vector3( 8, 8, 8 ), -}; - -inline EntityClass *EntityClass_Create_Default( const char *name, bool has_brushes ){ - // create a new class for it - if ( has_brushes ) { - return EClass_Create( name, Vector3( 0.0f, 0.5f, 0.0f ), "Not found in source." ); - } - else - { - return EClass_Create_FixedSize( name, Vector3( 0.0f, 0.5f, 0.0f ), smallbox[0], smallbox[1], "Not found in source." ); - } -} - -#endif diff --git a/tools/urt/libs/entitylib.cpp b/tools/urt/libs/entitylib.cpp deleted file mode 100644 index 646c6e3..0000000 --- a/tools/urt/libs/entitylib.cpp +++ /dev/null @@ -1,2 +0,0 @@ - -#include "entitylib.h" diff --git a/tools/urt/libs/entitylib.h b/tools/urt/libs/entitylib.h deleted file mode 100644 index c9b107b..0000000 --- a/tools/urt/libs/entitylib.h +++ /dev/null @@ -1,650 +0,0 @@ - -#if !defined ( INCLUDED_ENTITYLIB_H ) -#define INCLUDED_ENTITYLIB_H - -#include "ireference.h" -#include "debugging/debugging.h" - -#include "ientity.h" -#include "irender.h" -#include "igl.h" -#include "selectable.h" - -#include "generic/callback.h" -#include "math/vector.h" -#include "math/aabb.h" -#include "undolib.h" -#include "string/string.h" -#include "generic/referencecounted.h" -#include "scenelib.h" -#include "container/container.h" -#include "eclasslib.h" - -#include -#include - -inline void arrow_draw( const Vector3& origin, const Vector3& direction ){ - Vector3 up( 0, 0, 1 ); - Vector3 left( -direction[1], direction[0], 0 ); - - Vector3 endpoint( vector3_added( origin, vector3_scaled( direction, 32.0 ) ) ); - - Vector3 tip1( vector3_added( vector3_added( endpoint, vector3_scaled( direction, -8.0 ) ), vector3_scaled( up, -4.0 ) ) ); - Vector3 tip2( vector3_added( tip1, vector3_scaled( up, 8.0 ) ) ); - Vector3 tip3( vector3_added( vector3_added( endpoint, vector3_scaled( direction, -8.0 ) ), vector3_scaled( left, -4.0 ) ) ); - Vector3 tip4( vector3_added( tip3, vector3_scaled( left, 8.0 ) ) ); - - glBegin( GL_LINES ); - - glVertex3fv( vector3_to_array( origin ) ); - glVertex3fv( vector3_to_array( endpoint ) ); - - glVertex3fv( vector3_to_array( endpoint ) ); - glVertex3fv( vector3_to_array( tip1 ) ); - - glVertex3fv( vector3_to_array( endpoint ) ); - glVertex3fv( vector3_to_array( tip2 ) ); - - glVertex3fv( vector3_to_array( endpoint ) ); - glVertex3fv( vector3_to_array( tip3 ) ); - - glVertex3fv( vector3_to_array( endpoint ) ); - glVertex3fv( vector3_to_array( tip4 ) ); - - glVertex3fv( vector3_to_array( tip1 ) ); - glVertex3fv( vector3_to_array( tip3 ) ); - - glVertex3fv( vector3_to_array( tip3 ) ); - glVertex3fv( vector3_to_array( tip2 ) ); - - glVertex3fv( vector3_to_array( tip2 ) ); - glVertex3fv( vector3_to_array( tip4 ) ); - - glVertex3fv( vector3_to_array( tip4 ) ); - glVertex3fv( vector3_to_array( tip1 ) ); - - glEnd(); -} - -class SelectionIntersection; - -inline void aabb_testselect( const AABB& aabb, SelectionTest& test, SelectionIntersection& best ){ - const IndexPointer::index_type indices[24] = { - 2, 1, 5, 6, - 1, 0, 4, 5, - 0, 1, 2, 3, - 3, 7, 4, 0, - 3, 2, 6, 7, - 7, 6, 5, 4, - }; - - Vector3 points[8]; - aabb_corners( aabb, points ); - test.TestQuads( VertexPointer( reinterpret_cast( points ), sizeof( Vector3 ) ), IndexPointer( indices, 24 ), best ); -} - -inline void aabb_draw_wire( const Vector3 points[8] ){ - typedef std::size_t index_t; - index_t indices[24] = { - 0, 1, 1, 2, 2, 3, 3, 0, - 4, 5, 5, 6, 6, 7, 7, 4, - 0, 4, 1, 5, 2, 6, 3, 7, - }; -#if 1 - glVertexPointer( 3, GL_FLOAT, 0, points ); - glDrawElements( GL_LINES, sizeof( indices ) / sizeof( index_t ), GL_UNSIGNED_INT, indices ); -#else - glBegin( GL_LINES ); - for ( std::size_t i = 0; i < sizeof( indices ) / sizeof( index_t ); ++i ) - { - glVertex3fv( points[indices[i]] ); - } - glEnd(); -#endif -} - -inline void aabb_draw_flatshade( const Vector3 points[8] ){ - glBegin( GL_QUADS ); - - glNormal3fv( vector3_to_array( aabb_normals[0] ) ); - glVertex3fv( vector3_to_array( points[2] ) ); - glVertex3fv( vector3_to_array( points[1] ) ); - glVertex3fv( vector3_to_array( points[5] ) ); - glVertex3fv( vector3_to_array( points[6] ) ); - - glNormal3fv( vector3_to_array( aabb_normals[1] ) ); - glVertex3fv( vector3_to_array( points[1] ) ); - glVertex3fv( vector3_to_array( points[0] ) ); - glVertex3fv( vector3_to_array( points[4] ) ); - glVertex3fv( vector3_to_array( points[5] ) ); - - glNormal3fv( vector3_to_array( aabb_normals[2] ) ); - glVertex3fv( vector3_to_array( points[0] ) ); - glVertex3fv( vector3_to_array( points[1] ) ); - glVertex3fv( vector3_to_array( points[2] ) ); - glVertex3fv( vector3_to_array( points[3] ) ); - - glNormal3fv( vector3_to_array( aabb_normals[3] ) ); - glVertex3fv( vector3_to_array( points[0] ) ); - glVertex3fv( vector3_to_array( points[3] ) ); - glVertex3fv( vector3_to_array( points[7] ) ); - glVertex3fv( vector3_to_array( points[4] ) ); - - glNormal3fv( vector3_to_array( aabb_normals[4] ) ); - glVertex3fv( vector3_to_array( points[3] ) ); - glVertex3fv( vector3_to_array( points[2] ) ); - glVertex3fv( vector3_to_array( points[6] ) ); - glVertex3fv( vector3_to_array( points[7] ) ); - - glNormal3fv( vector3_to_array( aabb_normals[5] ) ); - glVertex3fv( vector3_to_array( points[7] ) ); - glVertex3fv( vector3_to_array( points[6] ) ); - glVertex3fv( vector3_to_array( points[5] ) ); - glVertex3fv( vector3_to_array( points[4] ) ); - - glEnd(); -} - -inline void aabb_draw_wire( const AABB& aabb ){ - Vector3 points[8]; - aabb_corners( aabb, points ); - aabb_draw_wire( points ); -} - -inline void aabb_draw_flatshade( const AABB& aabb ){ - Vector3 points[8]; - aabb_corners( aabb, points ); - aabb_draw_flatshade( points ); -} - -inline void aabb_draw_textured( const AABB& aabb ){ - Vector3 points[8]; - aabb_corners( aabb, points ); - - glBegin( GL_QUADS ); - - glNormal3fv( vector3_to_array( aabb_normals[0] ) ); - glTexCoord2fv( aabb_texcoord_topleft ); - glVertex3fv( vector3_to_array( points[2] ) ); - glTexCoord2fv( aabb_texcoord_topright ); - glVertex3fv( vector3_to_array( points[1] ) ); - glTexCoord2fv( aabb_texcoord_botright ); - glVertex3fv( vector3_to_array( points[5] ) ); - glTexCoord2fv( aabb_texcoord_botleft ); - glVertex3fv( vector3_to_array( points[6] ) ); - - glNormal3fv( vector3_to_array( aabb_normals[1] ) ); - glTexCoord2fv( aabb_texcoord_topleft ); - glVertex3fv( vector3_to_array( points[1] ) ); - glTexCoord2fv( aabb_texcoord_topright ); - glVertex3fv( vector3_to_array( points[0] ) ); - glTexCoord2fv( aabb_texcoord_botright ); - glVertex3fv( vector3_to_array( points[4] ) ); - glTexCoord2fv( aabb_texcoord_botleft ); - glVertex3fv( vector3_to_array( points[5] ) ); - - glNormal3fv( vector3_to_array( aabb_normals[2] ) ); - glTexCoord2fv( aabb_texcoord_topleft ); - glVertex3fv( vector3_to_array( points[0] ) ); - glTexCoord2fv( aabb_texcoord_topright ); - glVertex3fv( vector3_to_array( points[1] ) ); - glTexCoord2fv( aabb_texcoord_botright ); - glVertex3fv( vector3_to_array( points[2] ) ); - glTexCoord2fv( aabb_texcoord_botleft ); - glVertex3fv( vector3_to_array( points[3] ) ); - - glNormal3fv( vector3_to_array( aabb_normals[3] ) ); - glTexCoord2fv( aabb_texcoord_topleft ); - glVertex3fv( vector3_to_array( points[0] ) ); - glTexCoord2fv( aabb_texcoord_topright ); - glVertex3fv( vector3_to_array( points[3] ) ); - glTexCoord2fv( aabb_texcoord_botright ); - glVertex3fv( vector3_to_array( points[7] ) ); - glTexCoord2fv( aabb_texcoord_botleft ); - glVertex3fv( vector3_to_array( points[4] ) ); - - glNormal3fv( vector3_to_array( aabb_normals[4] ) ); - glTexCoord2fv( aabb_texcoord_topleft ); - glVertex3fv( vector3_to_array( points[3] ) ); - glTexCoord2fv( aabb_texcoord_topright ); - glVertex3fv( vector3_to_array( points[2] ) ); - glTexCoord2fv( aabb_texcoord_botright ); - glVertex3fv( vector3_to_array( points[6] ) ); - glTexCoord2fv( aabb_texcoord_botleft ); - glVertex3fv( vector3_to_array( points[7] ) ); - - glNormal3fv( vector3_to_array( aabb_normals[5] ) ); - glTexCoord2fv( aabb_texcoord_topleft ); - glVertex3fv( vector3_to_array( points[7] ) ); - glTexCoord2fv( aabb_texcoord_topright ); - glVertex3fv( vector3_to_array( points[6] ) ); - glTexCoord2fv( aabb_texcoord_botright ); - glVertex3fv( vector3_to_array( points[5] ) ); - glTexCoord2fv( aabb_texcoord_botleft ); - glVertex3fv( vector3_to_array( points[4] ) ); - - glEnd(); -} - -inline void aabb_draw_solid( const AABB& aabb, RenderStateFlags state ){ - if ( state & RENDER_TEXTURE ) { - aabb_draw_textured( aabb ); - } - else - { - aabb_draw_flatshade( aabb ); - } -} - -inline void aabb_draw( const AABB& aabb, RenderStateFlags state ){ - if ( state & RENDER_FILL ) { - aabb_draw_solid( aabb, state ); - } - else - { - aabb_draw_wire( aabb ); - } -} - -class RenderableSolidAABB : public OpenGLRenderable -{ -const AABB& m_aabb; -public: -RenderableSolidAABB( const AABB& aabb ) : m_aabb( aabb ){ -} -void render( RenderStateFlags state ) const { - aabb_draw_solid( m_aabb, state ); -} -}; - -class RenderableWireframeAABB : public OpenGLRenderable -{ -const AABB& m_aabb; -public: -RenderableWireframeAABB( const AABB& aabb ) : m_aabb( aabb ){ -} -void render( RenderStateFlags state ) const { - aabb_draw_wire( m_aabb ); -} -}; - - -typedef Callback1 KeyObserver; - -/// \brief A key/value pair of strings. -/// -/// - Notifies observers when value changes - value changes to "" on destruction. -/// - Provides undo support through the global undo system. -class KeyValue -{ -typedef UnsortedSet KeyObservers; - -std::size_t m_refcount; -KeyObservers m_observers; -CopiedString m_string; -const char* m_empty; -ObservedUndoableObject m_undo; -static EntityCreator::KeyValueChangedFunc m_entityKeyValueChanged; -public: - -KeyValue( const char* string, const char* empty ) - : m_refcount( 0 ), m_string( string ), m_empty( empty ), m_undo( m_string, UndoImportCaller( *this ) ){ - notify(); -} -~KeyValue(){ - ASSERT_MESSAGE( m_observers.empty(), "KeyValue::~KeyValue: observers still attached" ); -} - -static void setKeyValueChangedFunc( EntityCreator::KeyValueChangedFunc func ){ - m_entityKeyValueChanged = func; -} - -void IncRef(){ - ++m_refcount; -} -void DecRef(){ - if ( --m_refcount == 0 ) { - delete this; - } -} - -void instanceAttach( MapFile* map ){ - m_undo.instanceAttach( map ); -} -void instanceDetach( MapFile* map ){ - m_undo.instanceDetach( map ); -} - -void attach( const KeyObserver& observer ){ - ( *m_observers.insert ( observer ) )( c_str() ); -} -void detach( const KeyObserver& observer ){ - observer( m_empty ); - m_observers.erase( observer ); -} -const char* c_str() const { - if ( string_empty( m_string.c_str() ) ) { - return m_empty; - } - return m_string.c_str(); -} -void assign( const char* other ){ - if ( !string_equal( m_string.c_str(), other ) ) { - m_undo.save(); - m_string = other; - notify(); - } -} - -void notify(){ - m_entityKeyValueChanged(); - KeyObservers::reverse_iterator i = m_observers.rbegin(); - while ( i != m_observers.rend() ) - { - ( *i++ )( c_str() ); - } -} - -void importState( const CopiedString& string ){ - m_string = string; - - notify(); -} -typedef MemberCaller1 UndoImportCaller; -}; - -/// \brief An unsorted list of key/value pairs. -/// -/// - Notifies observers when a pair is inserted or removed. -/// - Provides undo support through the global undo system. -/// - New keys are appended to the end of the list. -class EntityKeyValues : public Entity -{ -public: - typedef KeyValue Value; - - class Observer - { -public: - virtual void insert( const char* key, Value& value ) = 0; - virtual void erase( const char* key, Value& value ) = 0; - }; - -private: - static EntityCreator::KeyValueChangedFunc m_entityKeyValueChanged; - static Counter* m_counter; - - EntityClass* m_eclass; - - typedef SmartPointer KeyValuePtr; - typedef UnsortedMap KeyValues; - KeyValues m_keyValues; - - typedef UnsortedSet Observers; - Observers m_observers; - - ObservedUndoableObject m_undo; - bool m_instanced; - - bool m_observerMutex; - - void notifyInsert( const char* key, Value& value ){ - m_observerMutex = true; - for ( Observers::iterator i = m_observers.begin(); i != m_observers.end(); ++i ) - { - ( *i )->insert( key, value ); - } - m_observerMutex = false; - } - void notifyErase( const char* key, Value& value ){ - m_observerMutex = true; - for ( Observers::iterator i = m_observers.begin(); i != m_observers.end(); ++i ) - { - ( *i )->erase( key, value ); - } - m_observerMutex = false; - } - void forEachKeyValue_notifyInsert(){ - for ( KeyValues::const_iterator i = m_keyValues.begin(); i != m_keyValues.end(); ++i ) - { - notifyInsert( ( *i ).first.c_str(), *( *i ).second ); - } - } - void forEachKeyValue_notifyErase(){ - for ( KeyValues::const_iterator i = m_keyValues.begin(); i != m_keyValues.end(); ++i ) - { - notifyErase( ( *i ).first.c_str(), *( *i ).second ); - } - } - - void insert( const char* key, const KeyValuePtr& keyValue ){ - KeyValues::iterator i = m_keyValues.insert( KeyValues::value_type( key, keyValue ) ); - notifyInsert( key, *( *i ).second ); - - if ( m_instanced ) { - ( *i ).second->instanceAttach( m_undo.map() ); - } - } - - void insert( const char* key, const char* value ){ - KeyValues::iterator i = m_keyValues.find( key ); - if ( i != m_keyValues.end() ) { - ( *i ).second->assign( value ); - } - else - { - m_undo.save(); - insert( key, KeyValuePtr( new KeyValue( value, EntityClass_valueForKey( *m_eclass, key ) ) ) ); - } - } - - void erase( KeyValues::iterator i ){ - if ( m_instanced ) { - ( *i ).second->instanceDetach( m_undo.map() ); - } - - CopiedString key( ( *i ).first ); - KeyValuePtr value( ( *i ).second ); - m_keyValues.erase( i ); - notifyErase( key.c_str(), *value ); - } - - void erase( const char* key ){ - KeyValues::iterator i = m_keyValues.find( key ); - if ( i != m_keyValues.end() ) { - m_undo.save(); - erase( i ); - } - } - -public: - EntityKeyValues( EntityClass* eclass ) : - m_eclass( eclass ), - m_undo( m_keyValues, UndoImportCaller( *this ) ), - m_instanced( false ), - m_observerMutex( false ){ - } - EntityKeyValues( const EntityKeyValues& other ) : - Entity( other ), - m_eclass( &other.getEntityClass() ), - m_undo( m_keyValues, UndoImportCaller( *this ) ), - m_instanced( false ), - m_observerMutex( false ){ - for ( KeyValues::const_iterator i = other.m_keyValues.begin(); i != other.m_keyValues.end(); ++i ) - { - insert( ( *i ).first.c_str(), ( *i ).second->c_str() ); - } - } - ~EntityKeyValues(){ - ASSERT_MESSAGE( m_observers.empty(), "EntityKeyValues::~EntityKeyValues: observers still attached" ); - } - - static void setKeyValueChangedFunc( EntityCreator::KeyValueChangedFunc func ){ - m_entityKeyValueChanged = func; - KeyValue::setKeyValueChangedFunc( func ); - } - static void setCounter( Counter* counter ){ - m_counter = counter; - } - - void importState( const KeyValues& keyValues ){ - for ( KeyValues::iterator i = m_keyValues.begin(); i != m_keyValues.end(); ) - { - erase( i++ ); - } - - for ( KeyValues::const_iterator i = keyValues.begin(); i != keyValues.end(); ++i ) - { - insert( ( *i ).first.c_str(), ( *i ).second ); - } - - m_entityKeyValueChanged(); - } - typedef MemberCaller1 UndoImportCaller; - - void attach( Observer& observer ){ - ASSERT_MESSAGE( !m_observerMutex, "observer cannot be attached during iteration" ); - m_observers.insert( &observer ); - for ( KeyValues::const_iterator i = m_keyValues.begin(); i != m_keyValues.end(); ++i ) - { - observer.insert( ( *i ).first.c_str(), *( *i ).second ); - } - } - void detach( Observer& observer ){ - ASSERT_MESSAGE( !m_observerMutex, "observer cannot be detached during iteration" ); - m_observers.erase( &observer ); - for ( KeyValues::const_iterator i = m_keyValues.begin(); i != m_keyValues.end(); ++i ) - { - observer.erase( ( *i ).first.c_str(), *( *i ).second ); - } - } - - void forEachKeyValue_instanceAttach( MapFile* map ){ - for ( KeyValues::const_iterator i = m_keyValues.begin(); i != m_keyValues.end(); ++i ) - { - ( *i ).second->instanceAttach( map ); - } - } - void forEachKeyValue_instanceDetach( MapFile* map ){ - for ( KeyValues::const_iterator i = m_keyValues.begin(); i != m_keyValues.end(); ++i ) - { - ( *i ).second->instanceDetach( map ); - } - } - - void instanceAttach( MapFile* map ){ - if ( m_counter != 0 ) { - m_counter->increment(); - } - - m_instanced = true; - forEachKeyValue_instanceAttach( map ); - m_undo.instanceAttach( map ); - } - void instanceDetach( MapFile* map ){ - if ( m_counter != 0 ) { - m_counter->decrement(); - } - - m_undo.instanceDetach( map ); - forEachKeyValue_instanceDetach( map ); - m_instanced = false; - } - - // entity - EntityClass& getEntityClass() const { - return *m_eclass; - } - void forEachKeyValue( Visitor& visitor ) const { - for ( KeyValues::const_iterator i = m_keyValues.begin(); i != m_keyValues.end(); ++i ) - { - visitor.visit( ( *i ).first.c_str(), ( *i ).second->c_str() ); - } - } - void setKeyValue( const char* key, const char* value ){ - if ( value[0] == '\0' - /*|| string_equal(EntityClass_valueForKey(*m_eclass, key), value)*/ ) { // don't delete values equal to default - erase( key ); - } - else - { - insert( key, value ); - } - m_entityKeyValueChanged(); - } - const char* getKeyValue( const char* key ) const { - KeyValues::const_iterator i = m_keyValues.find( key ); - if ( i != m_keyValues.end() ) { - return ( *i ).second->c_str(); - } - - return EntityClass_valueForKey( *m_eclass, key ); - } -}; - -/// \brief A Resource reference with a controlled lifetime. -/// \brief The resource is released when the ResourceReference is destroyed. -class ResourceReference -{ - CopiedString m_name; - Resource* m_resource; -public: - ResourceReference( const char* name ) - : m_name( name ){ - capture(); - } - ResourceReference( const ResourceReference& other ) - : m_name( other.m_name ){ - capture(); - } - ResourceReference& operator=( const ResourceReference& other ){ - ResourceReference tmp( other ); - tmp.swap( *this ); - return *this; - } - ~ResourceReference(){ - release(); - } - - void capture(){ - m_resource = GlobalReferenceCache().capture( m_name.c_str() ); - } - void release(){ - GlobalReferenceCache().release( m_name.c_str() ); - } - - const char* getName() const { - return m_name.c_str(); - } - void setName( const char* name ){ - ResourceReference tmp( name ); - tmp.swap( *this ); - } - - void swap( ResourceReference& other ){ - std::swap( m_resource, other.m_resource ); - std::swap( m_name, other.m_name ); - } - - void attach( ModuleObserver& observer ){ - m_resource->attach( observer ); - } - void detach( ModuleObserver& observer ){ - m_resource->detach( observer ); - } - - Resource* get(){ - return m_resource; - } -}; - -namespace std -{ - /// \brief Swaps the values of \p self and \p other. - /// Overloads std::swap. - inline void swap( ResourceReference& self, ResourceReference& other ){ - self.swap( other ); - } -} - -#endif diff --git a/tools/urt/libs/entityxml.cpp b/tools/urt/libs/entityxml.cpp deleted file mode 100644 index da63491..0000000 --- a/tools/urt/libs/entityxml.cpp +++ /dev/null @@ -1,2 +0,0 @@ - -#include "entityxml.h" diff --git a/tools/urt/libs/entityxml.h b/tools/urt/libs/entityxml.h deleted file mode 100644 index f849a75..0000000 --- a/tools/urt/libs/entityxml.h +++ /dev/null @@ -1,78 +0,0 @@ - -#if !defined( INCLUDED_ENTITYXML_H ) -#define INCLUDED_ENTITYXML_H - -#include "ientity.h" -#include "xml/ixml.h" -#include "xml/xmlelement.h" - -class entity_import : public XMLImporter -{ -Entity& m_entity; -public: -entity_import( Entity& entity ) - : m_entity( entity ){ -} -void pushElement( const XMLElement& element ){ - if ( strcmp( element.name(), "epair" ) == 0 ) { - m_entity.setKeyValue( element.attribute( "key" ), element.attribute( "value" ) ); - } -} -void popElement( const char* name ){ -} -std::size_t write( const char* data, std::size_t length ){ - return length; -} -}; - -class entity_export : public XMLExporter -{ -class ExportXMLVisitor : public Entity::Visitor -{ -XMLImporter& m_importer; -public: -ExportXMLVisitor( XMLImporter& importer ) : m_importer( importer ){ -} -void visit( const char* key, const char* value ){ - StaticElement element( "epair" ); - element.insertAttribute( "key", key ); - element.insertAttribute( "value", value ); - m_importer.pushElement( element ); - m_importer.popElement( element.name() ); -} -}; - -const Entity& m_entity; - -public: -entity_export( const Entity& entity ) : m_entity( entity ){ -} -void exportXML( XMLImporter& observer ){ - ExportXMLVisitor visitor( observer ); - - m_entity.forEachKeyValue( visitor ); -} -}; - -inline void entity_copy( Entity& entity, const Entity& other ){ - entity_export exporter( other ); - entity_import importer( entity ); - exporter.exportXML( importer ); -} - -template -class EntityConstruction -{ -public: -typedef EntityClass* type; -static type get( const EntityType& entity ){ - return &entity.getEntity().getEntityClass(); -} -static void copy( EntityType& entity, const EntityType& other ){ - entity_copy( entity.getEntity(), other.getEntity() ); -} -}; - - - -#endif diff --git a/tools/urt/libs/fs_filesystem.cpp b/tools/urt/libs/fs_filesystem.cpp deleted file mode 100644 index 67cec49..0000000 --- a/tools/urt/libs/fs_filesystem.cpp +++ /dev/null @@ -1,2 +0,0 @@ - -#include "fs_filesystem.h" diff --git a/tools/urt/libs/fs_filesystem.h b/tools/urt/libs/fs_filesystem.h deleted file mode 100644 index f7cd3b6..0000000 --- a/tools/urt/libs/fs_filesystem.h +++ /dev/null @@ -1,138 +0,0 @@ - -#if !defined( INCLUDED_FS_FILESYSTEM_H ) -#define INCLUDED_FS_FILESYSTEM_H - -#include "string/string.h" -#include "os/path.h" - -#include - -inline unsigned int path_get_depth( const char* path ){ - unsigned int depth = 0; - while ( path != 0 && path[0] != '\0' ) - { - path = strchr( path, '/' ); - if ( path != 0 ) { - ++path; - } - ++depth; - } - return depth; -} - -/// \brief A generic unix-style file-system which maps paths to files and directories. -/// Provides average O(log n) find and insert methods. -/// \param file_type The data type which represents a file. -template -class GenericFileSystem -{ -class Path -{ -CopiedString m_path; -unsigned int m_depth; -public: -Path( const char* path ) - : m_path( path ), m_depth( path_get_depth( c_str() ) ){ -} -Path( const char* start, const char* finish ) - : m_path( start, finish ), m_depth( path_get_depth( c_str() ) ){ -} -bool operator<( const Path& other ) const { - return string_less_nocase( c_str(), other.c_str() ); -} -unsigned int depth() const { - return m_depth; -} -const char* c_str() const { - return m_path.c_str(); -} -}; - -class Entry -{ -file_type* m_file; -public: -Entry( file_type* file ) - : m_file( file ){ -} -file_type* file() const { - return m_file; -} -bool is_directory() const { - return file() == 0; -} -}; - -typedef std::map Entries; -Entries m_entries; - -public: -typedef typename Entries::iterator iterator; -typedef typename Entries::value_type value_type; - -iterator begin(){ - return m_entries.begin(); -} -iterator end(){ - return m_entries.end(); -} - -/// \brief Adds the file \p entry at \p path. -/// Creates all directories below \p path if they do not exist. -/// O(log n) on average. -void insert( const Path& path, const Entry& entry ){ - { - const char* end = path_remove_directory( path.c_str() ); - while ( end[0] != '\0' ) - { - Path dir( path.c_str(), end ); - m_entries.insert( value_type( dir, Entry( 0 ) ) ); - end = path_remove_directory( end ); - } - } - - m_entries.insert( value_type( path, entry ) ); -} - -/// \brief Returns the file at \p path or end() if not found. -iterator find( const Path& path ){ - return m_entries.find( path ); -} - -iterator begin( const char* root ){ - if ( root[0] == '\0' ) { - return m_entries.begin(); - } - iterator i = m_entries.find( root ); - if ( i == m_entries.end() ) { - return i; - } - return ++i; -} - -/// \brief Performs a depth-first traversal of the file-system subtree rooted at \p root. -/// Traverses the entire tree if \p root is "". -/// Calls \p visitor.file() with the path to each file relative to the filesystem root. -/// Calls \p visitor.directory() with the path to each directory relative to the filesystem root. -template -void traverse( visitor_type visitor, const char* root ){ - unsigned int start_depth = path_get_depth( root ); - unsigned int skip_depth = 0; - for ( iterator i = begin( root ); i != end() && i->first.depth() > start_depth; ++i ) - { - if ( i->first.depth() == skip_depth ) { - skip_depth = 0; - } - if ( skip_depth == 0 ) { - if ( !i->second.is_directory() ) { - visitor.file( i->first.c_str() ); - } - else if ( visitor.directory( i->first.c_str(), i->first.depth() - start_depth ) ) { - skip_depth = i->first.depth(); - } - } - } -} -}; - -#endif diff --git a/tools/urt/libs/fs_path.cpp b/tools/urt/libs/fs_path.cpp deleted file mode 100644 index 3dab10b..0000000 --- a/tools/urt/libs/fs_path.cpp +++ /dev/null @@ -1,2 +0,0 @@ - -#include "fs_path.h" diff --git a/tools/urt/libs/fs_path.h b/tools/urt/libs/fs_path.h deleted file mode 100644 index 87d5e54..0000000 --- a/tools/urt/libs/fs_path.h +++ /dev/null @@ -1,62 +0,0 @@ - -#if !defined( INCLUDED_FS_PATH_H ) -#define INCLUDED_FS_PATH_H - -#include "stream/stringstream.h" - -/// \brief A unix-style path string which can be modified at runtime. -/// -/// - Maintains a path ending in a path-separator. -/// - Provides a limited STL-style interface to push and pop file or directory names at the end of the path. -class UnixPath -{ -StringBuffer m_string; - -void check_separator(){ - if ( !empty() && m_string.back() != '/' ) { - m_string.push_back( '/' ); - } -} - -public: -/// \brief Constructs with the directory \p root. -UnixPath( const char* root ) - : m_string( root ){ - check_separator(); -} - -bool empty() const { - return m_string.empty(); -} - -const char* c_str() const { - return m_string.c_str(); -} - -/// \brief Appends the directory \p name. -void push( const char* name ){ - m_string.push_string( name ); - check_separator(); -} -/// \brief Appends the directory [\p first, \p last). -void push( const char* first, const char* last ){ - m_string.push_range( first, last ); - check_separator(); -} -/// \brief Appends the filename \p name. -void push_filename( const char* name ){ - m_string.push_string( name ); -} -/// \brief Removes the last directory or filename appended. -void pop(){ - if ( m_string.back() == '/' ) { - m_string.pop_back(); - } - while ( !empty() && m_string.back() != '/' ) - { - m_string.pop_back(); - } -} -}; - -#endif diff --git a/tools/urt/libs/generic/arrayrange.cpp b/tools/urt/libs/generic/arrayrange.cpp deleted file mode 100644 index 64caaf8..0000000 --- a/tools/urt/libs/generic/arrayrange.cpp +++ /dev/null @@ -1,2 +0,0 @@ - -#include "arrayrange.h" diff --git a/tools/urt/libs/generic/arrayrange.h b/tools/urt/libs/generic/arrayrange.h deleted file mode 100644 index 3c86f61..0000000 --- a/tools/urt/libs/generic/arrayrange.h +++ /dev/null @@ -1,48 +0,0 @@ - -#if !defined( INCLUDED_GENERIC_ARRAYRANGE_H ) -#define INCLUDED_GENERIC_ARRAYRANGE_H - -/// \file -/// \brief Macros for automatically converting a compile-time-sized array to a range. - -template -struct ArrayRange -{ - typedef Element* Iterator; - ArrayRange( Iterator _begin, Iterator _end ) - : begin( _begin ), end( _end ){ - } - Iterator begin; - Iterator end; -}; - -template -inline ArrayRange makeArrayRange( Element* begin, Element* end ){ - return ArrayRange( begin, end ); -} - -template -struct ArrayConstRange -{ - typedef const Element* Iterator; - ArrayConstRange( Iterator _begin, Iterator _end ) - : begin( _begin ), end( _end ){ - } - Iterator begin; - Iterator end; -}; - -template -inline ArrayConstRange makeArrayRange( const Element* begin, const Element* end ){ - return ArrayConstRange( begin, end ); -} - -#define ARRAY_SIZE( array ) ( sizeof( array ) / sizeof( *array ) ) -#define ARRAY_END( array ) ( array + ARRAY_SIZE( array ) ) -#define ARRAY_RANGE( array ) ( makeArrayRange( array, ARRAY_END( array ) ) ) - - -typedef ArrayConstRange StringArrayRange; -#define STRING_ARRAY_RANGE( array ) ( StringArrayRange( array, ARRAY_END( array ) ) ) - -#endif diff --git a/tools/urt/libs/generic/bitfield.cpp b/tools/urt/libs/generic/bitfield.cpp deleted file mode 100644 index e4156f0..0000000 --- a/tools/urt/libs/generic/bitfield.cpp +++ /dev/null @@ -1,2 +0,0 @@ - -#include "bitfield.h" diff --git a/tools/urt/libs/generic/bitfield.h b/tools/urt/libs/generic/bitfield.h deleted file mode 100644 index 10c9ebd..0000000 --- a/tools/urt/libs/generic/bitfield.h +++ /dev/null @@ -1,95 +0,0 @@ - -#if !defined( INCLUDED_GENERIC_BITFIELD_H ) -#define INCLUDED_GENERIC_BITFIELD_H - -/// \file -/// \brief Type safe bitfield. - -/// \brief A bit-field value. -/// -/// - Can be forward-declared when the definition of Enumeration is unknown. -/// - Can only be constructed from valid enumerated values. -/// - Can only be compared and combined with others of the same type. -/// -/// \param Enumeration A type that contains an enum \c Value of the bits that can be set in this field. -template -class BitFieldValue : public Enumeration -{ -unsigned m_value; -protected: -explicit BitFieldValue( unsigned value ) : m_value( value ){ -} -public: -BitFieldValue() : m_value( 0 ){ -} -explicit BitFieldValue( typename Enumeration::Value value ) : m_value( 1 << value ){ -} -unsigned get() const { - return m_value; -} -}; - -template -class BitFieldValueUnsafe : public BitFieldValue -{ -public: -explicit BitFieldValueUnsafe( unsigned value ) : BitFieldValue( value ){ -} -}; - -template -inline bool operator==( BitFieldValue self, BitFieldValue other ){ - return self.get() == other.get(); -} -template -inline bool operator!=( BitFieldValue self, BitFieldValue other ){ - return !operator==( self, other ); -} - -template -inline BitFieldValue operator|( BitFieldValue self, BitFieldValue other ){ - return BitFieldValueUnsafe( self.get() | other.get() ); -} -template -inline BitFieldValue& operator|=( BitFieldValue& self, BitFieldValue other ){ - return self = self | other; -} -template -inline BitFieldValue operator&( BitFieldValue self, BitFieldValue other ){ - return BitFieldValueUnsafe( self.get() & other.get() ); -} -template -inline BitFieldValue& operator&=( BitFieldValue& self, BitFieldValue other ){ - return self = self & other; -} -template -inline BitFieldValue operator~( BitFieldValue self ){ - return BitFieldValueUnsafe( ~self.get() ); -} - - - -inline unsigned int bitfield_enable( unsigned int bitfield, unsigned int mask ){ - return bitfield | mask; -} -inline unsigned int bitfield_disable( unsigned int bitfield, unsigned int mask ){ - return bitfield & ~mask; -} -inline bool bitfield_enabled( unsigned int bitfield, unsigned int mask ){ - return ( bitfield & mask ) != 0; -} - -template -inline BitFieldValue bitfield_enable( BitFieldValue bitfield, BitFieldValue mask ){ - return bitfield | mask; -} -template -inline BitFieldValue bitfield_disable( BitFieldValue bitfield, BitFieldValue mask ){ - return bitfield & ~mask; -} -template -inline bool bitfield_enabled( BitFieldValue bitfield, BitFieldValue mask ){ - return ( bitfield & mask ).get() != 0; -} - -#endif diff --git a/tools/urt/libs/generic/callback.cpp b/tools/urt/libs/generic/callback.cpp deleted file mode 100644 index 065ab7d..0000000 --- a/tools/urt/libs/generic/callback.cpp +++ /dev/null @@ -1,83 +0,0 @@ - -#include "callback.h" - -#if defined( _DEBUG ) || defined( DOXYGEN ) - -namespace ExampleMemberCaller -{ -// MemberCaller example -class Integer -{ -public: -int value; - -void printValue() const { - // print this->value here; -} - -void setValue(){ - value = 3; -} -// a typedef to make things more readable -typedef MemberCaller SetValueCaller; -}; - -void example(){ - Integer foo = { 0 }; - - { - Callback bar = ConstMemberCaller( foo ); - - // invoke the callback - bar(); // foo.printValue() - } - - - { - // use the typedef to improve readability - Callback bar = Integer::SetValueCaller( foo ); - - // invoke the callback - bar(); // foo.setValue() - } -} -// end example -} - -namespace ExampleReferenceCaller -{ -// ReferenceCaller example -void Int_printValue( const int& value ){ - // print value here; -} - -void Int_setValue( int& value ){ - value = 3; -} - -// a typedef to make things more readable -typedef ReferenceCaller IntSetValueCaller; - -void example(){ - int foo = 0; - - { - Callback bar = ConstReferenceCaller( foo ); - - // invoke the callback - bar(); // Int_printValue(foo) - } - - - { - // use the typedef to improve readability - Callback bar = IntSetValueCaller( foo ); - - // invoke the callback - bar(); // Int_setValue(foo) - } -} -// end example -} - -#endif diff --git a/tools/urt/libs/generic/callback.h b/tools/urt/libs/generic/callback.h deleted file mode 100644 index 86b3ef9..0000000 --- a/tools/urt/libs/generic/callback.h +++ /dev/null @@ -1,454 +0,0 @@ - -#if !defined( INCLUDED_GENERIC_CLOSURE_H ) -#define INCLUDED_GENERIC_CLOSURE_H - -/// \file -/// \brief Type-safe techniques for binding the first argument of an anonymous callback. - -#include - -/// \brief Combines a void pointer with a pointer to a function which operates on a void pointer. -/// -/// Use with the callback constructors MemberCaller, ConstMemberCaller, ReferenceCaller, ConstReferenceCaller, PointerCaller, ConstPointerCaller and FreeCaller. -class Callback -{ -typedef void ( *Thunk )( void* ); -void* m_environment; -Thunk m_thunk; - -static void nullThunk( void* ){ -} - -public: -Callback() : m_environment( 0 ), m_thunk( nullThunk ){ -} -Callback( void* environment, Thunk function ) : m_environment( environment ), m_thunk( function ){ -} -void* getEnvironment() const { - return m_environment; -} -Thunk getThunk() const { - return m_thunk; -} -void operator()() const { - m_thunk( m_environment ); -} -}; - -inline bool operator==( const Callback& self, const Callback& other ){ - return self.getEnvironment() == other.getEnvironment() && self.getThunk() == other.getThunk(); -} -inline bool operator<( const Callback& self, const Callback& other ){ - return self.getEnvironment() < other.getEnvironment() || - ( !( other.getEnvironment() < self.getEnvironment() ) && self.getThunk() < other.getThunk() ); -} - -/// \brief Combines a void pointer with a pointer to a function which operates on a void pointer and one other argument. -/// -/// Use with the callback constructors MemberCaller1, ConstMemberCaller1, ReferenceCaller1, ConstReferenceCaller1, PointerCaller1, ConstPointerCaller1 and FreeCaller1. -template -class Callback1 -{ -typedef void ( *Thunk )( void*, FirstArgument ); -void* m_environment; -Thunk m_thunk; - -static void nullThunk( void*, FirstArgument ){ -} - -public: -typedef FirstArgument first_argument_type; - -Callback1() : m_environment( 0 ), m_thunk( nullThunk ){ -} -Callback1( void* environment, Thunk function ) : m_environment( environment ), m_thunk( function ){ -} -void* getEnvironment() const { - return m_environment; -} -Thunk getThunk() const { - return m_thunk; -} -void operator()( FirstArgument firstArgument ) const { - m_thunk( m_environment, firstArgument ); -} -}; - -template -inline bool operator==( const Callback1& self, const Callback1& other ){ - return self.getEnvironment() == other.getEnvironment() && self.getThunk() == other.getThunk(); -} -template -inline bool operator<( const Callback1& self, const Callback1& other ){ - return self.getEnvironment() < other.getEnvironment() || - ( !( other.getEnvironment() < self.getEnvironment() ) && self.getThunk() < other.getThunk() ); -} - -template -class FunctorInvoke -{ -public: -inline void operator()( Functor functor ){ - functor(); -} -}; - -typedef FunctorInvoke CallbackInvoke; - - -template -class Functor1Invoke -{ -FirstArgument m_firstArgument; -public: -Functor1Invoke( FirstArgument firstArgument ) : m_firstArgument( firstArgument ){ -} -inline void operator()( Functor functor ){ - functor( m_firstArgument ); -} -}; - - -typedef Callback1 BoolImportCallback; -typedef Callback1 BoolExportCallback; - -typedef Callback1 IntImportCallback; -typedef Callback1 IntExportCallback; - -typedef Callback1 FloatImportCallback; -typedef Callback1 FloatExportCallback; - -typedef Callback1 StringImportCallback; -typedef Callback1 StringExportCallback; - -typedef Callback1 SizeImportCallback; -typedef Callback1 SizeExportCallback; - - -/// \brief Forms a Callback from a non-const Environment reference and a non-const Environment member-function. -/// -/// \dontinclude generic/callback.cpp -/// \skipline MemberCaller example -/// \until end example -template -class MemberCaller -{ -Environment& m_environment; -public: -MemberCaller( Environment& environment ) : m_environment( environment ){ -} -void* getEnvironment() const { - return &m_environment; -} -static void thunk( void* environment ){ - ( ( *reinterpret_cast( environment ) ).*member )(); -} -operator Callback() const -{ - return Callback( getEnvironment(), thunk ); -} -}; - -/// \brief Forms a Callback from a const Environment reference and a const Environment member-function. -/// -/// \dontinclude generic/callback.cpp -/// \skipline MemberCaller example -/// \until end example -template -class ConstMemberCaller -{ -const Environment& m_environment; -public: -ConstMemberCaller( const Environment& environment ) : m_environment( environment ){ -} -void* getEnvironment() const { - return const_cast( &m_environment ); -} -static void thunk( void* environment ){ - ( ( *reinterpret_cast( environment ) ).*member )(); -} -operator Callback() const -{ - return Callback( getEnvironment(), thunk ); -} -}; - -/// \brief Forms a Callback from a non-const Environment reference and a const Environment member-function which takes one argument. -template -class MemberCaller1 -{ -Environment& m_environment; -public: -MemberCaller1( Environment& environment ) : m_environment( environment ){ -} -void* getEnvironment() const { - return &m_environment; -} -static void thunk( void* environment, FirstArgument firstArgument ){ - ( ( *reinterpret_cast( environment ) ).*member )( firstArgument ); -} -operator Callback1( ) const -{ - return Callback1( getEnvironment(), thunk ); -} -}; - -/// \brief Forms a Callback from a const Environment reference and a const Environment member-function which takes one argument. -template -class ConstMemberCaller1 -{ -const Environment& m_environment; -public: -ConstMemberCaller1( const Environment& environment ) : m_environment( environment ){ -} -void* getEnvironment() const { - return const_cast( &m_environment ); -} -static void thunk( void* environment, FirstArgument firstArgument ){ - ( ( *reinterpret_cast( environment ) ).*member )( firstArgument ); -} -operator Callback1( ) const -{ - return Callback1( getEnvironment(), thunk ); -} -}; - -/// \brief Forms a Callback from a non-const Environment reference and a free function which operates on a non-const Environment reference. -/// -/// \dontinclude generic/callback.cpp -/// \skipline ReferenceCaller example -/// \until end example -template -class ReferenceCaller -{ -Environment& m_environment; -public: -ReferenceCaller( Environment& environment ) : m_environment( environment ){ -} -void* getEnvironment() const { - return &m_environment; -} -static void thunk( void* environment ){ - (func)( *reinterpret_cast( environment ) ); -} -operator Callback() const -{ - return Callback( getEnvironment(), thunk ); -} -}; - -/// \brief Forms a Callback from a const Environment reference and a free function which operates on a const Environment reference. -/// -/// \dontinclude generic/callback.cpp -/// \skipline ReferenceCaller example -/// \until end example -template -class ConstReferenceCaller -{ -const Environment& m_environment; -public: -ConstReferenceCaller( const Environment& environment ) : m_environment( environment ){ -} -void* getEnvironment() const { - return const_cast( &m_environment ); -} -static void thunk( void* environment ){ - (func)( *reinterpret_cast( environment ) ); -} -operator Callback() const -{ - return Callback( getEnvironment(), thunk ); -} -}; - -/// \brief Forms a Callback from a non-const Environment reference and a free function which operates on a non-const Environment reference and one other argument. -template -class ReferenceCaller1 -{ -Environment& m_environment; -public: -ReferenceCaller1( Environment& environment ) : m_environment( environment ){ -} -void* getEnvironment() const { - return &m_environment; -} -static void thunk( void* environment, FirstArgument firstArgument ){ - (func)( *reinterpret_cast( environment ), firstArgument ); -} -operator Callback1( ) const -{ - return Callback1( getEnvironment(), thunk ); -} -}; - -/// \brief Forms a Callback from a const Environment reference and a free function which operates on a const Environment reference and one other argument. -template -class ConstReferenceCaller1 -{ -const Environment& m_environment; -public: -ConstReferenceCaller1( const Environment& environment ) : m_environment( environment ){ -} -void* getEnvironment() const { - return const_cast( &m_environment ); -} -static void thunk( void* environment, FirstArgument firstArgument ){ - (func)( *reinterpret_cast( environment ), firstArgument ); -} -operator Callback1( ) const -{ - return Callback1( getEnvironment(), thunk ); -} -}; - -/// \brief Forms a Callback from a non-const Environment pointer and a free function which operates on a non-const Environment pointer. -template -class PointerCaller -{ -Environment* m_environment; -public: -PointerCaller( Environment* environment ) : m_environment( environment ){ -} -void* getEnvironment() const { - return m_environment; -} -static void thunk( void* environment ){ - (func)( reinterpret_cast( environment ) ); -} -operator Callback() const -{ - return Callback( getEnvironment(), thunk ); -} -}; - -/// \brief Forms a Callback from a const Environment pointer and a free function which operates on a const Environment pointer. -template -class ConstPointerCaller -{ -const Environment* m_environment; -public: -ConstPointerCaller( const Environment* environment ) : m_environment( environment ){ -} -void* getEnvironment() const { - return const_cast( m_environment ); -} -static void thunk( void* environment ){ - (func)( reinterpret_cast( environment ) ); -} -operator Callback() const -{ - return Callback( getEnvironment(), thunk ); -} -}; - -/// \brief Forms a Callback from a non-const Environment pointer and a free function which operates on a non-const Environment pointer and one other argument. -template -class PointerCaller1 -{ -Environment* m_environment; -public: -PointerCaller1( Environment* environment ) : m_environment( environment ){ -} -void* getEnvironment() const { - return m_environment; -} -static void thunk( void* environment, FirstArgument firstArgument ){ - (func)( reinterpret_cast( environment ), firstArgument ); -} -operator Callback1( ) const -{ - return Callback1( getEnvironment(), thunk ); -} -}; - -/// \brief Forms a Callback from a const Environment pointer and a free function which operates on a const Environment pointer and one other argument. -template -class ConstPointerCaller1 -{ -const Environment* m_environment; -public: -ConstPointerCaller1( const Environment* environment ) : m_environment( environment ){ -} -void* getEnvironment() const { - return const_cast( m_environment ); -} -static void thunk( void* environment, FirstArgument firstArgument ){ - (func)( reinterpret_cast( environment ), firstArgument ); -} -operator Callback1( ) const -{ - return Callback1( getEnvironment(), thunk ); -} -}; - - -/// \brief Forms a Callback from a free function which takes no arguments. -template -class FreeCaller -{ -public: -void* getEnvironment() const { - return 0; -} -static void thunk( void* ){ - (func)( ); -} -operator Callback() const -{ - return Callback( getEnvironment(), thunk ); -} -}; - -/// \brief Forms a Callback from a free function which takes a single argument. -template -class FreeCaller1 -{ -public: -void* getEnvironment() const { - return 0; -} -static void thunk( void*, FirstArgument firstArgument ){ - (func)( firstArgument ); -} -operator Callback1( ) const -{ - return Callback1( getEnvironment(), thunk ); -} -}; - - -/// \brief Constructs a Callback from a non-const \p functor with zero arguments. -/// -/// \param Functor Must define \c operator()(). -template -inline Callback makeCallback( Functor& functor ){ - return Callback( MemberCaller( functor ) ); -} - -/// \brief Constructs a Callback from a const \p functor with zero arguments. -/// -/// \param Functor Must define const \c operator()(). -template -inline Callback makeCallback( const Functor& functor ){ - return Callback( ConstMemberCaller( functor ) ); -} - -/// \brief Constructs a Callback1 from a non-const \p functor with one argument. -/// -/// \param Functor Must define \c first_argument_type and \c operator()(first_argument_type). -template -inline Callback1 makeCallback1( Functor& functor ){ - typedef typename Functor::first_argument_type FirstArgument; - return Callback1( MemberCaller1( functor ) ); -} - -/// \brief Constructs a Callback1 from a const \p functor with one argument. -/// -/// \param Functor Must define \c first_argument_type and const \c operator()(first_argument_type). -template -inline Callback1 makeCallback1( const Functor& functor ){ - typedef typename Functor::first_argument_type FirstArgument; - return Callback1( ConstMemberCaller1( functor ) ); -} - -#endif diff --git a/tools/urt/libs/generic/enumeration.cpp b/tools/urt/libs/generic/enumeration.cpp deleted file mode 100644 index a8ee400..0000000 --- a/tools/urt/libs/generic/enumeration.cpp +++ /dev/null @@ -1,2 +0,0 @@ - -#include "enumeration.h" diff --git a/tools/urt/libs/generic/enumeration.h b/tools/urt/libs/generic/enumeration.h deleted file mode 100644 index 41f0a02..0000000 --- a/tools/urt/libs/generic/enumeration.h +++ /dev/null @@ -1,36 +0,0 @@ - -#if !defined( INCLUDED_GENERIC_ENUMERATION_H ) -#define INCLUDED_GENERIC_ENUMERATION_H - -/// \file -/// \brief Type safe enumeration. - -/// \brief An enumerated value. -/// -/// - Can be forward-declared when the definition of Enumeration is unknown. -/// - Can only be constructed from valid enumerated values. -/// - Can only be compared with others of the same type. -/// -/// \param Enumeration A type that contains an enum \c Value of the allowed values of the enumeration. -template -class EnumeratedValue : public Enumeration -{ -typename Enumeration::Value m_value; -public: -explicit EnumeratedValue( typename Enumeration::Value value ) : m_value( value ){ -} -typename Enumeration::Value get() const { - return m_value; -} -}; - -template -inline bool operator==( EnumeratedValue self, EnumeratedValue other ){ - return self.get() == other.get(); -} -template -inline bool operator!=( EnumeratedValue self, EnumeratedValue other ){ - return !operator==( self, other ); -} - -#endif diff --git a/tools/urt/libs/generic/object.cpp b/tools/urt/libs/generic/object.cpp deleted file mode 100644 index b3b4532..0000000 --- a/tools/urt/libs/generic/object.cpp +++ /dev/null @@ -1,19 +0,0 @@ - -#include "object.h" - -namespace -{ -class Blah -{ -int i; -public: -Blah(){ - i = 3; -} -}; - -void Test(){ - char storage[sizeof( Blah )]; - constructor( *reinterpret_cast( storage ) ); -} -} \ No newline at end of file diff --git a/tools/urt/libs/generic/object.h b/tools/urt/libs/generic/object.h deleted file mode 100644 index 8142125..0000000 --- a/tools/urt/libs/generic/object.h +++ /dev/null @@ -1,68 +0,0 @@ - -#if !defined( INCLUDED_GENERIC_OBJECT_H ) -#define INCLUDED_GENERIC_OBJECT_H - -/// \file -/// \brief Convenience functions (syntactic sugar) to wrap explicit constructor (aka in-place 'new') and destructor calls. -/// -/// Use makeReference() to wrap non-const-reference constructor parameters. - -#if _MSC_VER > 1000 && defined( WIN32 ) -#pragma warning(disable:4345) // behavior change: an object of POD type constructed with an initializer of the form () will be default-initialized -#endif - -#include - -template -inline void constructor( Type& object ){ - new( &object )Type(); -} - -template -inline void constructor( Type& object, const T1& t1 ){ - new( &object )Type( t1 ); -} - -template -inline void constructor( Type& object, const T1& t1, const T2& t2 ){ - new( &object )Type( t1, t2 ); -} - -template -inline void constructor( Type& object, const T1& t1, const T2& t2, const T3& t3 ){ - new( &object )Type( t1, t2, t3 ); -} - -template -inline void constructor( Type& object, const T1& t1, const T2& t2, const T3& t3, const T4& t4 ){ - new( &object )Type( t1, t2, t3, t4 ); -} - -template -inline void constructor( Type& object, const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5 ){ - new( &object )Type( t1, t2, t3, t4, t5 ); -} - -template -inline void constructor( Type& object, const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5, const T6& t6 ){ - new( &object )Type( t1, t2, t3, t4, t5, t6 ); -} - -template -inline void constructor( Type& object, const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5, const T6& t6, const T7& t7 ){ - new( &object )Type( t1, t2, t3, t4, t5, t6, t7 ); -} - -template -inline void constructor( Type& object, const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5, const T6& t6, const T7& t7, const T8& t8 ){ - new( &object )Type( t1, t2, t3, t4, t5, t6, t7, t8 ); -} - -template -inline void destructor( Type& object ){ - object.~Type(); -} - - - -#endif diff --git a/tools/urt/libs/generic/reference.cpp b/tools/urt/libs/generic/reference.cpp deleted file mode 100644 index 73d3def..0000000 --- a/tools/urt/libs/generic/reference.cpp +++ /dev/null @@ -1,2 +0,0 @@ - -#include "reference.h" diff --git a/tools/urt/libs/generic/reference.h b/tools/urt/libs/generic/reference.h deleted file mode 100644 index 582a50a..0000000 --- a/tools/urt/libs/generic/reference.h +++ /dev/null @@ -1,95 +0,0 @@ - -#if !defined( INCLUDED_GENERIC_REFERENCE_H ) -#define INCLUDED_GENERIC_REFERENCE_H - -/// \file -/// \brief Wrappers to allow storing objects in templated containers using 'reference' semantics. - -/// \brief A reference to a mutable object. -/// Has 'reference' semantics, except for \c 'operator==' and \c 'operator.'. -/// \param Type The type of the referenced object. -template -class Reference -{ -Type* m_contained; -public: -explicit Reference( Type& contained ) : m_contained( &contained ){ -} -Type& operator*() const { - return *m_contained; -} -Type* operator->() const { - return m_contained; -} -operator Type&() const -{ - return *m_contained; -} -Type& get() const { - return *m_contained; -} -Type* get_pointer() const { - return m_contained; -} -}; - -template -bool operator<( const Reference& self, const Reference& other ){ - return self.get() < other.get(); -} -template -bool operator==( const Reference& self, const Reference& other ){ - return self.get() == other.get(); -} - -/// \brief construct a reference to a mutable object. -template -inline Reference makeReference( Type& value ){ - return Reference( value ); -} - -/// \brief A reference to a non-mutable object. -/// Has 'reference' semantics, except for \c 'operator==' and \c 'operator.'. -/// \param Type The type of the referenced object. -template -class ConstReference -{ -const Type* m_contained; -public: -explicit ConstReference( const Type& contained ) : m_contained( &contained ){ -} -const Type& operator*() const { - return *m_contained; -} -const Type* operator->() const { - return m_contained; -} -operator const Type&() const -{ - return *m_contained; -} -const Type& get() const { - return *m_contained; -} -const Type* get_pointer() const { - return m_contained; -} -}; - -template -bool operator<( const ConstReference& self, const ConstReference& other ){ - return self.get() < other.get(); -} -template -bool operator==( const ConstReference& self, const ConstReference& other ){ - return self.get() == other.get(); -} - -/// \brief construct a reference to a non-mutable object. -template -inline ConstReference makeReference( const Type& value ){ - return ConstReference( value ); -} - - -#endif diff --git a/tools/urt/libs/generic/referencecounted.cpp b/tools/urt/libs/generic/referencecounted.cpp deleted file mode 100644 index aa32b7c..0000000 --- a/tools/urt/libs/generic/referencecounted.cpp +++ /dev/null @@ -1,2 +0,0 @@ - -#include "referencecounted.h" diff --git a/tools/urt/libs/generic/referencecounted.h b/tools/urt/libs/generic/referencecounted.h deleted file mode 100644 index a6dda90..0000000 --- a/tools/urt/libs/generic/referencecounted.h +++ /dev/null @@ -1,160 +0,0 @@ - -#if !defined( INCLUDED_GENERIC_REFERENCECOUNTED_H ) -#define INCLUDED_GENERIC_REFERENCECOUNTED_H - -/// \file -/// \brief 'smart' pointers and references. - -#include - -template -class IncRefDecRefCounter -{ -public: -void increment( Type& value ){ - value.IncRef(); -} -void decrement( Type& value ){ - value.DecRef(); -} -}; - -/// \brief A smart-pointer that uses a counter stored in the object pointed-to. -template > -class SmartPointer : public Counter -{ -Type* m_value; -public: - -SmartPointer( const SmartPointer& other ) - : m_value( other.m_value ){ - Counter::increment( *m_value ); -} -explicit SmartPointer( Type* value ) - : m_value( value ){ - Counter::increment( *m_value ); -} -~SmartPointer(){ - Counter::decrement( *m_value ); -} -SmartPointer& operator=( const SmartPointer& other ){ - SmartPointer temp( other ); - temp.swap( *this ); - return *this; -} -SmartPointer& operator=( Type* value ){ - SmartPointer temp( value ); - temp.swap( *this ); - return *this; -} -void swap( SmartPointer& other ){ - std::swap( m_value, other.m_value ); -} - -operator Type*() const -{ - return m_value; -} -Type& operator*() const { - return *m_value; -} -Type* operator->() const { - return m_value; -} -Type* get() const { - return m_value; -} -}; - -template -inline bool operator<( const SmartPointer& self, const SmartPointer& other ){ - return self.get() < other.get(); -} -template -inline bool operator==( const SmartPointer& self, const SmartPointer& other ){ - return self.get() == other.get(); -} -template -inline bool operator!=( const SmartPointer& self, const SmartPointer& other ){ - return !::operator==( self, other ); -} - -namespace std -{ -/// \brief Swaps the values of \p self and \p other. -/// Overloads std::swap(). -template -inline void swap( SmartPointer& self, SmartPointer& other ){ - self.swap( other ); -} -} - - -/// \brief A smart-reference that uses a counter stored in the object pointed-to. -template > -class SmartReference : public Counter -{ -Type* m_value; -public: - -SmartReference( const SmartReference& other ) - : m_value( other.m_value ){ - Counter::increment( *m_value ); -} -explicit SmartReference( Type& value ) - : m_value( &value ){ - Counter::increment( *m_value ); -} -~SmartReference(){ - Counter::decrement( *m_value ); -} -SmartReference& operator=( const SmartReference& other ){ - SmartReference temp( other ); - temp.swap( *this ); - return *this; -} -SmartReference& operator=( Type& value ){ - SmartReference temp( value ); - temp.swap( *this ); - return *this; -} -void swap( SmartReference& other ){ - std::swap( m_value, other.m_value ); -} - -operator Type&() const -{ - return *m_value; -} -Type& get() const { - return *m_value; -} -Type* get_pointer() const { - return m_value; -} -}; - -template -inline bool operator<( const SmartReference& self, const SmartReference& other ){ - return self.get() < other.get(); -} -template -inline bool operator==( const SmartReference& self, const SmartReference& other ){ - return self.get() == other.get(); -} -template -inline bool operator!=( const SmartReference& self, const SmartReference& other ){ - return !::operator==( self, other ); -} - -namespace std -{ -/// \brief Swaps the values of \p self and \p other. -/// Overloads std::swap(). -template -inline void swap( SmartReference& self, SmartReference& other ){ - self.swap( other ); -} -} - -#endif diff --git a/tools/urt/libs/generic/static.cpp b/tools/urt/libs/generic/static.cpp deleted file mode 100644 index acf50d5..0000000 --- a/tools/urt/libs/generic/static.cpp +++ /dev/null @@ -1,104 +0,0 @@ - -#include "static.h" - -#if defined( _DEBUG ) || defined( DOXYGEN ) - -namespace ExampleStatic -{ -// Static example -// ---- myclass.h -class MyClass -{ -public: -int value; -MyClass() : value( 3 ){ -} -}; - -typedef Static StaticMyClass; - -// ---- main.cpp -class DynamicInitialisation -{ -public: -DynamicInitialisation(){ - // StaticMyClass::instance() may be invalid here because construction order is undefined -} -}; - -DynamicInitialisation g_dynamicInitialisation; - -void duringMain(){ - int bar = StaticMyClass::instance().value; -} -// end example -} - -namespace ExampleLazyStatic -{ -// LazyStatic example -// ---- myclass.h -class MyClass -{ -public: -int value; -MyClass() : value( 3 ){ -} -// destructor will never be called -}; - -typedef LazyStatic StaticMyClass; - -// ---- main.cpp -class DynamicInitialisation -{ -public: -DynamicInitialisation(){ - int bar = StaticMyClass::instance().value; -} -}; - -DynamicInitialisation g_dynamicInitialisation; - -void duringMain(){ - int bar = StaticMyClass::instance().value; -} -// end example -} - -namespace ExampleSmartStatic -{ -// SmartStatic example -// ---- myclass.h -class MyClass -{ -public: -int value; -MyClass() : value( 3 ){ -} -}; - -typedef CountedStatic StaticMyClass; - -// ---- main.cpp -class DynamicInitialisation -{ -public: -DynamicInitialisation(){ - // StaticMyClass::instance() is invalid before the ref is constructed - SmartStatic ref; - int bar = ref.instance().value; - - SmartStatic ref2; // any number of instances are allowed. -} -}; - -DynamicInitialisation g_dynamicInitialisation; - -void duringMain(){ - int bar = SmartStatic().instance().value; // an instance can be a temporary -} -// end example -} - -#endif diff --git a/tools/urt/libs/generic/static.h b/tools/urt/libs/generic/static.h deleted file mode 100644 index 9c50743..0000000 --- a/tools/urt/libs/generic/static.h +++ /dev/null @@ -1,112 +0,0 @@ - -#if !defined( INCLUDED_GENERIC_STATIC_H ) -#define INCLUDED_GENERIC_STATIC_H - -/// \file -/// \brief Template techniques for instantiating singletons. - -#include - -/// \brief A singleton which is statically initialised. -/// -/// \param Type The singleton object type. -/// -/// \dontinclude generic/static.cpp -/// \skipline Static example -/// \until end example -template -class Static -{ -static Type m_instance; -public: -static Type& instance(){ - return m_instance; -} -}; - -template -Type Static::m_instance; - - -/// \brief A singleton which is lazily initialised. -/// The instance is constructed the first time it is referenced, and is never destroyed. -/// -/// \param Type The singleton object type. -/// -/// \dontinclude generic/static.cpp -/// \skipline LazyStatic example -/// \until end example -template -class LazyStatic -{ -static Type* m_instance; // this will be initialised to 0 by the CRT, according to the c++ standard -public: -static Type& instance(){ - if ( m_instance == 0 ) { - m_instance = new Type; // allocate using 'new' to get the correct alignment - } - return *m_instance; -} -}; - -template -Type * LazyStatic::m_instance; - - -/// \brief A singleton which keeps a count of the number of times it is referenced. -/// -/// The instance is constructed when its reference count changes from 0 to 1 and destroyed when its reference count changes from 1 to 0. -/// Use with SmartStatic. -/// -/// \param Type The singleton object type. -template -class CountedStatic -{ -static std::size_t m_refcount; // this will be initialised to 0 by the CRT, according to the c++ standard -static Type* m_instance; -public: -static Type& instance(){ - return *m_instance; -} -static void capture(){ - if ( ++m_refcount == 1 ) { - m_instance = new Type; // allocate using 'new' to get the correct alignment - } -} -static void release(){ - if ( --m_refcount == 0 ) { - delete m_instance; - } -} -}; - -template -std::size_t CountedStatic::m_refcount; // this will be initialised to 0 by the CRT, according to the c++ standard -template -Type * CountedStatic::m_instance; - -/// \brief A reference to a CountedStatic. -/// Guarantees that CountedStatic will be constructed for the lifetime of this object. -/// -/// \param Type The type parameter of the CountedStatic to reference. -/// -/// \dontinclude generic/static.cpp -/// \skipline SmartStatic example -/// \until end example -template -class SmartStatic -{ -public: -SmartStatic(){ - CountedStatic::capture(); -} -~SmartStatic(){ - CountedStatic::release(); -} -Type& instance(){ - return CountedStatic::instance(); -} -}; - - -#endif diff --git a/tools/urt/libs/gtkutil/accelerator.cpp b/tools/urt/libs/gtkutil/accelerator.cpp deleted file mode 100644 index a2070a9..0000000 --- a/tools/urt/libs/gtkutil/accelerator.cpp +++ /dev/null @@ -1,456 +0,0 @@ - -#include "accelerator.h" - -#include "debugging/debugging.h" - -#include -#include -#include -#include - -#include "generic/callback.h" -#include "generic/bitfield.h" - -#include "pointer.h" -#include "closure.h" - - - -typedef std::map AcceleratorMap; - -void accelerator_map_insert( AcceleratorMap& acceleratorMap, Accelerator accelerator, const Callback& callback ){ - if ( accelerator.key != 0 ) { - ASSERT_MESSAGE( acceleratorMap.find( accelerator ) == acceleratorMap.end(), "failed to add accelerator" ); - acceleratorMap.insert( AcceleratorMap::value_type( accelerator, callback ) ); - } -} - -void accelerator_map_erase( AcceleratorMap& acceleratorMap, Accelerator accelerator ){ - if ( accelerator.key != 0 ) { - ASSERT_MESSAGE( acceleratorMap.find( accelerator ) != acceleratorMap.end(), "failed to remove accelerator" ); - acceleratorMap.erase( accelerator ); - } -} - -Accelerator accelerator_for_event_key( guint keyval, guint state ){ - keyval = gdk_keyval_to_upper( keyval ); - if ( keyval == GDK_ISO_Left_Tab ) { - keyval = GDK_Tab; - } - return Accelerator( keyval, (GdkModifierType)( state & gtk_accelerator_get_default_mod_mask() ) ); -} - -bool AcceleratorMap_activate( const AcceleratorMap& acceleratorMap, const Accelerator& accelerator ){ - AcceleratorMap::const_iterator i = acceleratorMap.find( accelerator ); - if ( i != acceleratorMap.end() ) { - ( *i ).second(); - return true; - } - - return false; -} - -static gboolean accelerator_key_event( GtkWindow* window, GdkEventKey* event, AcceleratorMap* acceleratorMap ){ - return AcceleratorMap_activate( *acceleratorMap, accelerator_for_event_key( event->keyval, event->state ) ); -} - - -AcceleratorMap g_special_accelerators; - - -namespace MouseButton -{ -enum -{ - Left = 1 << 0, - Right = 1 << 1, - Middle = 1 << 2, -}; -} - -typedef unsigned int ButtonMask; - -void print_buttons( ButtonMask mask ){ - globalOutputStream() << "button state: "; - if ( ( mask & MouseButton::Left ) != 0 ) { - globalOutputStream() << "Left "; - } - if ( ( mask & MouseButton::Right ) != 0 ) { - globalOutputStream() << "Right "; - } - if ( ( mask & MouseButton::Middle ) != 0 ) { - globalOutputStream() << "Middle "; - } - globalOutputStream() << "\n"; -} - -ButtonMask ButtonMask_for_event_button( guint button ){ - switch ( button ) - { - case 1: - return MouseButton::Left; - case 2: - return MouseButton::Middle; - case 3: - return MouseButton::Right; - } - return 0; -} - -bool window_has_accel( GtkWindow* toplevel ){ - return g_slist_length( gtk_accel_groups_from_object( G_OBJECT( toplevel ) ) ) != 0; -} - -namespace -{ -bool g_accel_enabled = true; -} - -bool global_accel_enabled(){ - return g_accel_enabled; -} - - -AcceleratorMap g_queuedAccelerators; - -GClosure* accel_group_add_accelerator( GtkAccelGroup* group, Accelerator accelerator, const Callback& callback ); - -void GlobalQueuedAccelerators_commit(){ - for ( AcceleratorMap::const_iterator i = g_queuedAccelerators.begin(); i != g_queuedAccelerators.end(); ++i ) - { - accel_group_add_accelerator( global_accel, ( *i ).first, ( *i ).second ); - } - g_queuedAccelerators.clear(); -} - -void GlobalQueuedAccelerators_add( Accelerator accelerator, const Callback& callback ){ - g_queuedAccelerators.insert( AcceleratorMap::value_type( accelerator, callback ) ); -} - -void accel_group_test( GtkWindow* toplevel, GtkAccelGroup* accel ){ - guint n_entries; - gtk_accel_group_query( accel, '4', (GdkModifierType)0, &n_entries ); - globalOutputStream() << "grid4: " << n_entries << "\n"; - globalOutputStream() << "toplevel accelgroups: " << g_slist_length( gtk_accel_groups_from_object( G_OBJECT( toplevel ) ) ) << "\n"; -} - -typedef std::set WindowSet; -WindowSet g_accel_windows; - -bool Buttons_press( ButtonMask& buttons, guint button, guint state ){ - if ( buttons == 0 && bitfield_enable( buttons, ButtonMask_for_event_button( button ) ) != 0 ) { - ASSERT_MESSAGE( g_accel_enabled, "Buttons_press: accelerators not enabled" ); - g_accel_enabled = false; - for ( WindowSet::iterator i = g_accel_windows.begin(); i != g_accel_windows.end(); ++i ) - { - GtkWindow* toplevel = *i; - ASSERT_MESSAGE( window_has_accel( toplevel ), "ERROR" ); - ASSERT_MESSAGE( GTK_WIDGET_TOPLEVEL( toplevel ), "disabling accel for non-toplevel window" ); - gtk_window_remove_accel_group( toplevel, global_accel ); -#if 0 - globalOutputStream() << reinterpret_cast( toplevel ) << ": disabled global accelerators\n"; -#endif -#if 0 - accel_group_test( toplevel, global_accel ); -#endif - } - } - buttons = bitfield_enable( buttons, ButtonMask_for_event_button( button ) ); -#if 0 - globalOutputStream() << "Buttons_press: "; - print_buttons( buttons ); -#endif - return false; -} - -bool Buttons_release( ButtonMask& buttons, guint button, guint state ){ - if ( buttons != 0 && bitfield_disable( buttons, ButtonMask_for_event_button( button ) ) == 0 ) { - ASSERT_MESSAGE( !g_accel_enabled, "Buttons_release: accelerators are enabled" ); - g_accel_enabled = true; - for ( WindowSet::iterator i = g_accel_windows.begin(); i != g_accel_windows.end(); ++i ) - { - GtkWindow* toplevel = *i; - ASSERT_MESSAGE( !window_has_accel( toplevel ), "ERROR" ); - ASSERT_MESSAGE( GTK_WIDGET_TOPLEVEL( toplevel ), "enabling accel for non-toplevel window" ); - gtk_window_add_accel_group( toplevel, global_accel ); -#if 0 - globalOutputStream() << reinterpret_cast( toplevel ) << ": enabled global accelerators\n"; -#endif -#if 0 - accel_group_test( toplevel, global_accel ); -#endif - } - GlobalQueuedAccelerators_commit(); - } - buttons = bitfield_disable( buttons, ButtonMask_for_event_button( button ) ); -#if 0 - globalOutputStream() << "Buttons_release: "; - print_buttons( buttons ); -#endif - return false; -} - -bool Buttons_releaseAll( ButtonMask& buttons ){ - Buttons_release( buttons, MouseButton::Left | MouseButton::Middle | MouseButton::Right, 0 ); - return false; -} - -struct PressedButtons -{ - ButtonMask buttons; - - PressedButtons() : buttons( 0 ){ - } -}; - -gboolean PressedButtons_button_press( GtkWidget* widget, GdkEventButton* event, PressedButtons* pressed ){ - if ( event->type == GDK_BUTTON_PRESS ) { - return Buttons_press( pressed->buttons, event->button, event->state ); - } - return FALSE; -} - -gboolean PressedButtons_button_release( GtkWidget* widget, GdkEventButton* event, PressedButtons* pressed ){ - if ( event->type == GDK_BUTTON_RELEASE ) { - return Buttons_release( pressed->buttons, event->button, event->state ); - } - return FALSE; -} - -gboolean PressedButtons_focus_out( GtkWidget* widget, GdkEventFocus* event, PressedButtons* pressed ){ - Buttons_releaseAll( pressed->buttons ); - return FALSE; -} - -void PressedButtons_connect( PressedButtons& pressedButtons, GtkWidget* widget ){ - g_signal_connect( G_OBJECT( widget ), "button_press_event", G_CALLBACK( PressedButtons_button_press ), &pressedButtons ); - g_signal_connect( G_OBJECT( widget ), "button_release_event", G_CALLBACK( PressedButtons_button_release ), &pressedButtons ); - g_signal_connect( G_OBJECT( widget ), "focus_out_event", G_CALLBACK( PressedButtons_focus_out ), &pressedButtons ); -} - -PressedButtons g_pressedButtons; - - -#include - -struct PressedKeys -{ - typedef std::set Keys; - Keys keys; - std::size_t refcount; - - PressedKeys() : refcount( 0 ){ - } -}; - -AcceleratorMap g_keydown_accelerators; -AcceleratorMap g_keyup_accelerators; - -bool Keys_press( PressedKeys::Keys& keys, guint keyval ){ - if ( keys.insert( keyval ).second ) { - return AcceleratorMap_activate( g_keydown_accelerators, accelerator_for_event_key( keyval, 0 ) ); - } - return g_keydown_accelerators.find( accelerator_for_event_key( keyval, 0 ) ) != g_keydown_accelerators.end(); -} - -bool Keys_release( PressedKeys::Keys& keys, guint keyval ){ - if ( keys.erase( keyval ) != 0 ) { - return AcceleratorMap_activate( g_keyup_accelerators, accelerator_for_event_key( keyval, 0 ) ); - } - return g_keyup_accelerators.find( accelerator_for_event_key( keyval, 0 ) ) != g_keyup_accelerators.end(); -} - -void Keys_releaseAll( PressedKeys::Keys& keys, guint state ){ - for ( PressedKeys::Keys::iterator i = keys.begin(); i != keys.end(); ++i ) - { - AcceleratorMap_activate( g_keyup_accelerators, accelerator_for_event_key( *i, state ) ); - } - keys.clear(); -} - -gboolean PressedKeys_key_press( GtkWidget* widget, GdkEventKey* event, PressedKeys* pressedKeys ){ - //globalOutputStream() << "pressed: " << event->keyval << "\n"; - return event->state == 0 && Keys_press( pressedKeys->keys, event->keyval ); -} - -gboolean PressedKeys_key_release( GtkWidget* widget, GdkEventKey* event, PressedKeys* pressedKeys ){ - //globalOutputStream() << "released: " << event->keyval << "\n"; - return Keys_release( pressedKeys->keys, event->keyval ); -} - -gboolean PressedKeys_focus_in( GtkWidget* widget, GdkEventFocus* event, PressedKeys* pressedKeys ){ - ++pressedKeys->refcount; - return FALSE; -} - -gboolean PressedKeys_focus_out( GtkWidget* widget, GdkEventFocus* event, PressedKeys* pressedKeys ){ - if ( --pressedKeys->refcount == 0 ) { - Keys_releaseAll( pressedKeys->keys, 0 ); - } - return FALSE; -} - -PressedKeys g_pressedKeys; - -void GlobalPressedKeys_releaseAll(){ - Keys_releaseAll( g_pressedKeys.keys, 0 ); -} - -void GlobalPressedKeys_connect( GtkWindow* window ){ - unsigned int key_press_handler = g_signal_connect( G_OBJECT( window ), "key_press_event", G_CALLBACK( PressedKeys_key_press ), &g_pressedKeys ); - unsigned int key_release_handler = g_signal_connect( G_OBJECT( window ), "key_release_event", G_CALLBACK( PressedKeys_key_release ), &g_pressedKeys ); - g_object_set_data( G_OBJECT( window ), "key_press_handler", gint_to_pointer( key_press_handler ) ); - g_object_set_data( G_OBJECT( window ), "key_release_handler", gint_to_pointer( key_release_handler ) ); - unsigned int focus_in_handler = g_signal_connect( G_OBJECT( window ), "focus_in_event", G_CALLBACK( PressedKeys_focus_in ), &g_pressedKeys ); - unsigned int focus_out_handler = g_signal_connect( G_OBJECT( window ), "focus_out_event", G_CALLBACK( PressedKeys_focus_out ), &g_pressedKeys ); - g_object_set_data( G_OBJECT( window ), "focus_in_handler", gint_to_pointer( focus_in_handler ) ); - g_object_set_data( G_OBJECT( window ), "focus_out_handler", gint_to_pointer( focus_out_handler ) ); -} - -void GlobalPressedKeys_disconnect( GtkWindow* window ){ - g_signal_handler_disconnect( G_OBJECT( window ), gpointer_to_int( g_object_get_data( G_OBJECT( window ), "key_press_handler" ) ) ); - g_signal_handler_disconnect( G_OBJECT( window ), gpointer_to_int( g_object_get_data( G_OBJECT( window ), "key_release_handler" ) ) ); - g_signal_handler_disconnect( G_OBJECT( window ), gpointer_to_int( g_object_get_data( G_OBJECT( window ), "focus_in_handler" ) ) ); - g_signal_handler_disconnect( G_OBJECT( window ), gpointer_to_int( g_object_get_data( G_OBJECT( window ), "focus_out_handler" ) ) ); -} - - - -void special_accelerators_add( Accelerator accelerator, const Callback& callback ){ - accelerator_map_insert( g_special_accelerators, accelerator, callback ); -} -void special_accelerators_remove( Accelerator accelerator ){ - accelerator_map_erase( g_special_accelerators, accelerator ); -} - -void keydown_accelerators_add( Accelerator accelerator, const Callback& callback ){ - accelerator_map_insert( g_keydown_accelerators, accelerator, callback ); -} -void keydown_accelerators_remove( Accelerator accelerator ){ - accelerator_map_erase( g_keydown_accelerators, accelerator ); -} - -void keyup_accelerators_add( Accelerator accelerator, const Callback& callback ){ - accelerator_map_insert( g_keyup_accelerators, accelerator, callback ); -} -void keyup_accelerators_remove( Accelerator accelerator ){ - accelerator_map_erase( g_keyup_accelerators, accelerator ); -} - - -gboolean accel_closure_callback( GtkAccelGroup* group, GtkWidget* widget, guint key, GdkModifierType modifiers, gpointer data ){ - ( *reinterpret_cast( data ) )( ); - return TRUE; -} - -GClosure* accel_group_add_accelerator( GtkAccelGroup* group, Accelerator accelerator, const Callback& callback ){ - if ( accelerator.key != 0 && gtk_accelerator_valid( accelerator.key, accelerator.modifiers ) ) { - //globalOutputStream() << "adding accelerator: " << accelerator.key << " " << accelerator.modifiers << "\n"; - GClosure* closure = create_cclosure( G_CALLBACK( accel_closure_callback ), callback ); - gtk_accel_group_connect( group, accelerator.key, accelerator.modifiers, GTK_ACCEL_VISIBLE, closure ); - return closure; - } - else - { - special_accelerators_add( accelerator, callback ); - return 0; - } -} - -void accel_group_remove_accelerator( GtkAccelGroup* group, Accelerator accelerator ){ - if ( accelerator.key != 0 && gtk_accelerator_valid( accelerator.key, accelerator.modifiers ) ) { - gtk_accel_group_disconnect_key( group, accelerator.key, accelerator.modifiers ); - } - else - { - special_accelerators_remove( accelerator ); - } -} - -GtkAccelGroup* global_accel = 0; - -void global_accel_init(){ - global_accel = gtk_accel_group_new(); -} - -void global_accel_destroy(){ - g_object_unref( global_accel ); -} - -GClosure* global_accel_group_add_accelerator( Accelerator accelerator, const Callback& callback ){ - if ( !global_accel_enabled() ) { - // workaround: cannot add to GtkAccelGroup while it is disabled - GlobalQueuedAccelerators_add( accelerator, callback ); - return 0; - } - return accel_group_add_accelerator( global_accel, accelerator, callback ); -} -void global_accel_group_remove_accelerator( Accelerator accelerator ){ - //ASSERT_MESSAGE(global_accel_enabled(), "removing accelerator while global accel is disabled"); - accel_group_remove_accelerator( global_accel, accelerator ); -} - -/// \brief Propagates key events to the focus-widget, overriding global accelerators. -static gboolean override_global_accelerators( GtkWindow* window, GdkEventKey* event, gpointer data ){ - return gtk_window_propagate_key_event( window, event ); -} - -void global_accel_connect_window( GtkWindow* window ){ -#if 1 - unsigned int override_handler = g_signal_connect( G_OBJECT( window ), "key_press_event", G_CALLBACK( override_global_accelerators ), 0 ); - g_object_set_data( G_OBJECT( window ), "override_handler", gint_to_pointer( override_handler ) ); - - unsigned int special_key_press_handler = g_signal_connect( G_OBJECT( window ), "key_press_event", G_CALLBACK( accelerator_key_event ), &g_special_accelerators ); - g_object_set_data( G_OBJECT( window ), "special_key_press_handler", gint_to_pointer( special_key_press_handler ) ); - - GlobalPressedKeys_connect( window ); -#else - unsigned int key_press_handler = g_signal_connect( G_OBJECT( window ), "key_press_event", G_CALLBACK( accelerator_key_event ), &g_keydown_accelerators ); - unsigned int key_release_handler = g_signal_connect( G_OBJECT( window ), "key_release_event", G_CALLBACK( accelerator_key_event ), &g_keyup_accelerators ); - g_object_set_data( G_OBJECT( window ), "key_press_handler", gint_to_pointer( key_press_handler ) ); - g_object_set_data( G_OBJECT( window ), "key_release_handler", gint_to_pointer( key_release_handler ) ); -#endif - g_accel_windows.insert( window ); - gtk_window_add_accel_group( window, global_accel ); -} -void global_accel_disconnect_window( GtkWindow* window ){ -#if 1 - GlobalPressedKeys_disconnect( window ); - - g_signal_handler_disconnect( G_OBJECT( window ), gpointer_to_int( g_object_get_data( G_OBJECT( window ), "override_handler" ) ) ); - g_signal_handler_disconnect( G_OBJECT( window ), gpointer_to_int( g_object_get_data( G_OBJECT( window ), "special_key_press_handler" ) ) ); -#else - g_signal_handler_disconnect( G_OBJECT( window ), gpointer_to_int( g_object_get_data( G_OBJECT( window ), "key_press_handler" ) ) ); - g_signal_handler_disconnect( G_OBJECT( window ), gpointer_to_int( g_object_get_data( G_OBJECT( window ), "key_release_handler" ) ) ); -#endif - gtk_window_remove_accel_group( window, global_accel ); - std::size_t count = g_accel_windows.erase( window ); - ASSERT_MESSAGE( count == 1, "failed to remove accel group\n" ); -} - - -GClosure* global_accel_group_find( Accelerator accelerator ){ - guint numEntries = 0; - GtkAccelGroupEntry* entry = gtk_accel_group_query( global_accel, accelerator.key, accelerator.modifiers, &numEntries ); - if ( numEntries != 0 ) { - if ( numEntries != 1 ) { - char* name = gtk_accelerator_name( accelerator.key, accelerator.modifiers ); - globalErrorStream() << "accelerator already in-use: " << name << "\n"; - g_free( name ); - } - return entry->closure; - } - return 0; -} - -void command_connect_accelerator( const Accelerator& accelerator, const Callback& callback ){ - if ( accelerator.key != 0 ) { - global_accel_group_add_accelerator( accelerator, callback ); - } -} - -void command_disconnect_accelerator( const Accelerator& accelerator, const Callback& callback ){ - if ( accelerator.key != 0 ) { - global_accel_group_remove_accelerator( accelerator ); - } -} diff --git a/tools/urt/libs/gtkutil/accelerator.h b/tools/urt/libs/gtkutil/accelerator.h deleted file mode 100644 index 1759bdc..0000000 --- a/tools/urt/libs/gtkutil/accelerator.h +++ /dev/null @@ -1,90 +0,0 @@ - -#if !defined( INCLUDED_GTKUTIL_ACCELERATOR_H ) -#define INCLUDED_GTKUTIL_ACCELERATOR_H - -#include -#include - -#include "generic/callback.h" - - -struct Accelerator -{ - Accelerator( guint _key ) - : key( _key ), modifiers( ( GdkModifierType ) 0 ){ - } - Accelerator( guint _key, GdkModifierType _modifiers ) - : key( _key ), modifiers( _modifiers ){ - } - bool operator<( const Accelerator& other ) const { - return key < other.key || ( !( other.key < key ) && modifiers < other.modifiers ); - } - guint key; - GdkModifierType modifiers; -}; - -inline Accelerator accelerator_null(){ - return Accelerator( 0, (GdkModifierType)0 ); -} - - -void keydown_accelerators_add( Accelerator accelerator, const Callback& callback ); -void keydown_accelerators_remove( Accelerator accelerator ); -void keyup_accelerators_add( Accelerator accelerator, const Callback& callback ); -void keyup_accelerators_remove( Accelerator accelerator ); - -typedef struct _GtkWidget GtkWidget; -typedef struct _GtkWindow GtkWindow; -void global_accel_connect_window( GtkWindow* window ); -void global_accel_disconnect_window( GtkWindow* window ); - -void GlobalPressedKeys_releaseAll(); - -typedef struct _GtkAccelGroup GtkAccelGroup; -extern GtkAccelGroup* global_accel; -void global_accel_init(); -void global_accel_destroy(); - -GClosure* global_accel_group_find( Accelerator accelerator ); - -void command_connect_accelerator( const Accelerator& accelerator, const Callback& callback ); -void command_disconnect_accelerator( const Accelerator& accelerator, const Callback& callback ); - - -class Command -{ -public: -Callback m_callback; -const Accelerator& m_accelerator; -Command( const Callback& callback, const Accelerator& accelerator ) : m_callback( callback ), m_accelerator( accelerator ){ -} -}; - -class Toggle -{ -public: -Command m_command; -BoolExportCallback m_exportCallback; -Toggle( const Callback& callback, const Accelerator& accelerator, const BoolExportCallback& exportCallback ) : m_command( callback, accelerator ), m_exportCallback( exportCallback ){ -} -}; - -class KeyEvent -{ -public: -const Accelerator& m_accelerator; -Callback m_keyDown; -Callback m_keyUp; -KeyEvent( const Accelerator& accelerator, const Callback& keyDown, const Callback& keyUp ) : m_accelerator( accelerator ), m_keyDown( keyDown ), m_keyUp( keyUp ){ -} -}; - - - -struct PressedButtons; -typedef struct _GtkWidget GtkWidget; -void PressedButtons_connect( PressedButtons& pressedButtons, GtkWidget* widget ); - -extern PressedButtons g_pressedButtons; - -#endif diff --git a/tools/urt/libs/gtkutil/button.cpp b/tools/urt/libs/gtkutil/button.cpp deleted file mode 100644 index 6d8ce05..0000000 --- a/tools/urt/libs/gtkutil/button.cpp +++ /dev/null @@ -1,105 +0,0 @@ - -#include "button.h" - -#include - -#include "stream/textstream.h" -#include "stream/stringstream.h" -#include "generic/callback.h" - -#include "image.h" -#include "pointer.h" - -void clicked_closure_callback( GtkWidget* widget, gpointer data ){ - ( *reinterpret_cast( data ) )( ); -} - -void button_connect_callback( GtkButton* button, const Callback& callback ){ -#if 1 - g_signal_connect_swapped( G_OBJECT( button ), "clicked", G_CALLBACK( callback.getThunk() ), callback.getEnvironment() ); -#else - g_signal_connect_closure( G_OBJECT( button ), "clicked", create_cclosure( G_CALLBACK( clicked_closure_callback ), callback ), FALSE ); -#endif -} - -guint toggle_button_connect_callback( GtkToggleButton* button, const Callback& callback ){ -#if 1 - guint handler = g_signal_connect_swapped( G_OBJECT( button ), "toggled", G_CALLBACK( callback.getThunk() ), callback.getEnvironment() ); -#else - guint handler = g_signal_connect_closure( G_OBJECT( button ), "toggled", create_cclosure( G_CALLBACK( clicked_closure_callback ), callback ), TRUE ); -#endif - g_object_set_data( G_OBJECT( button ), "handler", gint_to_pointer( handler ) ); - return handler; -} - -void button_set_icon( GtkButton* button, const char* icon ){ - GtkImage* image = new_local_image( icon ); - gtk_widget_show( GTK_WIDGET( image ) ); - gtk_container_add( GTK_CONTAINER( button ), GTK_WIDGET( image ) ); -} - -void toggle_button_set_active_no_signal( GtkToggleButton* button, gboolean active ){ - //globalOutputStream() << "set active: " << active << "\n"; - guint handler_id = gpointer_to_int( g_object_get_data( G_OBJECT( button ), "handler" ) ); - //guint signal_id = g_signal_lookup("toggled", G_OBJECT_TYPE (button)); - //globalOutputStream() << "signal_id: " << signal_id << "\n"; - //guint found = g_signal_handler_find(G_OBJECT(button), G_SIGNAL_MATCH_ID, signal_id, 0, 0, 0, 0); - //globalOutputStream() << " handler found: " << found << "\n"; - g_signal_handler_block( G_OBJECT( button ), handler_id ); - gtk_toggle_button_set_active( button, active ); - g_signal_handler_unblock( G_OBJECT( button ), handler_id ); -} - - -void radio_button_print_state( GtkRadioButton* button ){ - globalOutputStream() << "toggle button: "; - for ( GSList* radio = gtk_radio_button_group( button ); radio != 0; radio = g_slist_next( radio ) ) - { - globalOutputStream() << gtk_toggle_button_get_active( GTK_TOGGLE_BUTTON( radio->data ) ); - } - globalOutputStream() << "\n"; -} - -GtkToggleButton* radio_button_get_nth( GtkRadioButton* radio, int index ){ - GSList *group = gtk_radio_button_group( radio ); - return GTK_TOGGLE_BUTTON( g_slist_nth_data( group, g_slist_length( group ) - index - 1 ) ); -} - -void radio_button_set_active( GtkRadioButton* radio, int index ){ - //radio_button_print_state(radio); - gtk_toggle_button_set_active( radio_button_get_nth( radio, index ), TRUE ); - //radio_button_print_state(radio); -} - -void radio_button_set_active_no_signal( GtkRadioButton* radio, int index ){ - { - for ( GSList* l = gtk_radio_button_get_group( radio ); l != 0; l = g_slist_next( l ) ) - { - g_signal_handler_block( G_OBJECT( l->data ), gpointer_to_int( g_object_get_data( G_OBJECT( l->data ), "handler" ) ) ); - } - } - radio_button_set_active( radio, index ); - { - for ( GSList* l = gtk_radio_button_get_group( radio ); l != 0; l = g_slist_next( l ) ) - { - g_signal_handler_unblock( G_OBJECT( l->data ), gpointer_to_int( g_object_get_data( G_OBJECT( l->data ), "handler" ) ) ); - } - } -} - -int radio_button_get_active( GtkRadioButton* radio ){ - //radio_button_print_state(radio); - GSList *group = gtk_radio_button_group( radio ); - int index = g_slist_length( group ) - 1; - for (; group != 0; group = g_slist_next( group ) ) - { - if ( gtk_toggle_button_get_active( GTK_TOGGLE_BUTTON( group->data ) ) ) { - break; - } - else - { - index--; - } - } - return index; -} diff --git a/tools/urt/libs/gtkutil/button.h b/tools/urt/libs/gtkutil/button.h deleted file mode 100644 index 307ff7e..0000000 --- a/tools/urt/libs/gtkutil/button.h +++ /dev/null @@ -1,23 +0,0 @@ - -#if !defined( INCLUDED_GTKUTIL_BUTTON_H ) -#define INCLUDED_GTKUTIL_BUTTON_H - -typedef struct _GtkButton GtkButton; -typedef struct _GtkToggleButton GtkToggleButton; -typedef struct _GtkRadioButton GtkRadioButton; -typedef int gint; -typedef gint gboolean; -typedef unsigned int guint; -class Callback; - -void button_connect_callback( GtkButton* button, const Callback& callback ); -guint toggle_button_connect_callback( GtkToggleButton* button, const Callback& callback ); - -void button_set_icon( GtkButton* button, const char* icon ); -void toggle_button_set_active_no_signal( GtkToggleButton* item, gboolean active ); - -void radio_button_set_active( GtkRadioButton* radio, int index ); -void radio_button_set_active_no_signal( GtkRadioButton* radio, int index ); -int radio_button_get_active( GtkRadioButton* radio ); - -#endif diff --git a/tools/urt/libs/gtkutil/clipboard.cpp b/tools/urt/libs/gtkutil/clipboard.cpp deleted file mode 100644 index 6eaa925..0000000 --- a/tools/urt/libs/gtkutil/clipboard.cpp +++ /dev/null @@ -1,125 +0,0 @@ - -#include "clipboard.h" - -#include "stream/memstream.h" -#include "stream/textstream.h" - - -/// \file -/// \brief Platform-independent GTK clipboard support. -/// \todo Using GDK_SELECTION_CLIPBOARD fails on win32, so we use the win32 API directly for now. -#if defined ( __linux__ ) || defined ( __APPLE__ ) - -#include - -enum -{ - RADIANT_CLIPPINGS = 23, -}; - -static const GtkTargetEntry clipboard_targets[] = { - { "RADIANT_CLIPPINGS", 0, RADIANT_CLIPPINGS, }, -}; - -static void clipboard_get( GtkClipboard *clipboard, GtkSelectionData *selection_data, guint info, gpointer data ){ - std::size_t len = *reinterpret_cast( data ); - const char* buffer = ( len != 0 ) ? reinterpret_cast( data ) + sizeof( std::size_t ) : 0; - - GdkAtom type = GDK_NONE; - if ( info == clipboard_targets[0].info ) { - type = gdk_atom_intern( clipboard_targets[0].target, FALSE ); - } - - gtk_selection_data_set( selection_data, type, 8, reinterpret_cast( buffer ), static_cast( len ) ); -} - -static void clipboard_clear( GtkClipboard *clipboard, gpointer data ){ - delete [] reinterpret_cast( data ); -} - -static void clipboard_received( GtkClipboard *clipboard, GtkSelectionData *data, gpointer user_data ){ - if ( data->length < 0 ) { - globalErrorStream() << "Error retrieving selection\n"; - } - else if ( strcmp( gdk_atom_name( data->type ), clipboard_targets[0].target ) == 0 ) { - BufferInputStream istream( reinterpret_cast( data->data ), data->length ); - ( *reinterpret_cast( user_data ) )( istream ); - } -} - -void clipboard_copy( ClipboardCopyFunc copy ){ - GtkClipboard* clipboard = gtk_clipboard_get( GDK_SELECTION_CLIPBOARD ); - - BufferOutputStream ostream; - copy( ostream ); - std::size_t length = ostream.size(); - char* data = new char[length + sizeof( std::size_t )]; - *reinterpret_cast( data ) = length; - memcpy( data + sizeof( std::size_t ), ostream.data(), length ); - - gtk_clipboard_set_with_data( clipboard, clipboard_targets, 1, clipboard_get, clipboard_clear, data ); -} - -ClipboardPasteFunc g_clipboardPasteFunc = 0; -void clipboard_paste( ClipboardPasteFunc paste ){ - GtkClipboard* clipboard = gtk_clipboard_get( GDK_SELECTION_CLIPBOARD ); - - g_clipboardPasteFunc = paste; - gtk_clipboard_request_contents( clipboard, gdk_atom_intern( clipboard_targets[0].target, FALSE ), clipboard_received, &g_clipboardPasteFunc ); -} - -#elif defined( WIN32 ) - -const char* c_clipboard_format = "RadiantClippings"; - -#include - -void clipboard_copy( ClipboardCopyFunc copy ){ - BufferOutputStream ostream; - copy( ostream ); - - bool bClipped = false; - UINT nClipboard = ::RegisterClipboardFormat( c_clipboard_format ); - if ( nClipboard > 0 ) { - if ( ::OpenClipboard( 0 ) ) { - EmptyClipboard(); - std::size_t length = ostream.size(); - HANDLE h = ::GlobalAlloc( GMEM_ZEROINIT | GMEM_MOVEABLE | GMEM_DDESHARE, length + sizeof( std::size_t ) ); - if ( h != 0 ) { - char *buffer = reinterpret_cast( ::GlobalLock( h ) ); - *reinterpret_cast( buffer ) = length; - buffer += sizeof( std::size_t ); - memcpy( buffer, ostream.data(), length ); - ::GlobalUnlock( h ); - ::SetClipboardData( nClipboard, h ); - ::CloseClipboard(); - bClipped = true; - } - } - } - - if ( !bClipped ) { - globalOutputStream() << "Unable to register Windows clipboard formats, copy/paste between editors will not be possible\n"; - } -} - -void clipboard_paste( ClipboardPasteFunc paste ){ - UINT nClipboard = ::RegisterClipboardFormat( c_clipboard_format ); - if ( nClipboard > 0 && ::OpenClipboard( 0 ) ) { - if ( IsClipboardFormatAvailable( nClipboard ) ) { - HANDLE h = ::GetClipboardData( nClipboard ); - if ( h ) { - const char *buffer = reinterpret_cast( ::GlobalLock( h ) ); - std::size_t length = *reinterpret_cast( buffer ); - buffer += sizeof( std::size_t ); - BufferInputStream istream( buffer, length ); - paste( istream ); - ::GlobalUnlock( h ); - } - } - ::CloseClipboard(); - } -} - - -#endif diff --git a/tools/urt/libs/gtkutil/clipboard.h b/tools/urt/libs/gtkutil/clipboard.h deleted file mode 100644 index 580c425..0000000 --- a/tools/urt/libs/gtkutil/clipboard.h +++ /dev/null @@ -1,13 +0,0 @@ - -#if !defined( INCLUDED_GTKUTIL_CLIPBOARD_H ) -#define INCLUDED_GTKUTIL_CLIPBOARD_H - -class TextOutputStream; -typedef void ( *ClipboardCopyFunc )( TextOutputStream& ); -void clipboard_copy( ClipboardCopyFunc copy ); - -class TextInputStream; -typedef void ( *ClipboardPasteFunc )( TextInputStream& ); -void clipboard_paste( ClipboardPasteFunc paste ); - -#endif diff --git a/tools/urt/libs/gtkutil/closure.cpp b/tools/urt/libs/gtkutil/closure.cpp deleted file mode 100644 index 1fa581c..0000000 --- a/tools/urt/libs/gtkutil/closure.cpp +++ /dev/null @@ -1,2 +0,0 @@ - -#include "closure.h" diff --git a/tools/urt/libs/gtkutil/closure.h b/tools/urt/libs/gtkutil/closure.h deleted file mode 100644 index 0c9c733..0000000 --- a/tools/urt/libs/gtkutil/closure.h +++ /dev/null @@ -1,50 +0,0 @@ - -#if !defined( INCLUDED_GTKUTIL_CLOSURE_H ) -#define INCLUDED_GTKUTIL_CLOSURE_H - -#include -#include "generic/callback.h" - -inline void closure_destroy( gpointer data, GClosure* closure ){ - delete reinterpret_cast( data ); -} - -inline GClosure* create_cclosure( GCallback func, const Callback& callback ){ - return g_cclosure_new( func, new Callback( callback ), closure_destroy ); -} - -inline GValue GValue_default(){ - GValue value; - value.g_type = 0; - return value; -} - -inline gint object_get_int_property( GObject* object, const char* property ){ - GValue gvalue = GValue_default(); - g_value_init( &gvalue, G_TYPE_INT ); - g_object_get_property( object, property, &gvalue ); - return g_value_get_int( &gvalue ); -} - -inline void object_set_int_property( GObject* object, const char* property, gint value ){ - GValue gvalue = GValue_default(); - g_value_init( &gvalue, G_TYPE_INT ); - g_value_set_int( &gvalue, value ); - g_object_set_property( object, property, &gvalue ); -} - -inline gboolean object_get_boolean_property( GObject* object, const char* property ){ - GValue gvalue = GValue_default(); - g_value_init( &gvalue, G_TYPE_BOOLEAN ); - g_object_get_property( object, property, &gvalue ); - return g_value_get_boolean( &gvalue ); -} - -inline void object_set_boolean_property( GObject* object, const char* property, gboolean value ){ - GValue gvalue = GValue_default(); - g_value_init( &gvalue, G_TYPE_BOOLEAN ); - g_value_set_boolean( &gvalue, value ); - g_object_set_property( object, property, &gvalue ); -} - -#endif diff --git a/tools/urt/libs/gtkutil/container.cpp b/tools/urt/libs/gtkutil/container.cpp deleted file mode 100644 index 1a241cc..0000000 --- a/tools/urt/libs/gtkutil/container.cpp +++ /dev/null @@ -1,2 +0,0 @@ - -#include "container.h" diff --git a/tools/urt/libs/gtkutil/container.h b/tools/urt/libs/gtkutil/container.h deleted file mode 100644 index e1c7914..0000000 --- a/tools/urt/libs/gtkutil/container.h +++ /dev/null @@ -1,20 +0,0 @@ - -#if !defined( INCLUDED_GTKUTIL_CONTAINER_H ) -#define INCLUDED_GTKUTIL_CONTAINER_H - -#include - -inline GtkWidget* container_add_widget( GtkContainer* container, GtkWidget* widget ){ - gtk_container_add( container, widget ); - return widget; -} - -inline void container_remove( GtkWidget* item, gpointer data ){ - gtk_container_remove( GTK_CONTAINER( data ), item ); -} - -inline void container_remove_all( GtkContainer* container ){ - gtk_container_foreach( container, container_remove, container ); -} - -#endif diff --git a/tools/urt/libs/gtkutil/cursor.cpp b/tools/urt/libs/gtkutil/cursor.cpp deleted file mode 100644 index 1694d11..0000000 --- a/tools/urt/libs/gtkutil/cursor.cpp +++ /dev/null @@ -1,64 +0,0 @@ - -#include "cursor.h" - - -#include -#include -#include - - -GdkCursor* create_blank_cursor(){ - GdkPixmap *pixmap; - GdkBitmap *mask; - char buffer [( 32 * 32 ) / 8]; - memset( buffer, 0, ( 32 * 32 ) / 8 ); - GdkColor white = {0, 0xffff, 0xffff, 0xffff}; - GdkColor black = {0, 0x0000, 0x0000, 0x0000}; - pixmap = gdk_bitmap_create_from_data( 0, buffer, 32, 32 ); - mask = gdk_bitmap_create_from_data( 0, buffer, 32, 32 ); - GdkCursor *cursor = gdk_cursor_new_from_pixmap( pixmap, mask, &white, &black, 1, 1 ); - gdk_drawable_unref( pixmap ); - gdk_drawable_unref( mask ); - - return cursor; -} - -void blank_cursor( GtkWidget* widget ){ - GdkCursor* cursor = create_blank_cursor(); - gdk_window_set_cursor( widget->window, cursor ); - gdk_cursor_unref( cursor ); -} - -void default_cursor( GtkWidget* widget ){ - gdk_window_set_cursor( widget->window, 0 ); -} - - -#if defined( WIN32 ) - -#include - -void Sys_GetCursorPos( int *x, int *y ){ - POINT pos; - GetCursorPos( &pos ); - *x = pos.x; - *y = pos.y; -} - -void Sys_SetCursorPos( int x, int y ){ - SetCursorPos( x, y ); -} - -#else - -#include - -void Sys_GetCursorPos( int *x, int *y ){ - gdk_display_get_pointer( gdk_display_get_default(), 0, x, y, 0 ); -} - -void Sys_SetCursorPos( int x, int y ){ - XWarpPointer( GDK_DISPLAY(), None, GDK_ROOT_WINDOW(), 0, 0, 0, 0, x, y ); -} - -#endif diff --git a/tools/urt/libs/gtkutil/cursor.h b/tools/urt/libs/gtkutil/cursor.h deleted file mode 100644 index 23fb656..0000000 --- a/tools/urt/libs/gtkutil/cursor.h +++ /dev/null @@ -1,157 +0,0 @@ - -#if !defined( INCLUDED_GTKUTIL_CURSOR_H ) -#define INCLUDED_GTKUTIL_CURSOR_H - -#include -#include -#include - -#include "debugging/debugging.h" - -typedef struct _GdkCursor GdkCursor; -typedef struct _GtkWidget GtkWidget; - -GdkCursor* create_blank_cursor(); -void blank_cursor( GtkWidget* widget ); -void default_cursor( GtkWidget* widget ); -void Sys_GetCursorPos( int *x, int *y ); -void Sys_SetCursorPos( int x, int y ); - - - -class DeferredMotion -{ -guint m_handler; -typedef void ( *MotionFunction )( gdouble x, gdouble y, guint state, void* data ); -MotionFunction m_function; -void* m_data; -gdouble m_x; -gdouble m_y; -guint m_state; - -static gboolean deferred( DeferredMotion* self ){ - self->m_handler = 0; - self->m_function( self->m_x, self->m_y, self->m_state, self->m_data ); - return FALSE; -} -public: -DeferredMotion( MotionFunction function, void* data ) : m_handler( 0 ), m_function( function ), m_data( data ){ -} -void motion( gdouble x, gdouble y, guint state ){ - m_x = x; - m_y = y; - m_state = state; - if ( m_handler == 0 ) { - m_handler = g_idle_add( (GSourceFunc)deferred, this ); - } -} -static gboolean gtk_motion( GtkWidget *widget, GdkEventMotion *event, DeferredMotion* self ){ - self->motion( event->x, event->y, event->state ); - return FALSE; -} -}; - -class DeferredMotionDelta -{ -int m_delta_x; -int m_delta_y; -guint m_motion_handler; -typedef void ( *MotionDeltaFunction )( int x, int y, void* data ); -MotionDeltaFunction m_function; -void* m_data; - -static gboolean deferred_motion( gpointer data ){ - reinterpret_cast( data )->m_function( - reinterpret_cast( data )->m_delta_x, - reinterpret_cast( data )->m_delta_y, - reinterpret_cast( data )->m_data - ); - reinterpret_cast( data )->m_motion_handler = 0; - reinterpret_cast( data )->m_delta_x = 0; - reinterpret_cast( data )->m_delta_y = 0; - return FALSE; -} -public: -DeferredMotionDelta( MotionDeltaFunction function, void* data ) : m_delta_x( 0 ), m_delta_y( 0 ), m_motion_handler( 0 ), m_function( function ), m_data( data ){ -} -void flush(){ - if ( m_motion_handler != 0 ) { - g_source_remove( m_motion_handler ); - deferred_motion( this ); - } -} -void motion_delta( int x, int y, unsigned int state ){ - m_delta_x += x; - m_delta_y += y; - if ( m_motion_handler == 0 ) { - m_motion_handler = g_idle_add( deferred_motion, this ); - } -} -}; - -class FreezePointer -{ -unsigned int handle_motion; -int recorded_x, recorded_y; -typedef void ( *MotionDeltaFunction )( int x, int y, unsigned int state, void* data ); -MotionDeltaFunction m_function; -void* m_data; -public: -FreezePointer() : handle_motion( 0 ), m_function( 0 ), m_data( 0 ){ -} -static gboolean motion_delta( GtkWidget *widget, GdkEventMotion *event, FreezePointer* self ){ - int current_x, current_y; - Sys_GetCursorPos( ¤t_x, ¤t_y ); - int dx = current_x - self->recorded_x; - int dy = current_y - self->recorded_y; - if ( dx != 0 || dy != 0 ) { - //globalOutputStream() << "motion x: " << dx << ", y: " << dy << "\n"; - Sys_SetCursorPos( self->recorded_x, self->recorded_y ); - self->m_function( dx, dy, event->state, self->m_data ); - } - return FALSE; -} - -void freeze_pointer( GtkWidget* window, MotionDeltaFunction function, void* data ){ - ASSERT_MESSAGE( m_function == 0, "can't freeze pointer" ); - - blank_cursor( window ); - - const GdkEventMask mask = static_cast( GDK_POINTER_MOTION_MASK - | GDK_POINTER_MOTION_HINT_MASK - | GDK_BUTTON_MOTION_MASK - | GDK_BUTTON1_MOTION_MASK - | GDK_BUTTON2_MOTION_MASK - | GDK_BUTTON3_MOTION_MASK - | GDK_BUTTON_PRESS_MASK - | GDK_BUTTON_RELEASE_MASK - | GDK_VISIBILITY_NOTIFY_MASK ); - - //GdkGrabStatus status = - gdk_pointer_grab( window->window, TRUE, mask, window->window, 0, GDK_CURRENT_TIME ); - - Sys_GetCursorPos( &recorded_x, &recorded_y ); - - Sys_SetCursorPos( recorded_x, recorded_y ); - - m_function = function; - m_data = data; - - handle_motion = g_signal_connect( G_OBJECT( window ), "motion_notify_event", G_CALLBACK( motion_delta ), this ); -} - -void unfreeze_pointer( GtkWidget* window ){ - g_signal_handler_disconnect( G_OBJECT( window ), handle_motion ); - - m_function = 0; - m_data = 0; - - Sys_SetCursorPos( recorded_x, recorded_y ); - - gdk_pointer_ungrab( GDK_CURRENT_TIME ); - - default_cursor( window ); -} -}; - -#endif diff --git a/tools/urt/libs/gtkutil/dialog.cpp b/tools/urt/libs/gtkutil/dialog.cpp deleted file mode 100644 index b856dbe..0000000 --- a/tools/urt/libs/gtkutil/dialog.cpp +++ /dev/null @@ -1,256 +0,0 @@ - -#include "dialog.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "button.h" -#include "window.h" - -GtkVBox* create_dialog_vbox( int spacing, int border ){ - GtkVBox* vbox = GTK_VBOX( gtk_vbox_new( FALSE, spacing ) ); - gtk_widget_show( GTK_WIDGET( vbox ) ); - gtk_container_set_border_width( GTK_CONTAINER( vbox ), border ); - return vbox; -} - -GtkHBox* create_dialog_hbox( int spacing, int border ){ - GtkHBox* hbox = GTK_HBOX( gtk_hbox_new( FALSE, spacing ) ); - gtk_widget_show( GTK_WIDGET( hbox ) ); - gtk_container_set_border_width( GTK_CONTAINER( hbox ), border ); - return hbox; -} - -GtkFrame* create_dialog_frame( const char* label, GtkShadowType shadow ){ - GtkFrame* frame = GTK_FRAME( gtk_frame_new( label ) ); - gtk_widget_show( GTK_WIDGET( frame ) ); - gtk_frame_set_shadow_type( frame, shadow ); - return frame; -} - -GtkTable* create_dialog_table( unsigned int rows, unsigned int columns, unsigned int row_spacing, unsigned int col_spacing, int border ){ - GtkTable* table = GTK_TABLE( gtk_table_new( rows, columns, FALSE ) ); - gtk_widget_show( GTK_WIDGET( table ) ); - gtk_table_set_row_spacings( table, row_spacing ); - gtk_table_set_col_spacings( table, col_spacing ); - gtk_container_set_border_width( GTK_CONTAINER( table ), border ); - return table; -} - -GtkButton* create_dialog_button( const char* label, GCallback func, gpointer data ){ - GtkButton* button = GTK_BUTTON( gtk_button_new_with_label( label ) ); - gtk_widget_set_size_request( GTK_WIDGET( button ), 64, -1 ); - gtk_widget_show( GTK_WIDGET( button ) ); - g_signal_connect( G_OBJECT( button ), "clicked", func, data ); - return button; -} - -GtkWindow* create_dialog_window( GtkWindow* parent, const char* title, GCallback func, gpointer data, int default_w, int default_h ){ - GtkWindow* window = create_floating_window( title, parent ); - gtk_window_set_default_size( window, default_w, default_h ); - gtk_window_set_position( window, GTK_WIN_POS_CENTER_ON_PARENT ); - g_signal_connect( G_OBJECT( window ), "delete_event", func, data ); - - return window; -} - -gboolean modal_dialog_button_clicked( GtkWidget *widget, ModalDialogButton* button ){ - button->m_dialog.loop = false; - button->m_dialog.ret = button->m_value; - return TRUE; -} - -gboolean modal_dialog_delete( GtkWidget *widget, GdkEvent* event, ModalDialog* dialog ){ - dialog->loop = 0; - dialog->ret = eIDCANCEL; - return TRUE; -} - -EMessageBoxReturn modal_dialog_show( GtkWindow* window, ModalDialog& dialog ){ - gtk_grab_add( GTK_WIDGET( window ) ); - gtk_widget_show( GTK_WIDGET( window ) ); - - dialog.loop = true; - while ( dialog.loop ) - { - gtk_main_iteration(); - } - - gtk_widget_hide( GTK_WIDGET( window ) ); - gtk_grab_remove( GTK_WIDGET( window ) ); - - return dialog.ret; -} - -GtkButton* create_modal_dialog_button( const char* label, ModalDialogButton& button ){ - return create_dialog_button( label, G_CALLBACK( modal_dialog_button_clicked ), &button ); -} - -GtkWindow* create_modal_dialog_window( GtkWindow* parent, const char* title, ModalDialog& dialog, int default_w, int default_h ){ - return create_dialog_window( parent, title, G_CALLBACK( modal_dialog_delete ), &dialog, default_w, default_h ); -} - -GtkWindow* create_fixedsize_modal_dialog_window( GtkWindow* parent, const char* title, ModalDialog& dialog, int width, int height ){ - GtkWindow* window = create_modal_dialog_window( parent, title, dialog, width, height ); - - gtk_window_set_resizable( window, FALSE ); - gtk_window_set_modal( window, TRUE ); - gtk_window_set_position( window, GTK_WIN_POS_CENTER ); - - window_remove_minmax( window ); - - //gtk_widget_set_size_request(GTK_WIDGET(window), width, height); - //gtk_window_set_default_size(window, width, height); - //gtk_window_resize(window, width, height); - //GdkGeometry geometry = { width, height, -1, -1, width, height, -1, -1, -1, -1, GDK_GRAVITY_STATIC, }; - //gtk_window_set_geometry_hints(window, GTK_WIDGET(window), &geometry, (GdkWindowHints)(GDK_HINT_POS|GDK_HINT_MIN_SIZE|GDK_HINT_BASE_SIZE)); - - return window; -} - -gboolean dialog_button_ok( GtkWidget *widget, ModalDialog* data ){ - data->loop = false; - data->ret = eIDOK; - return TRUE; -} - -gboolean dialog_button_cancel( GtkWidget *widget, ModalDialog* data ){ - data->loop = false; - data->ret = eIDCANCEL; - return TRUE; -} - -gboolean dialog_button_yes( GtkWidget *widget, ModalDialog* data ){ - data->loop = false; - data->ret = eIDYES; - return TRUE; -} - -gboolean dialog_button_no( GtkWidget *widget, ModalDialog* data ){ - data->loop = false; - data->ret = eIDNO; - return TRUE; -} - -gboolean dialog_delete_callback( GtkWidget *widget, GdkEventAny* event, ModalDialog* data ){ - gtk_widget_hide( widget ); - data->loop = false; - return TRUE; -} - -GtkWindow* create_simple_modal_dialog_window( const char* title, ModalDialog& dialog, GtkWidget* contents ){ - GtkWindow* window = create_fixedsize_modal_dialog_window( 0, title, dialog ); - - GtkVBox* vbox1 = create_dialog_vbox( 8, 4 ); - gtk_container_add( GTK_CONTAINER( window ), GTK_WIDGET( vbox1 ) ); - - gtk_container_add( GTK_CONTAINER( vbox1 ), contents ); - - GtkAlignment* alignment = GTK_ALIGNMENT( gtk_alignment_new( 0.5, 0.0, 0.0, 0.0 ) ); - gtk_widget_show( GTK_WIDGET( alignment ) ); - gtk_box_pack_start( GTK_BOX( vbox1 ), GTK_WIDGET( alignment ), FALSE, FALSE, 0 ); - - GtkButton* button = create_dialog_button( "OK", G_CALLBACK( dialog_button_ok ), &dialog ); - gtk_container_add( GTK_CONTAINER( alignment ), GTK_WIDGET( button ) ); - - return window; -} - -RadioHBox RadioHBox_new( StringArrayRange names ){ - GtkHBox* hbox = GTK_HBOX( gtk_hbox_new( TRUE, 4 ) ); - gtk_widget_show( GTK_WIDGET( hbox ) ); - - GSList* group = 0; - GtkRadioButton* radio = 0; - for ( StringArrayRange::Iterator i = names.begin; i != names.end; ++i ) - { - radio = GTK_RADIO_BUTTON( gtk_radio_button_new_with_label( group, *i ) ); - gtk_widget_show( GTK_WIDGET( radio ) ); - gtk_box_pack_start( GTK_BOX( hbox ), GTK_WIDGET( radio ), FALSE, FALSE, 0 ); - - group = gtk_radio_button_get_group( radio ); - } - - return RadioHBox( hbox, radio ); -} - - -PathEntry PathEntry_new(){ - GtkFrame* frame = GTK_FRAME( gtk_frame_new( NULL ) ); - gtk_widget_show( GTK_WIDGET( frame ) ); - gtk_frame_set_shadow_type( frame, GTK_SHADOW_IN ); - - // path entry - GtkHBox* hbox = GTK_HBOX( gtk_hbox_new( FALSE, 0 ) ); - gtk_widget_show( GTK_WIDGET( hbox ) ); - - GtkEntry* entry = GTK_ENTRY( gtk_entry_new() ); - gtk_entry_set_has_frame( entry, FALSE ); - gtk_widget_show( GTK_WIDGET( entry ) ); - gtk_box_pack_start( GTK_BOX( hbox ), GTK_WIDGET( entry ), TRUE, TRUE, 0 ); - - // browse button - GtkButton* button = GTK_BUTTON( gtk_button_new() ); - button_set_icon( button, "ellipsis.bmp" ); - gtk_widget_show( GTK_WIDGET( button ) ); - gtk_box_pack_end( GTK_BOX( hbox ), GTK_WIDGET( button ), FALSE, FALSE, 0 ); - - gtk_container_add( GTK_CONTAINER( frame ), GTK_WIDGET( hbox ) ); - - return PathEntry( frame, entry, button ); -} - -void PathEntry_setPath( PathEntry& self, const char* path ){ - gtk_entry_set_text( self.m_entry, path ); -} -typedef ReferenceCaller1 PathEntrySetPathCaller; - -void BrowsedPathEntry_clicked( GtkWidget* widget, BrowsedPathEntry* self ){ - self->m_browse( PathEntrySetPathCaller( self->m_entry ) ); -} - -BrowsedPathEntry::BrowsedPathEntry( const BrowseCallback& browse ) : - m_entry( PathEntry_new() ), - m_browse( browse ){ - g_signal_connect( G_OBJECT( m_entry.m_button ), "clicked", G_CALLBACK( BrowsedPathEntry_clicked ), this ); -} - - -GtkLabel* DialogLabel_new( const char* name ){ - GtkLabel* label = GTK_LABEL( gtk_label_new( name ) ); - gtk_widget_show( GTK_WIDGET( label ) ); - gtk_misc_set_alignment( GTK_MISC( label ), 1, 0.5 ); - gtk_label_set_justify( label, GTK_JUSTIFY_LEFT ); - - return label; -} - -GtkTable* DialogRow_new( const char* name, GtkWidget* widget ){ - GtkTable* table = GTK_TABLE( gtk_table_new( 1, 3, TRUE ) ); - gtk_widget_show( GTK_WIDGET( table ) ); - - gtk_table_set_col_spacings( table, 4 ); - gtk_table_set_row_spacings( table, 0 ); - - gtk_table_attach( table, GTK_WIDGET( DialogLabel_new( name ) ), 0, 1, 0, 1, - (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); - - gtk_table_attach( table, widget, 1, 3, 0, 1, - (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ), - (GtkAttachOptions) ( 0 ), 0, 0 ); - - return table; -} - -void DialogVBox_packRow( GtkVBox* vbox, GtkWidget* row ){ - gtk_box_pack_start( GTK_BOX( vbox ), row, FALSE, FALSE, 0 ); -} diff --git a/tools/urt/libs/gtkutil/dialog.h b/tools/urt/libs/gtkutil/dialog.h deleted file mode 100644 index 46d6582..0000000 --- a/tools/urt/libs/gtkutil/dialog.h +++ /dev/null @@ -1,121 +0,0 @@ - -#if !defined( INCLUDED_GTKUTIL_DIALOG_H ) -#define INCLUDED_GTKUTIL_DIALOG_H - -#include "generic/callback.h" -#include "generic/arrayrange.h" -#include "qerplugin.h" -#include - -typedef int gint; -typedef gint gboolean; -typedef struct _GdkEventAny GdkEventAny; -typedef struct _GtkWidget GtkWidget; -typedef struct _GtkHBox GtkHBox; -typedef struct _GtkVBox GtkVBox; -typedef struct _GtkRadioButton GtkRadioButton; -typedef struct _GtkFrame GtkFrame; -typedef struct _GtkEntry GtkEntry; -typedef struct _GtkButton GtkButton; -typedef struct _GtkLabel GtkLabel; -typedef struct _GtkTable GtkTable; - - -struct ModalDialog -{ - ModalDialog() - : loop( true ), ret( eIDCANCEL ){ - } - bool loop; - EMessageBoxReturn ret; -}; - -struct ModalDialogButton -{ - ModalDialogButton( ModalDialog& dialog, EMessageBoxReturn value ) - : m_dialog( dialog ), m_value( value ){ - } - ModalDialog& m_dialog; - EMessageBoxReturn m_value; -}; - -typedef void ( *GCallback )( void ); -typedef void* gpointer; -typedef struct _GtkWindow GtkWindow; -typedef struct _GtkTable GtkTable; -typedef struct _GtkButton GtkButton; -typedef struct _GtkVBox GtkVBox; -typedef struct _GtkHBox GtkHBox; -typedef struct _GtkFrame GtkFrame; - -GtkWindow* create_fixedsize_modal_window( GtkWindow* parent, const char* title, int width, int height ); - -GtkWindow* create_dialog_window( GtkWindow* parent, const char* title, GCallback func, gpointer data, int default_w = -1, int default_h = -1 ); -GtkTable* create_dialog_table( unsigned int rows, unsigned int columns, unsigned int row_spacing, unsigned int col_spacing, int border = 0 ); -GtkButton* create_dialog_button( const char* label, GCallback func, gpointer data ); -GtkVBox* create_dialog_vbox( int spacing, int border = 0 ); -GtkHBox* create_dialog_hbox( int spacing, int border = 0 ); -GtkFrame* create_dialog_frame( const char* label, GtkShadowType shadow = GTK_SHADOW_ETCHED_IN ); - -GtkButton* create_modal_dialog_button( const char* label, ModalDialogButton& button ); -GtkWindow* create_modal_dialog_window( GtkWindow* parent, const char* title, ModalDialog& dialog, int default_w = -1, int default_h = -1 ); -GtkWindow* create_fixedsize_modal_dialog_window( GtkWindow* parent, const char* title, ModalDialog& dialog, int width = -1, int height = -1 ); -EMessageBoxReturn modal_dialog_show( GtkWindow* window, ModalDialog& dialog ); - - -gboolean dialog_button_ok( GtkWidget *widget, ModalDialog* data ); -gboolean dialog_button_cancel( GtkWidget *widget, ModalDialog* data ); -gboolean dialog_button_yes( GtkWidget *widget, ModalDialog* data ); -gboolean dialog_button_no( GtkWidget *widget, ModalDialog* data ); -gboolean dialog_delete_callback( GtkWidget *widget, GdkEventAny* event, ModalDialog* data ); - -GtkWindow* create_simple_modal_dialog_window( const char* title, ModalDialog& dialog, GtkWidget* contents ); - -class RadioHBox -{ -public: -GtkHBox* m_hbox; -GtkRadioButton* m_radio; -RadioHBox( GtkHBox* hbox, GtkRadioButton* radio ) : - m_hbox( hbox ), - m_radio( radio ){ -} -}; - -RadioHBox RadioHBox_new( StringArrayRange names ); - - -class PathEntry -{ -public: -GtkFrame* m_frame; -GtkEntry* m_entry; -GtkButton* m_button; -PathEntry( GtkFrame* frame, GtkEntry* entry, GtkButton* button ) : - m_frame( frame ), - m_entry( entry ), - m_button( button ){ -} -}; - -PathEntry PathEntry_new(); - -class BrowsedPathEntry -{ -public: -typedef Callback1 SetPathCallback; -typedef Callback1 BrowseCallback; - -PathEntry m_entry; -BrowseCallback m_browse; - -BrowsedPathEntry( const BrowseCallback& browse ); -}; - -GtkLabel* DialogLabel_new( const char* name ); -GtkTable* DialogRow_new( const char* name, GtkWidget* widget ); -typedef struct _GtkVBox GtkVBox; -void DialogVBox_packRow( GtkVBox* vbox, GtkWidget* row ); - - -#endif diff --git a/tools/urt/libs/gtkutil/entry.cpp b/tools/urt/libs/gtkutil/entry.cpp deleted file mode 100644 index b4f57f2..0000000 --- a/tools/urt/libs/gtkutil/entry.cpp +++ /dev/null @@ -1,2 +0,0 @@ - -#include "entry.h" diff --git a/tools/urt/libs/gtkutil/entry.h b/tools/urt/libs/gtkutil/entry.h deleted file mode 100644 index 0ec6c45..0000000 --- a/tools/urt/libs/gtkutil/entry.h +++ /dev/null @@ -1,37 +0,0 @@ - -#if !defined( INCLUDED_GTKUTIL_ENTRY_H ) -#define INCLUDED_GTKUTIL_ENTRY_H - -#include -#include -#include - -inline void entry_set_string( GtkEntry* entry, const char* string ){ - gtk_entry_set_text( entry, string ); -} - -inline void entry_set_int( GtkEntry* entry, int i ){ - char buf[32]; - sprintf( buf, "%d", i ); - entry_set_string( entry, buf ); -} - -inline void entry_set_float( GtkEntry* entry, float f ){ - char buf[32]; - sprintf( buf, "%g", f ); - entry_set_string( entry, buf ); -} - -inline const char* entry_get_string( GtkEntry* entry ){ - return gtk_entry_get_text( entry ); -} - -inline int entry_get_int( GtkEntry* entry ){ - return atoi( entry_get_string( entry ) ); -} - -inline double entry_get_float( GtkEntry* entry ){ - return atof( entry_get_string( entry ) ); -} - -#endif diff --git a/tools/urt/libs/gtkutil/filechooser.cpp b/tools/urt/libs/gtkutil/filechooser.cpp deleted file mode 100644 index 1b9f8e6..0000000 --- a/tools/urt/libs/gtkutil/filechooser.cpp +++ /dev/null @@ -1,434 +0,0 @@ - -#include "filechooser.h" - -#include "ifiletypes.h" - -#include -#include -#include -#include -#include -#include -#include - -#include "string/string.h" -#include "stream/stringstream.h" -#include "container/array.h" -#include "os/path.h" -#include "os/file.h" - -#include "messagebox.h" - - -struct filetype_pair_t -{ - filetype_pair_t() - : m_moduleName( "" ){ - } - filetype_pair_t( const char* moduleName, filetype_t type ) - : m_moduleName( moduleName ), m_type( type ){ - } - const char* m_moduleName; - filetype_t m_type; -}; - -class FileTypeList : public IFileTypeList -{ -struct filetype_copy_t -{ - filetype_copy_t( const filetype_pair_t& other ) - : m_moduleName( other.m_moduleName ), m_name( other.m_type.name ), m_pattern( other.m_type.pattern ){ - } - CopiedString m_moduleName; - CopiedString m_name; - CopiedString m_pattern; -}; - -typedef std::list Types; -Types m_types; -public: - -typedef Types::const_iterator const_iterator; -const_iterator begin() const { - return m_types.begin(); -} -const_iterator end() const { - return m_types.end(); -} - -std::size_t size() const { - return m_types.size(); -} - -void addType( const char* moduleName, filetype_t type ){ - m_types.push_back( filetype_pair_t( moduleName, type ) ); -} -}; - -#ifdef WIN32 - -class Win32Filters -{ -const FileTypeList& m_types; -Array m_filters; -public: -Win32Filters( const FileTypeList& typeList ) : m_types( typeList ){ - std::size_t len = 0; - for ( FileTypeList::const_iterator i = m_types.begin(); i != m_types.end(); ++i ) - { - len = len + strlen( ( *i ).m_name.c_str() ) + strlen( ( *i ).m_pattern.c_str() ) * 2 + 5; - } - m_filters.resize( len + 1 ); // length + null char - char *w = m_filters.data(); - for ( FileTypeList::const_iterator i = m_types.begin(); i != m_types.end(); ++i ) - { - for ( const char *r = ( *i ).m_name.c_str(); *r != '\0'; r++, w++ ) - { - *w = *r; - } - *w++ = ' '; - *w++ = '('; - for ( const char *r = ( *i ).m_pattern.c_str(); *r != '\0'; r++, w++ ) - { - *w = *r; - } - *w++ = ')'; - *w++ = '\0'; - for ( const char *r = ( *i ).m_pattern.c_str(); *r != '\0'; r++, w++ ) - { - *w = ( *r == ',' ) ? ';' : *r; - } - *w++ = '\0'; - } - m_filters[len] = '\0'; -} -filetype_pair_t getType( const char *filter ) const { - for ( FileTypeList::const_iterator i = m_types.begin(); i != m_types.end(); ++i ) - { - if ( string_equal( ( *i ).m_pattern.c_str(), filter ) ) { - return filetype_pair_t( ( *i ).m_moduleName.c_str(), filetype_t( ( *i ).m_name.c_str(), ( *i ).m_pattern.c_str() ) ); - } - } - return filetype_pair_t(); -} -const char* getFilters() const { - return m_filters.data(); -} -}; - -#define WIN32_LEAN_AND_MEAN -#include -#include - -static char szFile[MAX_PATH]; /* filename string */ - - -#define FILEDLG_CUSTOM_FILTER_LENGTH 64 -// to be used with the advanced file selector - -const char* file_dialog_show_win32( GtkWidget* parent, bool open, const char* title, const char* path, const char* pattern ){ - const char* r; - char* w; - filetype_t type; - FileTypeList typelist; - - if ( pattern == 0 ) { - pattern = "*"; - } - - GlobalFiletypes().getTypeList( pattern, &typelist ); - - Win32Filters filters( typelist ); - - // win32 dialog stores the selected "save as type" extension in the second null-terminated string - char customfilter[FILEDLG_CUSTOM_FILTER_LENGTH]; - - static OPENFILENAME ofn; /* common dialog box structure */ - static char szDirName[MAX_PATH]; /* directory string */ - static char szFile[MAX_PATH]; /* filename string */ - static char szFileTitle[MAX_PATH]; /* file title string */ - static int i, cbString; /* integer count variables */ - static HANDLE hf; /* file handle */ - - // do that the native way - /* Place the terminating null character in the szFile. */ - szFile[0] = '\0'; - customfilter[0] = customfilter[1] = customfilter[2] = '\0'; - - /* Set the members of the OPENFILENAME structure. */ - ofn.lStructSize = sizeof( OPENFILENAME ); - ofn.hwndOwner = (HWND)GDK_WINDOW_HWND( parent->window ); - ofn.nFilterIndex = 0; - ofn.lpstrFilter = filters.getFilters(); - ofn.lpstrCustomFilter = customfilter; - ofn.nMaxCustFilter = sizeof( customfilter ); - ofn.lpstrFile = szFile; - ofn.nMaxFile = sizeof( szFile ); - ofn.lpstrFileTitle = 0; // we don't need to get the name of the file - if ( path ) { - // szDirName: Radiant uses unix convention for paths internally - // Win32 (of course) and Gtk (who would have thought) expect the '\\' convention - // copy path, replacing dir separators as appropriate - for ( r = path, w = szDirName; *r != '\0'; r++ ) - *w++ = ( *r == '/' ) ? '\\' : *r; - // terminate string - *w = '\0'; - ofn.lpstrInitialDir = szDirName; - } - else{ ofn.lpstrInitialDir = 0; } - ofn.lpstrTitle = title; - ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_HIDEREADONLY; - - /* Display the Open dialog box. */ - // it's open or close depending on 'open' parameter - if ( open ) { - if ( !GetOpenFileName( &ofn ) ) { - return 0; // canceled - } - } - else - { - if ( !GetSaveFileName( &ofn ) ) { - return 0; // canceled - } - } - - if ( !string_equal( pattern, "*" ) ) { - type = filters.getType( customfilter + 1 ).m_type; - } - - // don't return an empty filename - if ( szFile[0] == '\0' ) { - return 0; - } - - // convert back to unix format - for ( w = szFile; *w != '\0'; w++ ) - { - if ( *w == '\\' ) { - *w = '/'; - } - } - // when saving, force an extension depending on filetype - /* \todo SPoG - file_dialog should return filetype information separately.. not force file extension.. */ - if ( !open && !string_equal( pattern, "*" ) ) { - // last ext separator - const char* extension = path_get_extension( szFile ); - // no extension - if ( string_empty( extension ) ) { - strcat( szFile, type.pattern + 1 ); - } - else - { - strcpy( szFile + ( extension - szFile ), type.pattern + 2 ); - } - } - - return szFile; -} - -#endif - - -class GTKMasks -{ -const FileTypeList& m_types; -public: -std::vector m_filters; -std::vector m_masks; - -GTKMasks( const FileTypeList& types ) : m_types( types ){ - m_masks.reserve( m_types.size() ); - for ( FileTypeList::const_iterator i = m_types.begin(); i != m_types.end(); ++i ) - { - std::size_t len = strlen( ( *i ).m_name.c_str() ) + strlen( ( *i ).m_pattern.c_str() ) + 3; - StringOutputStream buffer( len + 1 ); // length + null char - - buffer << ( *i ).m_name.c_str() << " <" << ( *i ).m_pattern.c_str() << ">"; - - m_masks.push_back( buffer.c_str() ); - } - - m_filters.reserve( m_types.size() ); - for ( FileTypeList::const_iterator i = m_types.begin(); i != m_types.end(); ++i ) - { - m_filters.push_back( ( *i ).m_pattern ); - } -} - -filetype_pair_t GetTypeForGTKMask( const char *mask ) const { - std::vector::const_iterator j = m_masks.begin(); - for ( FileTypeList::const_iterator i = m_types.begin(); i != m_types.end(); ++i, ++j ) - { - if ( string_equal( ( *j ).c_str(), mask ) ) { - return filetype_pair_t( ( *i ).m_moduleName.c_str(), filetype_t( ( *i ).m_name.c_str(), ( *i ).m_pattern.c_str() ) ); - } - } - return filetype_pair_t(); -} - -}; - -static char g_file_dialog_file[1024]; - -const char* file_dialog_show( GtkWidget* parent, bool open, const char* title, const char* path, const char* pattern ){ - filetype_t type; - - if ( pattern == 0 ) { - pattern = "*"; - } - - FileTypeList typelist; - GlobalFiletypes().getTypeList( pattern, &typelist ); - - GTKMasks masks( typelist ); - - if ( title == 0 ) { - title = open ? "Open File" : "Save File"; - } - - GtkWidget* dialog; - if ( open ) { - dialog = gtk_file_chooser_dialog_new( title, - GTK_WINDOW( parent ), - GTK_FILE_CHOOSER_ACTION_OPEN, - GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL, - GTK_STOCK_OPEN, GTK_RESPONSE_ACCEPT, - NULL ); - } - else - { - dialog = gtk_file_chooser_dialog_new( title, - GTK_WINDOW( parent ), - GTK_FILE_CHOOSER_ACTION_SAVE, - GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL, - GTK_STOCK_SAVE, GTK_RESPONSE_ACCEPT, - NULL ); - gtk_file_chooser_set_current_name( GTK_FILE_CHOOSER( dialog ), "unnamed" ); - } - - gtk_window_set_modal( GTK_WINDOW( dialog ), TRUE ); - gtk_window_set_position( GTK_WINDOW( dialog ), GTK_WIN_POS_CENTER_ON_PARENT ); - - // we expect an actual path below, if the path is 0 we might crash - if ( path != 0 && !string_empty( path ) ) { - ASSERT_MESSAGE( path_is_absolute( path ), "file_dialog_show: path not absolute: " << makeQuoted( path ) ); - - Array new_path( strlen( path ) + 1 ); - - // copy path, replacing dir separators as appropriate - Array::iterator w = new_path.begin(); - for ( const char* r = path; *r != '\0'; ++r ) - { - *w++ = ( *r == '/' ) ? G_DIR_SEPARATOR : *r; - } - // remove separator from end of path if required - if ( *( w - 1 ) == G_DIR_SEPARATOR ) { - --w; - } - // terminate string - *w = '\0'; - - gtk_file_chooser_set_current_folder( GTK_FILE_CHOOSER( dialog ), new_path.data() ); - } - - // we should add all important paths as shortcut folder... - // gtk_file_chooser_add_shortcut_folder(GTK_FILE_CHOOSER(dialog), "/tmp/", NULL); - - - for ( std::size_t i = 0; i < masks.m_filters.size(); ++i ) - { - GtkFileFilter* filter = gtk_file_filter_new(); - gtk_file_filter_add_pattern( filter, masks.m_filters[i].c_str() ); - gtk_file_filter_set_name( filter, masks.m_masks[i].c_str() ); - gtk_file_chooser_add_filter( GTK_FILE_CHOOSER( dialog ), filter ); - } - - if ( gtk_dialog_run( GTK_DIALOG( dialog ) ) == GTK_RESPONSE_ACCEPT ) { - strcpy( g_file_dialog_file, gtk_file_chooser_get_filename( GTK_FILE_CHOOSER( dialog ) ) ); - - if ( !string_equal( pattern, "*" ) ) { - GtkFileFilter* filter = gtk_file_chooser_get_filter( GTK_FILE_CHOOSER( dialog ) ); - type = masks.GetTypeForGTKMask( gtk_file_filter_get_name( filter ) ).m_type; - // last ext separator - const char* extension = path_get_extension( g_file_dialog_file ); - // no extension - if ( string_empty( extension ) ) { - strcat( g_file_dialog_file, type.pattern + 1 ); - } - else - { - strcpy( g_file_dialog_file + ( extension - g_file_dialog_file ), type.pattern + 2 ); - } - } - - // convert back to unix format - for ( char* w = g_file_dialog_file; *w != '\0'; w++ ) - { - if ( *w == '\\' ) { - *w = '/'; - } - } - } - else - { - g_file_dialog_file[0] = '\0'; - } - - gtk_widget_destroy( dialog ); - - // don't return an empty filename - if ( g_file_dialog_file[0] == '\0' ) { - return NULL; - } - - return g_file_dialog_file; -} - -char* dir_dialog( GtkWidget* parent, const char* title, const char* path ){ - GtkWidget* dialog = gtk_file_chooser_dialog_new( title, - GTK_WINDOW( parent ), - GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER, - GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL, - GTK_STOCK_OPEN, GTK_RESPONSE_ACCEPT, - NULL ); - - gtk_window_set_modal( GTK_WINDOW( dialog ), TRUE ); - gtk_window_set_position( GTK_WINDOW( dialog ), GTK_WIN_POS_CENTER_ON_PARENT ); - - if ( !string_empty( path ) ) { - gtk_file_chooser_set_current_folder( GTK_FILE_CHOOSER( dialog ), path ); - } - - char* filename = 0; - if ( gtk_dialog_run( GTK_DIALOG( dialog ) ) == GTK_RESPONSE_ACCEPT ) { - filename = gtk_file_chooser_get_filename( GTK_FILE_CHOOSER( dialog ) ); - } - - gtk_widget_destroy( dialog ); - - return filename; -} - - -#ifdef WIN32 -bool g_FileChooser_nativeGUI = true; -#endif - -const char* file_dialog( GtkWidget* parent, bool open, const char* title, const char* path, const char* pattern ){ - for (;; ) - { - const char* file = -#ifdef WIN32 - g_FileChooser_nativeGUI - ? file_dialog_show_win32( parent, open, title, path, pattern ) : -#endif - file_dialog_show( parent, open, title, path, pattern ); - - if ( open - || !file_exists( file ) - || gtk_MessageBox( parent, "The file specified already exists.\nDo you want to replace it?", title, eMB_NOYES, eMB_ICONQUESTION ) == eIDYES ) { - return file; - } - } -} diff --git a/tools/urt/libs/gtkutil/filechooser.h b/tools/urt/libs/gtkutil/filechooser.h deleted file mode 100644 index 730bb99..0000000 --- a/tools/urt/libs/gtkutil/filechooser.h +++ /dev/null @@ -1,22 +0,0 @@ - -#if !defined( INCLUDED_GTKUTIL_FILECHOOSER_H ) -#define INCLUDED_GTKUTIL_FILECHOOSER_H - -/// \file -/// GTK+ file-chooser dialogs. - -#ifdef WIN32 -extern bool g_FileChooser_nativeGUI; -#endif - -typedef struct _GtkWidget GtkWidget; -const char* file_dialog( GtkWidget *parent, bool open, const char* title, const char* path = 0, const char* pattern = 0 ); - - -/// \brief Prompts the user to browse for a directory. -/// The prompt window will be transient to \p parent. -/// The directory will initially default to \p path, which must be an absolute path. -/// The returned string is allocated with \c g_malloc and must be freed with \c g_free. -char* dir_dialog( GtkWidget *parent, const char* title = "Choose Directory", const char* path = "" ); - -#endif diff --git a/tools/urt/libs/gtkutil/frame.cpp b/tools/urt/libs/gtkutil/frame.cpp deleted file mode 100644 index f1d61ec..0000000 --- a/tools/urt/libs/gtkutil/frame.cpp +++ /dev/null @@ -1,13 +0,0 @@ - -#include "frame.h" - -#include - -GtkFrame* create_framed_widget( GtkWidget* widget ){ - GtkFrame* frame = GTK_FRAME( gtk_frame_new( 0 ) ); - gtk_widget_show( GTK_WIDGET( frame ) ); - gtk_frame_set_shadow_type( frame, GTK_SHADOW_IN ); - gtk_container_add( GTK_CONTAINER( frame ), widget ); - gtk_widget_show( GTK_WIDGET( widget ) ); - return frame; -} diff --git a/tools/urt/libs/gtkutil/frame.h b/tools/urt/libs/gtkutil/frame.h deleted file mode 100644 index b380c1a..0000000 --- a/tools/urt/libs/gtkutil/frame.h +++ /dev/null @@ -1,9 +0,0 @@ - -#if !defined( INCLUDED_GTKUTIL_FRAME_H ) -#define INCLUDED_GTKUTIL_FRAME_H - -typedef struct _GtkWidget GtkWidget; -typedef struct _GtkFrame GtkFrame; -GtkFrame* create_framed_widget( GtkWidget* widget ); - -#endif diff --git a/tools/urt/libs/gtkutil/glfont.cpp b/tools/urt/libs/gtkutil/glfont.cpp deleted file mode 100644 index d1e951b..0000000 --- a/tools/urt/libs/gtkutil/glfont.cpp +++ /dev/null @@ -1,33 +0,0 @@ - -#include "glfont.h" - -#include "igl.h" -#include - -GLFont glfont_create( const char* font_string ){ - GLuint font_list_base = glGenLists( 256 ); - gint font_height = 0; - - PangoFontDescription* font_desc = pango_font_description_from_string( font_string ); - - PangoFont* font = gdk_gl_font_use_pango_font( font_desc, 0, 256, font_list_base ); - - if ( font != 0 ) { - PangoFontMetrics* font_metrics = pango_font_get_metrics( font, 0 ); - - font_height = pango_font_metrics_get_ascent( font_metrics ) + - pango_font_metrics_get_descent( font_metrics ); - font_height = PANGO_PIXELS( font_height ); - - pango_font_metrics_unref( font_metrics ); - } - - pango_font_description_free( font_desc ); - - return GLFont( font_list_base, font_height ); -} - -void glfont_release( GLFont& font ){ - glDeleteLists( font.getDisplayList(), 256 ); - font = GLFont( 0, 0 ); -} diff --git a/tools/urt/libs/gtkutil/glfont.h b/tools/urt/libs/gtkutil/glfont.h deleted file mode 100644 index 7fa29a8..0000000 --- a/tools/urt/libs/gtkutil/glfont.h +++ /dev/null @@ -1,25 +0,0 @@ - -#if !defined( INCLUDED_GTKUTIL_GLFONT_H ) -#define INCLUDED_GTKUTIL_GLFONT_H - -typedef unsigned int GLuint; - -class GLFont -{ -GLuint m_displayList; -int m_pixelHeight; -public: -GLFont( GLuint displayList, int pixelHeight ) : m_displayList( displayList ), m_pixelHeight( pixelHeight ){ -} -GLuint getDisplayList() const { - return m_displayList; -} -int getPixelHeight() const { - return m_pixelHeight; -} -}; - -GLFont glfont_create( const char* font_string ); -void glfont_release( GLFont& font ); - -#endif diff --git a/tools/urt/libs/gtkutil/glwidget.cpp b/tools/urt/libs/gtkutil/glwidget.cpp deleted file mode 100644 index 956d128..0000000 --- a/tools/urt/libs/gtkutil/glwidget.cpp +++ /dev/null @@ -1,237 +0,0 @@ - -// OpenGL widget based on GtkGLExt - -#include "glwidget.h" - -#include "debugging/debugging.h" - -#include "igl.h" - -#include -#include - -#include "pointer.h" - -void ( *GLWidget_sharedContextCreated )() = 0; -void ( *GLWidget_sharedContextDestroyed )() = 0; - - -typedef int* attribs_t; -struct config_t -{ - const char* name; - attribs_t attribs; -}; -typedef const config_t* configs_iterator; - -int config_rgba32[] = { - GDK_GL_RGBA, - GDK_GL_DOUBLEBUFFER, - GDK_GL_BUFFER_SIZE, 24, - GDK_GL_ATTRIB_LIST_NONE, -}; - -int config_rgba[] = { - GDK_GL_RGBA, - GDK_GL_DOUBLEBUFFER, - GDK_GL_BUFFER_SIZE, 16, - GDK_GL_ATTRIB_LIST_NONE, -}; - -const config_t configs[] = { - { - "colour-buffer = 32bpp, depth-buffer = none", - config_rgba32, - }, - { - "colour-buffer = 16bpp, depth-buffer = none", - config_rgba, - } -}; - -GdkGLConfig* glconfig_new(){ - GdkGLConfig* glconfig = 0; - - for ( configs_iterator i = configs, end = configs + 2; i != end; ++i ) - { - glconfig = gdk_gl_config_new( ( *i ).attribs ); - if ( glconfig != 0 ) { - globalOutputStream() << "OpenGL window configuration: " << ( *i ).name << "\n"; - return glconfig; - } - } - - globalOutputStream() << "OpenGL window configuration: colour-buffer = auto, depth-buffer = none\n"; - return gdk_gl_config_new_by_mode( (GdkGLConfigMode)( GDK_GL_MODE_RGBA | GDK_GL_MODE_DOUBLE ) ); -} - -int config_rgba32_depth32[] = { - GDK_GL_RGBA, - GDK_GL_DOUBLEBUFFER, - GDK_GL_BUFFER_SIZE, 24, - GDK_GL_DEPTH_SIZE, 32, - GDK_GL_ATTRIB_LIST_NONE, -}; - -int config_rgba32_depth24[] = { - GDK_GL_RGBA, - GDK_GL_DOUBLEBUFFER, - GDK_GL_BUFFER_SIZE, 24, - GDK_GL_DEPTH_SIZE, 24, - GDK_GL_ATTRIB_LIST_NONE, -}; - -int config_rgba32_depth16[] = { - GDK_GL_RGBA, - GDK_GL_DOUBLEBUFFER, - GDK_GL_BUFFER_SIZE, 24, - GDK_GL_DEPTH_SIZE, 16, - GDK_GL_ATTRIB_LIST_NONE, -}; - -int config_rgba32_depth[] = { - GDK_GL_RGBA, - GDK_GL_DOUBLEBUFFER, - GDK_GL_BUFFER_SIZE, 24, - GDK_GL_DEPTH_SIZE, 1, - GDK_GL_ATTRIB_LIST_NONE, -}; - -int config_rgba_depth16[] = { - GDK_GL_RGBA, - GDK_GL_DOUBLEBUFFER, - GDK_GL_BUFFER_SIZE, 16, - GDK_GL_DEPTH_SIZE, 16, - GDK_GL_ATTRIB_LIST_NONE, -}; - -int config_rgba_depth[] = { - GDK_GL_RGBA, - GDK_GL_DOUBLEBUFFER, - GDK_GL_BUFFER_SIZE, 16, - GDK_GL_DEPTH_SIZE, 1, - GDK_GL_ATTRIB_LIST_NONE, -}; - -const config_t configs_with_depth[] = -{ - { - "colour-buffer = 32bpp, depth-buffer = 32bpp", - config_rgba32_depth32, - }, - { - "colour-buffer = 32bpp, depth-buffer = 24bpp", - config_rgba32_depth24, - }, - { - "colour-buffer = 32bpp, depth-buffer = 16bpp", - config_rgba32_depth16, - }, - { - "colour-buffer = 32bpp, depth-buffer = auto", - config_rgba32_depth, - }, - { - "colour-buffer = 16bpp, depth-buffer = 16bpp", - config_rgba_depth16, - }, - { - "colour-buffer = auto, depth-buffer = auto", - config_rgba_depth, - }, -}; - -GdkGLConfig* glconfig_new_with_depth(){ - GdkGLConfig* glconfig = 0; - - for ( configs_iterator i = configs_with_depth, end = configs_with_depth + 6; i != end; ++i ) - { - glconfig = gdk_gl_config_new( ( *i ).attribs ); - if ( glconfig != 0 ) { - globalOutputStream() << "OpenGL window configuration: " << ( *i ).name << "\n"; - return glconfig; - } - } - - globalOutputStream() << "OpenGL window configuration: colour-buffer = auto, depth-buffer = auto (fallback)\n"; - return gdk_gl_config_new_by_mode( (GdkGLConfigMode)( GDK_GL_MODE_RGBA | GDK_GL_MODE_DOUBLE | GDK_GL_MODE_DEPTH ) ); -} - -unsigned int g_context_count = 0; - -namespace -{ -GtkWidget* g_shared = 0; -} - -gint glwidget_context_created( GtkWidget* widget, gpointer data ){ - if ( ++g_context_count == 1 ) { - g_shared = widget; - gtk_widget_ref( g_shared ); - - glwidget_make_current( g_shared ); - GlobalOpenGL().contextValid = true; - - GLWidget_sharedContextCreated(); - } - return FALSE; -} - -gint glwidget_context_destroyed( GtkWidget* widget, gpointer data ){ - if ( --g_context_count == 0 ) { - GlobalOpenGL().contextValid = false; - - GLWidget_sharedContextDestroyed(); - - gtk_widget_unref( g_shared ); - g_shared = 0; - } - return FALSE; -} - -gboolean glwidget_enable_gl( GtkWidget* widget, GtkWidget* widget2, gpointer data ){ - if ( widget2 == 0 && !gtk_widget_is_gl_capable( widget ) ) { - GdkGLConfig* glconfig = ( g_object_get_data( G_OBJECT( widget ), "zbuffer" ) ) ? glconfig_new_with_depth() : glconfig_new(); - ASSERT_MESSAGE( glconfig != 0, "failed to create OpenGL config" ); - - gtk_widget_set_gl_capability( widget, glconfig, g_shared != 0 ? gtk_widget_get_gl_context( g_shared ) : 0, TRUE, GDK_GL_RGBA_TYPE ); - - gtk_widget_realize( widget ); - if ( g_shared == 0 ) { - g_shared = widget; - } - - // free glconfig? - } - return FALSE; -} - -GtkWidget* glwidget_new( gboolean zbuffer ){ - GtkWidget* widget = gtk_drawing_area_new(); - - g_object_set_data( G_OBJECT( widget ), "zbuffer", gint_to_pointer( zbuffer ) ); - - g_signal_connect( G_OBJECT( widget ), "hierarchy-changed", G_CALLBACK( glwidget_enable_gl ), 0 ); - - g_signal_connect( G_OBJECT( widget ), "realize", G_CALLBACK( glwidget_context_created ), 0 ); - g_signal_connect( G_OBJECT( widget ), "unrealize", G_CALLBACK( glwidget_context_destroyed ), 0 ); - - return widget; -} - -void glwidget_destroy_context( GtkWidget *widget ){ -} - -void glwidget_create_context( GtkWidget *widget ){ -} - -void glwidget_swap_buffers( GtkWidget *widget ){ - GdkGLDrawable *gldrawable = gtk_widget_get_gl_drawable( widget ); - gdk_gl_drawable_swap_buffers( gldrawable ); -} - -gboolean glwidget_make_current( GtkWidget *widget ){ - GdkGLContext *glcontext = gtk_widget_get_gl_context( widget ); - GdkGLDrawable *gldrawable = gtk_widget_get_gl_drawable( widget ); - return gdk_gl_drawable_gl_begin( gldrawable, glcontext ); -} diff --git a/tools/urt/libs/gtkutil/glwidget.h b/tools/urt/libs/gtkutil/glwidget.h deleted file mode 100644 index 38de928..0000000 --- a/tools/urt/libs/gtkutil/glwidget.h +++ /dev/null @@ -1,19 +0,0 @@ - -#if !defined( INCLUDED_GTKUTIL_GLWIDGET_H ) -#define INCLUDED_GTKUTIL_GLWIDGET_H - -typedef struct _GtkWidget GtkWidget; -typedef int gint; -typedef gint gboolean; - -GtkWidget* glwidget_new( gboolean zbuffer ); -void glwidget_swap_buffers( GtkWidget* widget ); -gboolean glwidget_make_current( GtkWidget* widget ); -void glwidget_destroy_context( GtkWidget* widget ); -void glwidget_create_context( GtkWidget* widget ); - -extern void ( *GLWidget_sharedContextCreated )(); -extern void ( *GLWidget_sharedContextDestroyed )(); - - -#endif diff --git a/tools/urt/libs/gtkutil/gtkutil.vcproj b/tools/urt/libs/gtkutil/gtkutil.vcproj deleted file mode 100644 index e5f548b..0000000 --- a/tools/urt/libs/gtkutil/gtkutil.vcproj +++ /dev/null @@ -1,255 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/tools/urt/libs/gtkutil/idledraw.cpp b/tools/urt/libs/gtkutil/idledraw.cpp deleted file mode 100644 index b761a17..0000000 --- a/tools/urt/libs/gtkutil/idledraw.cpp +++ /dev/null @@ -1,2 +0,0 @@ - -#include "idledraw.h" diff --git a/tools/urt/libs/gtkutil/idledraw.h b/tools/urt/libs/gtkutil/idledraw.h deleted file mode 100644 index c6ac8d7..0000000 --- a/tools/urt/libs/gtkutil/idledraw.h +++ /dev/null @@ -1,41 +0,0 @@ - -#if !defined( INCLUDED_GTKUTIL_IDLEDRAW_H ) -#define INCLUDED_GTKUTIL_IDLEDRAW_H - -#include - -#include "generic/callback.h" - -class IdleDraw -{ -Callback m_draw; -unsigned int m_handler; -static gboolean draw( gpointer data ){ - reinterpret_cast( data )->m_draw(); - reinterpret_cast( data )->m_handler = 0; - return FALSE; -} -public: -IdleDraw( const Callback& draw ) : m_draw( draw ), m_handler( 0 ){ -} -~IdleDraw(){ - if ( m_handler != 0 ) { - g_source_remove( m_handler ); - } -} -void queueDraw(){ - if ( m_handler == 0 ) { - m_handler = g_idle_add( &draw, this ); - } -} -typedef MemberCaller QueueDrawCaller; - -void flush(){ - if ( m_handler != 0 ) { - draw( this ); - } -} -}; - - -#endif diff --git a/tools/urt/libs/gtkutil/image.cpp b/tools/urt/libs/gtkutil/image.cpp deleted file mode 100644 index de7d625..0000000 --- a/tools/urt/libs/gtkutil/image.cpp +++ /dev/null @@ -1,66 +0,0 @@ - -#include "image.h" - -#include -#include - -#include "string/string.h" -#include "stream/stringstream.h" -#include "stream/textstream.h" - - -namespace -{ -CopiedString g_bitmapsPath; -} - -void BitmapsPath_set( const char* path ){ - g_bitmapsPath = path; -} - -GdkPixbuf* pixbuf_new_from_file_with_mask( const char* filename ){ - GdkPixbuf* rgb = gdk_pixbuf_new_from_file( filename, 0 ); - if ( rgb == 0 ) { - return 0; - } - else - { - GdkPixbuf* rgba = gdk_pixbuf_add_alpha( rgb, TRUE, 255, 0, 255 ); - gdk_pixbuf_unref( rgb ); - return rgba; - } -} - -GtkImage* image_new_from_file_with_mask( const char* filename ){ - GdkPixbuf* rgba = pixbuf_new_from_file_with_mask( filename ); - if ( rgba == 0 ) { - return 0; - } - else - { - GtkImage* image = GTK_IMAGE( gtk_image_new_from_pixbuf( rgba ) ); - gdk_pixbuf_unref( rgba ); - return image; - } -} - -GtkImage* image_new_missing(){ - return GTK_IMAGE( gtk_image_new_from_stock( GTK_STOCK_MISSING_IMAGE, GTK_ICON_SIZE_SMALL_TOOLBAR ) ); -} - -GtkImage* new_image( const char* filename ){ - { - GtkImage* image = image_new_from_file_with_mask( filename ); - if ( image != 0 ) { - return image; - } - } - - return image_new_missing(); -} - -GtkImage* new_local_image( const char* filename ){ - StringOutputStream fullPath( 256 ); - fullPath << g_bitmapsPath.c_str() << filename; - return new_image( fullPath.c_str() ); -} diff --git a/tools/urt/libs/gtkutil/image.h b/tools/urt/libs/gtkutil/image.h deleted file mode 100644 index f2f4cf3..0000000 --- a/tools/urt/libs/gtkutil/image.h +++ /dev/null @@ -1,16 +0,0 @@ - -#if !defined( INCLUDED_GTKUTIL_IMAGE_H ) -#define INCLUDED_GTKUTIL_IMAGE_H - -void BitmapsPath_set( const char* path ); - -typedef struct _GtkImage GtkImage; -typedef struct _GdkPixbuf GdkPixbuf; - -GdkPixbuf* pixbuf_new_from_file_with_mask( const char* filename ); -GtkImage* image_new_from_file_with_mask( const char* filename ); -GtkImage* image_new_missing(); -GtkImage* new_image( const char* filename ); // filename is full path to image file -GtkImage* new_local_image( const char* filename ); // filename is relative to local bitmaps path - -#endif diff --git a/tools/urt/libs/gtkutil/menu.cpp b/tools/urt/libs/gtkutil/menu.cpp deleted file mode 100644 index 4c2d99e..0000000 --- a/tools/urt/libs/gtkutil/menu.cpp +++ /dev/null @@ -1,262 +0,0 @@ - -#include "menu.h" - -#include -#include -#include -#include -#include -#include - -#include "generic/callback.h" - -#include "accelerator.h" -#include "closure.h" -#include "container.h" -#include "pointer.h" - -void menu_add_item( GtkMenu* menu, GtkMenuItem* item ){ - gtk_container_add( GTK_CONTAINER( menu ), GTK_WIDGET( item ) ); -} - -GtkMenuItem* menu_separator( GtkMenu* menu ){ - GtkMenuItem* menu_item = GTK_MENU_ITEM( gtk_menu_item_new() ); - container_add_widget( GTK_CONTAINER( menu ), GTK_WIDGET( menu_item ) ); - gtk_widget_set_sensitive( GTK_WIDGET( menu_item ), FALSE ); - gtk_widget_show( GTK_WIDGET( menu_item ) ); - return menu_item; -} - -GtkTearoffMenuItem* menu_tearoff( GtkMenu* menu ){ - GtkTearoffMenuItem* menu_item = GTK_TEAROFF_MENU_ITEM( gtk_tearoff_menu_item_new() ); - container_add_widget( GTK_CONTAINER( menu ), GTK_WIDGET( menu_item ) ); -// gtk_widget_set_sensitive(GTK_WIDGET(menu_item), FALSE); -- controls whether menu is detachable - gtk_widget_show( GTK_WIDGET( menu_item ) ); - return menu_item; -} - -GtkMenuItem* new_sub_menu_item_with_mnemonic( const char* mnemonic ){ - GtkMenuItem* item = GTK_MENU_ITEM( gtk_menu_item_new_with_mnemonic( mnemonic ) ); - gtk_widget_show( GTK_WIDGET( item ) ); - - GtkWidget* sub_menu = gtk_menu_new(); - gtk_menu_item_set_submenu( item, sub_menu ); - - return item; -} - -GtkMenu* create_sub_menu_with_mnemonic( GtkMenuShell* parent, const char* mnemonic ){ - GtkMenuItem* item = new_sub_menu_item_with_mnemonic( mnemonic ); - container_add_widget( GTK_CONTAINER( parent ), GTK_WIDGET( item ) ); - return GTK_MENU( gtk_menu_item_get_submenu( item ) ); -} - -GtkMenu* create_sub_menu_with_mnemonic( GtkMenuBar* bar, const char* mnemonic ){ - return create_sub_menu_with_mnemonic( GTK_MENU_SHELL( bar ), mnemonic ); -} - -GtkMenu* create_sub_menu_with_mnemonic( GtkMenu* parent, const char* mnemonic ){ - return create_sub_menu_with_mnemonic( GTK_MENU_SHELL( parent ), mnemonic ); -} - -void activate_closure_callback( GtkWidget* widget, gpointer data ){ - ( *reinterpret_cast( data ) )( ); -} - -guint menu_item_connect_callback( GtkMenuItem* item, const Callback& callback ){ -#if 1 - return g_signal_connect_swapped( G_OBJECT( item ), "activate", G_CALLBACK( callback.getThunk() ), callback.getEnvironment() ); -#else - return g_signal_connect_closure( G_OBJECT( item ), "activate", create_cclosure( G_CALLBACK( activate_closure_callback ), callback ), FALSE ); -#endif -} - -guint check_menu_item_connect_callback( GtkCheckMenuItem* item, const Callback& callback ){ -#if 1 - guint handler = g_signal_connect_swapped( G_OBJECT( item ), "toggled", G_CALLBACK( callback.getThunk() ), callback.getEnvironment() ); -#else - guint handler = g_signal_connect_closure( G_OBJECT( item ), "toggled", create_cclosure( G_CALLBACK( activate_closure_callback ), callback ), TRUE ); -#endif - g_object_set_data( G_OBJECT( item ), "handler", gint_to_pointer( handler ) ); - return handler; -} - -GtkMenuItem* new_menu_item_with_mnemonic( const char *mnemonic, const Callback& callback ){ - GtkMenuItem* item = GTK_MENU_ITEM( gtk_menu_item_new_with_mnemonic( mnemonic ) ); - gtk_widget_show( GTK_WIDGET( item ) ); - menu_item_connect_callback( item, callback ); - return item; -} - -GtkMenuItem* create_menu_item_with_mnemonic( GtkMenu* menu, const char *mnemonic, const Callback& callback ){ - GtkMenuItem* item = new_menu_item_with_mnemonic( mnemonic, callback ); - container_add_widget( GTK_CONTAINER( menu ), GTK_WIDGET( item ) ); - return item; -} - -GtkCheckMenuItem* new_check_menu_item_with_mnemonic( const char* mnemonic, const Callback& callback ){ - GtkCheckMenuItem* item = GTK_CHECK_MENU_ITEM( gtk_check_menu_item_new_with_mnemonic( mnemonic ) ); - gtk_widget_show( GTK_WIDGET( item ) ); - check_menu_item_connect_callback( item, callback ); - return item; -} - -GtkCheckMenuItem* create_check_menu_item_with_mnemonic( GtkMenu* menu, const char* mnemonic, const Callback& callback ){ - GtkCheckMenuItem* item = new_check_menu_item_with_mnemonic( mnemonic, callback ); - container_add_widget( GTK_CONTAINER( menu ), GTK_WIDGET( item ) ); - return item; -} - -GtkRadioMenuItem* new_radio_menu_item_with_mnemonic( GSList** group, const char* mnemonic, const Callback& callback ){ - GtkRadioMenuItem* item = GTK_RADIO_MENU_ITEM( gtk_radio_menu_item_new_with_mnemonic( *group, mnemonic ) ); - if ( *group == 0 ) { - gtk_check_menu_item_set_state( GTK_CHECK_MENU_ITEM( item ), TRUE ); - } - *group = gtk_radio_menu_item_group( item ); - gtk_widget_show( GTK_WIDGET( item ) ); - check_menu_item_connect_callback( GTK_CHECK_MENU_ITEM( item ), callback ); - return item; -} - -GtkRadioMenuItem* create_radio_menu_item_with_mnemonic( GtkMenu* menu, GSList** group, const char* mnemonic, const Callback& callback ){ - GtkRadioMenuItem* item = new_radio_menu_item_with_mnemonic( group, mnemonic, callback ); - container_add_widget( GTK_CONTAINER( menu ), GTK_WIDGET( item ) ); - return item; -} - -void check_menu_item_set_active_no_signal( GtkCheckMenuItem* item, gboolean active ){ - guint handler_id = gpointer_to_int( g_object_get_data( G_OBJECT( item ), "handler" ) ); - g_signal_handler_block( G_OBJECT( item ), handler_id ); - gtk_check_menu_item_set_active( item, active ); - g_signal_handler_unblock( G_OBJECT( item ), handler_id ); -} - - - -void radio_menu_item_set_active_no_signal( GtkRadioMenuItem* item, gboolean active ){ - { - for ( GSList* l = gtk_radio_menu_item_get_group( item ); l != 0; l = g_slist_next( l ) ) - { - g_signal_handler_block( G_OBJECT( l->data ), gpointer_to_int( g_object_get_data( G_OBJECT( l->data ), "handler" ) ) ); - } - } - gtk_check_menu_item_set_active( GTK_CHECK_MENU_ITEM( item ), active ); - { - for ( GSList* l = gtk_radio_menu_item_get_group( item ); l != 0; l = g_slist_next( l ) ) - { - g_signal_handler_unblock( G_OBJECT( l->data ), gpointer_to_int( g_object_get_data( G_OBJECT( l->data ), "handler" ) ) ); - } - } -} - - -void menu_item_set_accelerator( GtkMenuItem* item, GClosure* closure ){ - GtkAccelLabel* accel_label = GTK_ACCEL_LABEL( gtk_bin_get_child( GTK_BIN( item ) ) ); - gtk_accel_label_set_accel_closure( accel_label, closure ); -} - -void accelerator_name( const Accelerator& accelerator, GString* gstring ){ - gboolean had_mod = FALSE; - if ( accelerator.modifiers & GDK_SHIFT_MASK ) { - g_string_append( gstring, "Shift" ); - had_mod = TRUE; - } - if ( accelerator.modifiers & GDK_CONTROL_MASK ) { - if ( had_mod ) { - g_string_append( gstring, "+" ); - } - g_string_append( gstring, "Ctrl" ); - had_mod = TRUE; - } - if ( accelerator.modifiers & GDK_MOD1_MASK ) { - if ( had_mod ) { - g_string_append( gstring, "+" ); - } - g_string_append( gstring, "Alt" ); - had_mod = TRUE; - } - - if ( had_mod ) { - g_string_append( gstring, "+" ); - } - if ( accelerator.key < 0x80 || ( accelerator.key > 0x80 && accelerator.key <= 0xff ) ) { - switch ( accelerator.key ) - { - case ' ': - g_string_append( gstring, "Space" ); - break; - case '\\': - g_string_append( gstring, "Backslash" ); - break; - default: - g_string_append_c( gstring, gchar( toupper( accelerator.key ) ) ); - break; - } - } - else - { - gchar *tmp; - - tmp = gtk_accelerator_name( accelerator.key, (GdkModifierType)0 ); - if ( tmp[0] != 0 && tmp[1] == 0 ) { - tmp[0] = gchar( toupper( tmp[0] ) ); - } - g_string_append( gstring, tmp ); - g_free( tmp ); - } -} - -void menu_item_set_accelerator( GtkMenuItem* item, Accelerator accelerator ){ - GtkAccelLabel* accel_label = GTK_ACCEL_LABEL( gtk_bin_get_child( GTK_BIN( item ) ) ); - - g_free( accel_label->accel_string ); - accel_label->accel_string = 0; - - GString* gstring = g_string_new( accel_label->accel_string ); - g_string_append( gstring, " " ); - - accelerator_name( accelerator, gstring ); - - g_free( accel_label->accel_string ); - accel_label->accel_string = gstring->str; - g_string_free( gstring, FALSE ); - - if ( !accel_label->accel_string ) { - accel_label->accel_string = g_strdup( "" ); - } - - gtk_widget_queue_resize( GTK_WIDGET( accel_label ) ); -} - -void menu_item_add_accelerator( GtkMenuItem* item, Accelerator accelerator ){ - if ( accelerator.key != 0 ) { - GClosure* closure = global_accel_group_find( accelerator ); - if ( closure != 0 ) { - menu_item_set_accelerator( item, closure ); - } - else - { - menu_item_set_accelerator( item, accelerator ); - } - } -} - -GtkMenuItem* create_menu_item_with_mnemonic( GtkMenu* menu, const char* mnemonic, const Command& command ){ - command_connect_accelerator( command.m_accelerator, command.m_callback ); - GtkMenuItem* item = create_menu_item_with_mnemonic( menu, mnemonic, command.m_callback ); - menu_item_add_accelerator( item, command.m_accelerator ); - return item; -} - -void check_menu_item_set_active_callback( GtkCheckMenuItem& item, bool enabled ){ - check_menu_item_set_active_no_signal( &item, enabled ); -} -typedef ReferenceCaller1 CheckMenuItemSetActiveCaller; - -GtkCheckMenuItem* create_check_menu_item_with_mnemonic( GtkMenu* menu, const char* mnemonic, const Toggle& toggle ){ - command_connect_accelerator( toggle.m_command.m_accelerator, toggle.m_command.m_callback ); - GtkCheckMenuItem* item = create_check_menu_item_with_mnemonic( menu, mnemonic, toggle.m_command.m_callback ); - menu_item_add_accelerator( GTK_MENU_ITEM( item ), toggle.m_command.m_accelerator ); - toggle.m_exportCallback( CheckMenuItemSetActiveCaller( *item ) ); - return item; -} diff --git a/tools/urt/libs/gtkutil/menu.h b/tools/urt/libs/gtkutil/menu.h deleted file mode 100644 index b85e8ed..0000000 --- a/tools/urt/libs/gtkutil/menu.h +++ /dev/null @@ -1,37 +0,0 @@ - -#if !defined( INCLUDED_GTKUTIL_MENU_H ) -#define INCLUDED_GTKUTIL_MENU_H - -class Callback; -typedef int gint; -typedef gint gboolean; -typedef struct _GSList GSList; -typedef struct _GtkMenu GtkMenu; -typedef struct _GtkMenuBar GtkMenuBar; -typedef struct _GtkMenuItem GtkMenuItem; -typedef struct _GtkCheckMenuItem GtkCheckMenuItem; -typedef struct _GtkRadioMenuItem GtkRadioMenuItem; -typedef struct _GtkTearoffMenuItem GtkTearoffMenuItem; - -void menu_add_item( GtkMenu* menu, GtkMenuItem* item ); -GtkMenuItem* menu_separator( GtkMenu* menu ); -GtkTearoffMenuItem* menu_tearoff( GtkMenu* menu ); -GtkMenuItem* new_sub_menu_item_with_mnemonic( const char* mnemonic ); -GtkMenu* create_sub_menu_with_mnemonic( GtkMenuBar* bar, const char* mnemonic ); -GtkMenu* create_sub_menu_with_mnemonic( GtkMenu* parent, const char* mnemonic ); -GtkMenuItem* create_menu_item_with_mnemonic( GtkMenu* menu, const char* mnemonic, const Callback& callback ); -GtkCheckMenuItem* create_check_menu_item_with_mnemonic( GtkMenu* menu, const char* mnemonic, const Callback& callback ); -GtkRadioMenuItem* create_radio_menu_item_with_mnemonic( GtkMenu* menu, GSList** group, const char* mnemonic, const Callback& callback ); - -class Command; -GtkMenuItem* create_menu_item_with_mnemonic( GtkMenu* menu, const char* mnemonic, const Command& command ); -class Toggle; -GtkCheckMenuItem* create_check_menu_item_with_mnemonic( GtkMenu* menu, const char* mnemonic, const Toggle& toggle ); - - -typedef struct _GtkCheckMenuItem GtkCheckMenuItem; -void check_menu_item_set_active_no_signal( GtkCheckMenuItem* item, gboolean active ); -typedef struct _GtkRadioMenuItem GtkRadioMenuItem; -void radio_menu_item_set_active_no_signal( GtkRadioMenuItem* item, gboolean active ); - -#endif diff --git a/tools/urt/libs/gtkutil/messagebox.cpp b/tools/urt/libs/gtkutil/messagebox.cpp deleted file mode 100644 index 5f74e37..0000000 --- a/tools/urt/libs/gtkutil/messagebox.cpp +++ /dev/null @@ -1,184 +0,0 @@ - -#include "messagebox.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "dialog.h" -#include "widget.h" - -GtkWidget* create_padding( int width, int height ){ - GtkWidget* widget = gtk_alignment_new( 0.0, 0.0, 0.0, 0.0 ); - gtk_widget_show( widget ); - gtk_widget_set_size_request( widget, width, height ); - return widget; -} - -const char* messagebox_stock_icon( EMessageBoxIcon type ){ - switch ( type ) - { - default: - case eMB_ICONDEFAULT: - return GTK_STOCK_DIALOG_INFO; - case eMB_ICONERROR: - return GTK_STOCK_DIALOG_ERROR; - case eMB_ICONWARNING: - return GTK_STOCK_DIALOG_WARNING; - case eMB_ICONQUESTION: - return GTK_STOCK_DIALOG_QUESTION; - case eMB_ICONASTERISK: - return GTK_STOCK_DIALOG_INFO; - } -} - -EMessageBoxReturn gtk_MessageBox( GtkWidget *parent, const char* text, const char* title, EMessageBoxType type, EMessageBoxIcon icon ){ - ModalDialog dialog; - ModalDialogButton ok_button( dialog, eIDOK ); - ModalDialogButton cancel_button( dialog, eIDCANCEL ); - ModalDialogButton yes_button( dialog, eIDYES ); - ModalDialogButton no_button( dialog, eIDNO ); - - GtkWindow* parentWindow = parent != 0 ? GTK_WINDOW( parent ) : 0; - - GtkWindow* window = create_fixedsize_modal_dialog_window( parentWindow, title, dialog, 400, 100 ); - - if ( parentWindow != 0 ) { - //g_signal_connect(G_OBJECT(window), "delete_event", G_CALLBACK(floating_window_delete_present), parent); - gtk_window_deiconify( parentWindow ); - } - - GtkAccelGroup* accel = gtk_accel_group_new(); - gtk_window_add_accel_group( window, accel ); - - GtkVBox* vbox = create_dialog_vbox( 8, 8 ); - gtk_container_add( GTK_CONTAINER( window ), GTK_WIDGET( vbox ) ); - - - GtkHBox* hboxDummy = create_dialog_hbox( 0, 0 ); - gtk_box_pack_start( GTK_BOX( vbox ), GTK_WIDGET( hboxDummy ), FALSE, FALSE, 0 ); - - gtk_box_pack_start( GTK_BOX( hboxDummy ), create_padding( 0, 50 ), FALSE, FALSE, 0 ); // HACK to force minimum height - - GtkHBox* iconBox = create_dialog_hbox( 16, 0 ); - gtk_box_pack_start( GTK_BOX( hboxDummy ), GTK_WIDGET( iconBox ), FALSE, FALSE, 0 ); - - GtkImage* image = GTK_IMAGE( gtk_image_new_from_stock( messagebox_stock_icon( icon ), GTK_ICON_SIZE_DIALOG ) ); - gtk_widget_show( GTK_WIDGET( image ) ); - gtk_box_pack_start( GTK_BOX( iconBox ), GTK_WIDGET( image ), FALSE, FALSE, 0 ); - - GtkLabel* label = GTK_LABEL( gtk_label_new( text ) ); - gtk_widget_show( GTK_WIDGET( label ) ); - gtk_misc_set_alignment( GTK_MISC( label ), 0, 0.5 ); - gtk_label_set_justify( label, GTK_JUSTIFY_LEFT ); - gtk_label_set_line_wrap( label, TRUE ); - gtk_box_pack_start( GTK_BOX( iconBox ), GTK_WIDGET( label ), TRUE, TRUE, 0 ); - - - GtkVBox* vboxDummy = create_dialog_vbox( 0, 0 ); - gtk_box_pack_start( GTK_BOX( vbox ), GTK_WIDGET( vboxDummy ), FALSE, FALSE, 0 ); - - GtkAlignment* alignment = GTK_ALIGNMENT( gtk_alignment_new( 0.5, 0.0, 0.0, 0.0 ) ); - gtk_widget_show( GTK_WIDGET( alignment ) ); - gtk_box_pack_start( GTK_BOX( vboxDummy ), GTK_WIDGET( alignment ), FALSE, FALSE, 0 ); - - GtkHBox* hbox = create_dialog_hbox( 8, 0 ); - gtk_container_add( GTK_CONTAINER( alignment ), GTK_WIDGET( hbox ) ); - - gtk_box_pack_start( GTK_BOX( vboxDummy ), create_padding( 400, 0 ), FALSE, FALSE, 0 ); // HACK to force minimum width - - - if ( type == eMB_OK ) { - GtkButton* button = create_modal_dialog_button( "OK", ok_button ); - gtk_box_pack_start( GTK_BOX( hbox ), GTK_WIDGET( button ), TRUE, FALSE, 0 ); - gtk_widget_add_accelerator( GTK_WIDGET( button ), "clicked", accel, GDK_Escape, (GdkModifierType)0, (GtkAccelFlags)0 ); - gtk_widget_add_accelerator( GTK_WIDGET( button ), "clicked", accel, GDK_Return, (GdkModifierType)0, (GtkAccelFlags)0 ); - widget_make_default( GTK_WIDGET( button ) ); - gtk_widget_show( GTK_WIDGET( button ) ); - - dialog.ret = eIDOK; - } - else if ( type == eMB_OKCANCEL ) { - { - GtkButton* button = create_modal_dialog_button( "OK", ok_button ); - gtk_box_pack_start( GTK_BOX( hbox ), GTK_WIDGET( button ), TRUE, FALSE, 0 ); - gtk_widget_add_accelerator( GTK_WIDGET( button ), "clicked", accel, GDK_Return, (GdkModifierType)0, (GtkAccelFlags)0 ); - widget_make_default( GTK_WIDGET( button ) ); - gtk_widget_show( GTK_WIDGET( button ) ); - } - - { - GtkButton* button = create_modal_dialog_button( "OK", cancel_button ); - gtk_box_pack_start( GTK_BOX( hbox ), GTK_WIDGET( button ), TRUE, FALSE, 0 ); - gtk_widget_add_accelerator( GTK_WIDGET( button ), "clicked", accel, GDK_Escape, (GdkModifierType)0, (GtkAccelFlags)0 ); - gtk_widget_show( GTK_WIDGET( button ) ); - } - - dialog.ret = eIDCANCEL; - } - else if ( type == eMB_YESNOCANCEL ) { - { - GtkButton* button = create_modal_dialog_button( "Yes", yes_button ); - gtk_box_pack_start( GTK_BOX( hbox ), GTK_WIDGET( button ), TRUE, FALSE, 0 ); - widget_make_default( GTK_WIDGET( button ) ); - gtk_widget_show( GTK_WIDGET( button ) ); - } - - { - GtkButton* button = create_modal_dialog_button( "No", no_button ); - gtk_box_pack_start( GTK_BOX( hbox ), GTK_WIDGET( button ), TRUE, FALSE, 0 ); - gtk_widget_show( GTK_WIDGET( button ) ); - } - { - GtkButton* button = create_modal_dialog_button( "Cancel", cancel_button ); - gtk_box_pack_start( GTK_BOX( hbox ), GTK_WIDGET( button ), TRUE, FALSE, 0 ); - gtk_widget_show( GTK_WIDGET( button ) ); - } - - dialog.ret = eIDCANCEL; - } - else if ( type == eMB_NOYES ) { - { - GtkButton* button = create_modal_dialog_button( "No", no_button ); - gtk_box_pack_start( GTK_BOX( hbox ), GTK_WIDGET( button ), TRUE, FALSE, 0 ); - widget_make_default( GTK_WIDGET( button ) ); - gtk_widget_show( GTK_WIDGET( button ) ); - } - { - GtkButton* button = create_modal_dialog_button( "Yes", yes_button ); - gtk_box_pack_start( GTK_BOX( hbox ), GTK_WIDGET( button ), TRUE, FALSE, 0 ); - gtk_widget_show( GTK_WIDGET( button ) ); - } - - dialog.ret = eIDNO; - } - else /* if (type == eMB_YESNO) */ - { - { - GtkButton* button = create_modal_dialog_button( "Yes", yes_button ); - gtk_box_pack_start( GTK_BOX( hbox ), GTK_WIDGET( button ), TRUE, FALSE, 0 ); - widget_make_default( GTK_WIDGET( button ) ); - gtk_widget_show( GTK_WIDGET( button ) ); - } - - { - GtkButton* button = create_modal_dialog_button( "No", no_button ); - gtk_box_pack_start( GTK_BOX( hbox ), GTK_WIDGET( button ), TRUE, FALSE, 0 ); - gtk_widget_show( GTK_WIDGET( button ) ); - } - dialog.ret = eIDNO; - } - - modal_dialog_show( window, dialog ); - - gtk_widget_destroy( GTK_WIDGET( window ) ); - - return dialog.ret; -} diff --git a/tools/urt/libs/gtkutil/messagebox.h b/tools/urt/libs/gtkutil/messagebox.h deleted file mode 100644 index 5f747b1..0000000 --- a/tools/urt/libs/gtkutil/messagebox.h +++ /dev/null @@ -1,11 +0,0 @@ - -#if !defined( INCLUDED_GTKUTIL_MESSAGEBOX_H ) -#define INCLUDED_GTKUTIL_MESSAGEBOX_H - -#include "qerplugin.h" - -typedef struct _GtkWidget GtkWidget; -/// \brief Shows a modal message-box. -EMessageBoxReturn gtk_MessageBox( GtkWidget *parent, const char* text, const char* title = "GtkRadiant", EMessageBoxType type = eMB_OK, EMessageBoxIcon icon = eMB_ICONDEFAULT ); - -#endif diff --git a/tools/urt/libs/gtkutil/nonmodal.cpp b/tools/urt/libs/gtkutil/nonmodal.cpp deleted file mode 100644 index 29e7b1d..0000000 --- a/tools/urt/libs/gtkutil/nonmodal.cpp +++ /dev/null @@ -1,2 +0,0 @@ - -#include "nonmodal.h" diff --git a/tools/urt/libs/gtkutil/nonmodal.h b/tools/urt/libs/gtkutil/nonmodal.h deleted file mode 100644 index d9d64d8..0000000 --- a/tools/urt/libs/gtkutil/nonmodal.h +++ /dev/null @@ -1,144 +0,0 @@ - -#if !defined( INCLUDED_GTKUTIL_NONMODAL_H ) -#define INCLUDED_GTKUTIL_NONMODAL_H - -#include -#include -#include -#include - -#include "generic/callback.h" - -#include "pointer.h" -#include "button.h" - -typedef struct _GtkEntry GtkEntry; - - -inline gboolean escape_clear_focus_widget( GtkWidget* widget, GdkEventKey* event, gpointer data ){ - if ( event->keyval == GDK_Escape ) { - gtk_window_set_focus( GTK_WINDOW( gtk_widget_get_toplevel( GTK_WIDGET( widget ) ) ), NULL ); - return TRUE; - } - return FALSE; -} - -inline void widget_connect_escape_clear_focus_widget( GtkWidget* widget ){ - g_signal_connect( G_OBJECT( widget ), "key_press_event", G_CALLBACK( escape_clear_focus_widget ), 0 ); -} - - -class NonModalEntry -{ -bool m_editing; -Callback m_apply; -Callback m_cancel; - -static gboolean focus_in( GtkEntry* entry, GdkEventFocus *event, NonModalEntry* self ){ - self->m_editing = false; - return FALSE; -} - -static gboolean focus_out( GtkEntry* entry, GdkEventFocus *event, NonModalEntry* self ){ - if ( self->m_editing && GTK_WIDGET_VISIBLE( entry ) ) { - self->m_apply(); - } - self->m_editing = false; - return FALSE; -} - -static gboolean changed( GtkEntry* entry, NonModalEntry* self ){ - self->m_editing = true; - return FALSE; -} - -static gboolean enter( GtkEntry* entry, GdkEventKey* event, NonModalEntry* self ){ - if ( event->keyval == GDK_Return ) { - self->m_apply(); - self->m_editing = false; - gtk_window_set_focus( GTK_WINDOW( gtk_widget_get_toplevel( GTK_WIDGET( entry ) ) ), NULL ); - return TRUE; - } - return FALSE; -} - -static gboolean escape( GtkEntry* entry, GdkEventKey* event, NonModalEntry* self ){ - if ( event->keyval == GDK_Escape ) { - self->m_cancel(); - self->m_editing = false; - gtk_window_set_focus( GTK_WINDOW( gtk_widget_get_toplevel( GTK_WIDGET( entry ) ) ), NULL ); - return TRUE; - } - return FALSE; -} - -public: -NonModalEntry( const Callback& apply, const Callback& cancel ) : m_editing( false ), m_apply( apply ), m_cancel( cancel ){ -} -void connect( GtkEntry* entry ){ - g_signal_connect( G_OBJECT( entry ), "focus_in_event", G_CALLBACK( focus_in ), this ); - g_signal_connect( G_OBJECT( entry ), "focus_out_event", G_CALLBACK( focus_out ), this ); - g_signal_connect( G_OBJECT( entry ), "key_press_event", G_CALLBACK( enter ), this ); - g_signal_connect( G_OBJECT( entry ), "key_press_event", G_CALLBACK( escape ), this ); - g_signal_connect( G_OBJECT( entry ), "changed", G_CALLBACK( changed ), this ); -} -}; - - -class NonModalSpinner -{ -Callback m_apply; -Callback m_cancel; - -static gboolean changed( GtkSpinButton* spin, NonModalSpinner* self ){ - self->m_apply(); - return FALSE; -} - -static gboolean enter( GtkSpinButton* spin, GdkEventKey* event, NonModalSpinner* self ){ - if ( event->keyval == GDK_Return ) { - gtk_window_set_focus( GTK_WINDOW( gtk_widget_get_toplevel( GTK_WIDGET( spin ) ) ), NULL ); - return TRUE; - } - return FALSE; -} - -static gboolean escape( GtkSpinButton* spin, GdkEventKey* event, NonModalSpinner* self ){ - if ( event->keyval == GDK_Escape ) { - self->m_cancel(); - gtk_window_set_focus( GTK_WINDOW( gtk_widget_get_toplevel( GTK_WIDGET( spin ) ) ), NULL ); - return TRUE; - } - return FALSE; -} - -public: -NonModalSpinner( const Callback& apply, const Callback& cancel ) : m_apply( apply ), m_cancel( cancel ){ -} -void connect( GtkSpinButton* spin ){ - guint handler = g_signal_connect( G_OBJECT( gtk_spin_button_get_adjustment( spin ) ), "value_changed", G_CALLBACK( changed ), this ); - g_object_set_data( G_OBJECT( spin ), "handler", gint_to_pointer( handler ) ); - g_signal_connect( G_OBJECT( spin ), "key_press_event", G_CALLBACK( enter ), this ); - g_signal_connect( G_OBJECT( spin ), "key_press_event", G_CALLBACK( escape ), this ); -} -}; - - -class NonModalRadio -{ -Callback m_changed; - -public: -NonModalRadio( const Callback& changed ) : m_changed( changed ){ -} -void connect( GtkRadioButton* radio ){ - GSList* group = gtk_radio_button_group( radio ); - for (; group != 0; group = g_slist_next( group ) ) - { - toggle_button_connect_callback( GTK_TOGGLE_BUTTON( group->data ), m_changed ); - } -} -}; - - -#endif diff --git a/tools/urt/libs/gtkutil/paned.cpp b/tools/urt/libs/gtkutil/paned.cpp deleted file mode 100644 index eecc1f8..0000000 --- a/tools/urt/libs/gtkutil/paned.cpp +++ /dev/null @@ -1,74 +0,0 @@ - -#include "paned.h" - -#include -#include - -#include "frame.h" - - -class PanedState -{ -public: -float position; -int size; -}; - -gboolean hpaned_allocate( GtkWidget* widget, GtkAllocation* allocation, PanedState* paned ){ - if ( paned->size != allocation->width ) { - paned->size = allocation->width; - gtk_paned_set_position( GTK_PANED( widget ), static_cast( paned->size * paned->position ) ); - } - return FALSE; -} - -gboolean vpaned_allocate( GtkWidget* widget, GtkAllocation* allocation, PanedState* paned ){ - if ( paned->size != allocation->height ) { - paned->size = allocation->height; - gtk_paned_set_position( GTK_PANED( widget ), static_cast( paned->size * paned->position ) ); - } - return FALSE; -} - -gboolean paned_position( GtkWidget* widget, gpointer dummy, PanedState* paned ){ - if ( paned->size != -1 ) { - paned->position = gtk_paned_get_position( GTK_PANED( widget ) ) / static_cast( paned->size ); - } - return FALSE; -} - -PanedState g_hpaned = { 0.5f, -1, }; -PanedState g_vpaned1 = { 0.5f, -1, }; -PanedState g_vpaned2 = { 0.5f, -1, }; - -GtkHPaned* create_split_views( GtkWidget* topleft, GtkWidget* topright, GtkWidget* botleft, GtkWidget* botright ){ - GtkHPaned* hsplit = GTK_HPANED( gtk_hpaned_new() ); - gtk_widget_show( GTK_WIDGET( hsplit ) ); - - g_signal_connect( G_OBJECT( hsplit ), "size_allocate", G_CALLBACK( hpaned_allocate ), &g_hpaned ); - g_signal_connect( G_OBJECT( hsplit ), "notify::position", G_CALLBACK( paned_position ), &g_hpaned ); - - { - GtkVPaned* vsplit = GTK_VPANED( gtk_vpaned_new() ); - gtk_paned_add1( GTK_PANED( hsplit ), GTK_WIDGET( vsplit ) ); - gtk_widget_show( GTK_WIDGET( vsplit ) ); - - g_signal_connect( G_OBJECT( vsplit ), "size_allocate", G_CALLBACK( vpaned_allocate ), &g_vpaned1 ); - g_signal_connect( G_OBJECT( vsplit ), "notify::position", G_CALLBACK( paned_position ), &g_vpaned1 ); - - gtk_paned_add1( GTK_PANED( vsplit ), GTK_WIDGET( create_framed_widget( topleft ) ) ); - gtk_paned_add2( GTK_PANED( vsplit ), GTK_WIDGET( create_framed_widget( topright ) ) ); - } - { - GtkVPaned* vsplit = GTK_VPANED( gtk_vpaned_new() ); - gtk_paned_add2( GTK_PANED( hsplit ), GTK_WIDGET( vsplit ) ); - gtk_widget_show( GTK_WIDGET( vsplit ) ); - - g_signal_connect( G_OBJECT( vsplit ), "size_allocate", G_CALLBACK( vpaned_allocate ), &g_vpaned2 ); - g_signal_connect( G_OBJECT( vsplit ), "notify::position", G_CALLBACK( paned_position ), &g_vpaned2 ); - - gtk_paned_add1( GTK_PANED( vsplit ), GTK_WIDGET( create_framed_widget( botleft ) ) ); - gtk_paned_add2( GTK_PANED( vsplit ), GTK_WIDGET( create_framed_widget( botright ) ) ); - } - return hsplit; -} diff --git a/tools/urt/libs/gtkutil/paned.h b/tools/urt/libs/gtkutil/paned.h deleted file mode 100644 index 26259ff..0000000 --- a/tools/urt/libs/gtkutil/paned.h +++ /dev/null @@ -1,9 +0,0 @@ - -#if !defined( INCLUDED_GTKUTIL_PANED_H ) -#define INCLUDED_GTKUTIL_PANED_H - -typedef struct _GtkWidget GtkWidget; -typedef struct _GtkHPaned GtkHPaned; -GtkHPaned* create_split_views( GtkWidget* topleft, GtkWidget* topright, GtkWidget* botleft, GtkWidget* botright ); - -#endif diff --git a/tools/urt/libs/gtkutil/pointer.cpp b/tools/urt/libs/gtkutil/pointer.cpp deleted file mode 100644 index 9dd1a3b..0000000 --- a/tools/urt/libs/gtkutil/pointer.cpp +++ /dev/null @@ -1,2 +0,0 @@ - -#include "pointer.h" diff --git a/tools/urt/libs/gtkutil/pointer.h b/tools/urt/libs/gtkutil/pointer.h deleted file mode 100644 index 0938343..0000000 --- a/tools/urt/libs/gtkutil/pointer.h +++ /dev/null @@ -1,18 +0,0 @@ - -#if !defined( INCLUDED_GTKUTIL_POINTER_H ) -#define INCLUDED_GTKUTIL_POINTER_H - -typedef int gint; -typedef void* gpointer; - -#include - -inline gint gpointer_to_int( gpointer p ){ - return gint( std::size_t( p ) ); -} - -inline gpointer gint_to_pointer( gint i ){ - return gpointer( std::size_t( i ) ); -} - -#endif diff --git a/tools/urt/libs/gtkutil/toolbar.cpp b/tools/urt/libs/gtkutil/toolbar.cpp deleted file mode 100644 index a123df5..0000000 --- a/tools/urt/libs/gtkutil/toolbar.cpp +++ /dev/null @@ -1,52 +0,0 @@ - -#include "toolbar.h" - -#include -#include - -#include "generic/callback.h" - -#include "accelerator.h" -#include "button.h" -#include "closure.h" -#include "pointer.h" - - -void toolbar_append( GtkToolbar* toolbar, GtkButton* button, const char* description ){ - gtk_widget_show( GTK_WIDGET( button ) ); - gtk_button_set_relief( button, GTK_RELIEF_NONE ); - GTK_WIDGET_UNSET_FLAGS( GTK_WIDGET( button ), GTK_CAN_FOCUS ); - GTK_WIDGET_UNSET_FLAGS( GTK_WIDGET( button ), GTK_CAN_DEFAULT ); - gtk_toolbar_append_element( toolbar, GTK_TOOLBAR_CHILD_WIDGET, GTK_WIDGET( button ), "", description, "", 0, 0, 0 ); -} - -GtkButton* toolbar_append_button( GtkToolbar* toolbar, const char* description, const char* icon, const Callback& callback ){ - GtkButton* button = GTK_BUTTON( gtk_button_new() ); - button_set_icon( button, icon ); - button_connect_callback( button, callback ); - toolbar_append( toolbar, button, description ); - return button; -} - -GtkToggleButton* toolbar_append_toggle_button( GtkToolbar* toolbar, const char* description, const char* icon, const Callback& callback ){ - GtkToggleButton* button = GTK_TOGGLE_BUTTON( gtk_toggle_button_new() ); - button_set_icon( GTK_BUTTON( button ), icon ); - toggle_button_connect_callback( button, callback ); - toolbar_append( toolbar, GTK_BUTTON( button ), description ); - return button; -} - -GtkButton* toolbar_append_button( GtkToolbar* toolbar, const char* description, const char* icon, const Command& command ){ - return toolbar_append_button( toolbar, description, icon, command.m_callback ); -} - -void toggle_button_set_active_callback( GtkToggleButton& button, bool active ){ - toggle_button_set_active_no_signal( &button, active ); -} -typedef ReferenceCaller1 ToggleButtonSetActiveCaller; - -GtkToggleButton* toolbar_append_toggle_button( GtkToolbar* toolbar, const char* description, const char* icon, const Toggle& toggle ){ - GtkToggleButton* button = toolbar_append_toggle_button( toolbar, description, icon, toggle.m_command.m_callback ); - toggle.m_exportCallback( ToggleButtonSetActiveCaller( *button ) ); - return button; -} diff --git a/tools/urt/libs/gtkutil/toolbar.h b/tools/urt/libs/gtkutil/toolbar.h deleted file mode 100644 index 13a1ca5..0000000 --- a/tools/urt/libs/gtkutil/toolbar.h +++ /dev/null @@ -1,17 +0,0 @@ - -#if !defined( INCLUDED_GTKUTIL_TOOLBAR_H ) -#define INCLUDED_GTKUTIL_TOOLBAR_H - -class Callback; -typedef struct _GtkButton GtkButton; -typedef struct _GtkToggleButton GtkToggleButton; -typedef struct _GtkToolbar GtkToolbar; -class Command; -class Toggle; - -GtkButton* toolbar_append_button( GtkToolbar* toolbar, const char* description, const char* icon, const Callback& callback ); -GtkButton* toolbar_append_button( GtkToolbar* toolbar, const char* description, const char* icon, const Command& command ); -GtkToggleButton* toolbar_append_toggle_button( GtkToolbar* toolbar, const char* description, const char* icon, const Callback& callback ); -GtkToggleButton* toolbar_append_toggle_button( GtkToolbar* toolbar, const char* description, const char* icon, const Toggle& toggle ); - -#endif diff --git a/tools/urt/libs/gtkutil/widget.cpp b/tools/urt/libs/gtkutil/widget.cpp deleted file mode 100644 index bba1294..0000000 --- a/tools/urt/libs/gtkutil/widget.cpp +++ /dev/null @@ -1,2 +0,0 @@ - -#include "widget.h" diff --git a/tools/urt/libs/gtkutil/widget.h b/tools/urt/libs/gtkutil/widget.h deleted file mode 100644 index 628de12..0000000 --- a/tools/urt/libs/gtkutil/widget.h +++ /dev/null @@ -1,125 +0,0 @@ - -#if !defined( INCLUDED_GTKUTIL_WIDGET_H ) -#define INCLUDED_GTKUTIL_WIDGET_H - -#include -#include -#include "generic/callback.h" -#include "warnings.h" - -inline void widget_set_visible( GtkWidget* widget, bool shown ){ - if ( shown ) { - gtk_widget_show( widget ); - } - else - { - gtk_widget_hide( widget ); - } -} - -inline bool widget_is_visible( GtkWidget* widget ){ - return GTK_WIDGET_VISIBLE( widget ) != FALSE; -} - -inline void widget_toggle_visible( GtkWidget* widget ){ - widget_set_visible( widget, !widget_is_visible( widget ) ); -} - -class ToggleItem -{ -BoolExportCallback m_exportCallback; -typedef std::list ImportCallbacks; -ImportCallbacks m_importCallbacks; -public: -ToggleItem( const BoolExportCallback& exportCallback ) : m_exportCallback( exportCallback ){ -} - -void update(){ - for ( ImportCallbacks::iterator i = m_importCallbacks.begin(); i != m_importCallbacks.end(); ++i ) - { - m_exportCallback( *i ); - } -} - -void addCallback( const BoolImportCallback& callback ){ - m_importCallbacks.push_back( callback ); - m_exportCallback( callback ); -} -typedef MemberCaller1 AddCallbackCaller; -}; - -class ToggleShown -{ -bool m_shownDeferred; - -ToggleShown( const ToggleShown& other ); // NOT COPYABLE -ToggleShown& operator=( const ToggleShown& other ); // NOT ASSIGNABLE - -static gboolean notify_visible( GtkWidget* widget, gpointer dummy, ToggleShown* self ){ - self->update(); - return FALSE; -} -static gboolean destroy( GtkWidget* widget, ToggleShown* self ){ - self->m_shownDeferred = GTK_WIDGET_VISIBLE( self->m_widget ) != FALSE; - self->m_widget = 0; - return FALSE; -} -public: -GtkWidget* m_widget; -ToggleItem m_item; - -ToggleShown( bool shown ) - : m_shownDeferred( shown ), m_widget( 0 ), m_item( ActiveCaller( *this ) ){ -} -void update(){ - m_item.update(); -} -bool active() const { - if ( m_widget == 0 ) { - return m_shownDeferred; - } - else - { - return GTK_WIDGET_VISIBLE( m_widget ) != FALSE; - } -} -void exportActive( const BoolImportCallback& importCallback ){ - importCallback( active() ); -} -typedef MemberCaller1 ActiveCaller; -void set( bool shown ){ - if ( m_widget == 0 ) { - m_shownDeferred = shown; - } - else - { - widget_set_visible( m_widget, shown ); - } -} -void toggle(){ - widget_toggle_visible( m_widget ); -} -typedef MemberCaller ToggleCaller; -void connect( GtkWidget* widget ){ - m_widget = widget; - widget_set_visible( m_widget, m_shownDeferred ); - g_signal_connect( G_OBJECT( m_widget ), "notify::visible", G_CALLBACK( notify_visible ), this ); - g_signal_connect( G_OBJECT( m_widget ), "destroy", G_CALLBACK( destroy ), this ); - update(); -} -}; - - -inline void widget_queue_draw( GtkWidget& widget ){ - gtk_widget_queue_draw( &widget ); -} -typedef ReferenceCaller WidgetQueueDrawCaller; - - -inline void widget_make_default( GtkWidget* widget ){ - GTK_WIDGET_SET_FLAGS( widget, GTK_CAN_DEFAULT ); - gtk_widget_grab_default( widget ); -} - - -#endif diff --git a/tools/urt/libs/gtkutil/window.cpp b/tools/urt/libs/gtkutil/window.cpp deleted file mode 100644 index d41dcc6..0000000 --- a/tools/urt/libs/gtkutil/window.cpp +++ /dev/null @@ -1,126 +0,0 @@ - -#include "window.h" - -#include - -#include "pointer.h" -#include "accelerator.h" - -inline void CHECK_RESTORE( GtkWidget* w ){ - if ( gpointer_to_int( g_object_get_data( G_OBJECT( w ), "was_mapped" ) ) != 0 ) { - gtk_widget_show( w ); - } -} - -inline void CHECK_MINIMIZE( GtkWidget* w ){ - g_object_set_data( G_OBJECT( w ), "was_mapped", gint_to_pointer( GTK_WIDGET_VISIBLE( w ) ) ); - gtk_widget_hide( w ); -} - -static gboolean main_window_iconified( GtkWidget* widget, GdkEventWindowState* event, gpointer data ){ - if ( ( event->changed_mask & ( GDK_WINDOW_STATE_ICONIFIED | GDK_WINDOW_STATE_WITHDRAWN ) ) != 0 ) { - if ( ( event->new_window_state & ( GDK_WINDOW_STATE_ICONIFIED | GDK_WINDOW_STATE_WITHDRAWN ) ) != 0 ) { - CHECK_MINIMIZE( GTK_WIDGET( data ) ); - } - else - { - CHECK_RESTORE( GTK_WIDGET( data ) ); - } - } - return FALSE; -} - -unsigned int connect_floating( GtkWindow* main_window, GtkWindow* floating ){ - return g_signal_connect( G_OBJECT( main_window ), "window_state_event", G_CALLBACK( main_window_iconified ), floating ); -} - -gboolean destroy_disconnect_floating( GtkWindow* widget, gpointer data ){ - g_signal_handler_disconnect( G_OBJECT( data ), gpointer_to_int( g_object_get_data( G_OBJECT( widget ), "floating_handler" ) ) ); - return FALSE; -} - -gboolean floating_window_delete_present( GtkWindow* floating, GdkEventFocus *event, GtkWindow* main_window ){ - if ( gtk_window_is_active( floating ) || gtk_window_is_active( main_window ) ) { - gtk_window_present( main_window ); - } - return FALSE; -} - -guint connect_floating_window_delete_present( GtkWindow* floating, GtkWindow* main_window ){ - return g_signal_connect( G_OBJECT( floating ), "delete_event", G_CALLBACK( floating_window_delete_present ), main_window ); -} - -gboolean floating_window_destroy_present( GtkWindow* floating, GtkWindow* main_window ){ - if ( gtk_window_is_active( floating ) || gtk_window_is_active( main_window ) ) { - gtk_window_present( main_window ); - } - return FALSE; -} - -guint connect_floating_window_destroy_present( GtkWindow* floating, GtkWindow* main_window ){ - return g_signal_connect( G_OBJECT( floating ), "destroy", G_CALLBACK( floating_window_destroy_present ), main_window ); -} - -GtkWindow* create_floating_window( const char* title, GtkWindow* parent ){ - GtkWindow* window = GTK_WINDOW( gtk_window_new( GTK_WINDOW_TOPLEVEL ) ); - gtk_window_set_title( window, title ); - - if ( parent != 0 ) { - gtk_window_set_transient_for( window, parent ); - connect_floating_window_destroy_present( window, parent ); - g_object_set_data( G_OBJECT( window ), "floating_handler", gint_to_pointer( connect_floating( parent, window ) ) ); - g_signal_connect( G_OBJECT( window ), "destroy", G_CALLBACK( destroy_disconnect_floating ), parent ); - } - - return window; -} - -void destroy_floating_window( GtkWindow* window ){ - gtk_widget_destroy( GTK_WIDGET( window ) ); -} - -gint window_realize_remove_sysmenu( GtkWidget* widget, gpointer data ){ - gdk_window_set_decorations( widget->window, (GdkWMDecoration)( GDK_DECOR_ALL | GDK_DECOR_MENU ) ); - return FALSE; -} - -gboolean persistent_floating_window_delete( GtkWindow* floating, GdkEvent *event, GtkWindow* main_window ){ - gtk_widget_hide( GTK_WIDGET( floating ) ); - return TRUE; -} - -GtkWindow* create_persistent_floating_window( const char* title, GtkWindow* main_window ){ - GtkWindow* window = GTK_WINDOW( create_floating_window( title, main_window ) ); - - gtk_widget_set_events( GTK_WIDGET( window ), GDK_KEY_PRESS_MASK | GDK_KEY_RELEASE_MASK ); - - connect_floating_window_delete_present( window, main_window ); - g_signal_connect( G_OBJECT( window ), "delete_event", G_CALLBACK( persistent_floating_window_delete ), 0 ); - -#if 0 - if ( g_multimon_globals.m_bStartOnPrimMon && g_multimon_globals.m_bNoSysMenuPopups ) { - g_signal_connect( G_OBJECT( window ), "realize", G_CALLBACK( window_realize_remove_sysmenu ), 0 ); - } -#endif - - return window; -} - -gint window_realize_remove_minmax( GtkWidget* widget, gpointer data ){ - gdk_window_set_decorations( widget->window, (GdkWMDecoration)( GDK_DECOR_ALL | GDK_DECOR_MINIMIZE | GDK_DECOR_MAXIMIZE ) ); - return FALSE; -} - -void window_remove_minmax( GtkWindow* window ){ - g_signal_connect( G_OBJECT( window ), "realize", G_CALLBACK( window_realize_remove_minmax ), 0 ); -} - - -GtkScrolledWindow* create_scrolled_window( GtkPolicyType hscrollbar_policy, GtkPolicyType vscrollbar_policy, int border ){ - GtkScrolledWindow* scr = GTK_SCROLLED_WINDOW( gtk_scrolled_window_new( 0, 0 ) ); - gtk_widget_show( GTK_WIDGET( scr ) ); - gtk_scrolled_window_set_policy( scr, hscrollbar_policy, vscrollbar_policy ); - gtk_scrolled_window_set_shadow_type( scr, GTK_SHADOW_IN ); - gtk_container_set_border_width( GTK_CONTAINER( scr ), border ); - return scr; -} diff --git a/tools/urt/libs/gtkutil/window.h b/tools/urt/libs/gtkutil/window.h deleted file mode 100644 index 89cc8a1..0000000 --- a/tools/urt/libs/gtkutil/window.h +++ /dev/null @@ -1,136 +0,0 @@ - -#if !defined( INCLUDED_GTKUTIL_WINDOW_H ) -#define INCLUDED_GTKUTIL_WINDOW_H - -#include - -#include "debugging/debugging.h" -#include "generic/callback.h" -#include "widget.h" - -inline gboolean window_focus_in_clear_focus_widget( GtkWidget* widget, GdkEventKey* event, gpointer data ){ - gtk_window_set_focus( GTK_WINDOW( widget ), NULL ); - return FALSE; -} - -inline guint window_connect_focus_in_clear_focus_widget( GtkWindow* window ){ - return g_signal_connect( G_OBJECT( window ), "focus_in_event", G_CALLBACK( window_focus_in_clear_focus_widget ), NULL ); -} - - -unsigned int connect_floating( GtkWindow* main_window, GtkWindow* floating ); -GtkWindow* create_floating_window( const char* title, GtkWindow* parent ); -void destroy_floating_window( GtkWindow* window ); - -GtkWindow* create_persistent_floating_window( const char* title, GtkWindow* main_window ); -gboolean persistent_floating_window_delete( GtkWindow* floating, GdkEvent *event, GtkWindow* main_window ); - -void window_remove_minmax( GtkWindow* window ); - -typedef struct _GtkScrolledWindow GtkScrolledWindow; -GtkScrolledWindow* create_scrolled_window( GtkPolicyType hscrollbar_policy, GtkPolicyType vscrollbar_policy, int border = 0 ); - - -struct WindowPosition -{ - int x, y, w, h; - - WindowPosition(){ - } - WindowPosition( int _x, int _y, int _w, int _h ) - : x( _x ), y( _y ), w( _w ), h( _h ){ - } -}; - -const WindowPosition c_default_window_pos( 50, 25, 400, 300 ); - -inline void window_get_position( GtkWindow* window, WindowPosition& position ){ - ASSERT_MESSAGE( window != 0, "error saving window position" ); - - gtk_window_get_position( window, &position.x, &position.y ); - gtk_window_get_size( window, &position.w, &position.h ); -} - -inline void window_set_position( GtkWindow* window, const WindowPosition& position ){ - gtk_window_set_gravity( window, GDK_GRAVITY_STATIC ); - - GdkScreen* screen = gdk_screen_get_default(); - if ( position.x < 0 - || position.y < 0 - || position.x > gdk_screen_get_width( screen ) - || position.y > gdk_screen_get_height( screen ) ) { - gtk_window_set_position( window, GTK_WIN_POS_CENTER_ON_PARENT ); - } - else - { - gtk_window_move( window, position.x, position.y ); - } - - gtk_window_set_default_size( window, position.w, position.h ); -} - -inline void WindowPosition_Parse( WindowPosition& position, const char* value ){ - if ( sscanf( value, "%d %d %d %d", &position.x, &position.y, &position.w, &position.h ) != 4 ) { - position = WindowPosition( c_default_window_pos ); // ensure sane default value for window position - } -} -typedef ReferenceCaller1 WindowPositionImportStringCaller; - -inline void WindowPosition_Write( const WindowPosition& position, const StringImportCallback& importCallback ){ - char buffer[64]; - sprintf( buffer, "%d %d %d %d", position.x, position.y, position.w, position.h ); - importCallback( buffer ); -} -typedef ConstReferenceCaller1 WindowPositionExportStringCaller; - - - -class WindowPositionTracker -{ -WindowPosition m_position; - -static gboolean configure( GtkWidget* widget, GdkEventConfigure *event, WindowPositionTracker* self ){ - self->m_position = WindowPosition( event->x, event->y, event->width, event->height ); - return FALSE; -} - -public: -WindowPositionTracker() - : m_position( c_default_window_pos ){ -} - -void sync( GtkWindow* window ){ - window_set_position( window, m_position ); -} - -void connect( GtkWindow* window ){ - sync( window ); - g_signal_connect( G_OBJECT( window ), "configure_event", G_CALLBACK( configure ), this ); -} - -const WindowPosition& getPosition() const { - return m_position; -} - -//hack -void setPosition( const WindowPosition& position ){ - m_position = position; -} -}; - - -inline void WindowPositionTracker_importString( WindowPositionTracker& self, const char* value ){ - WindowPosition position; - WindowPosition_Parse( position, value ); - self.setPosition( position ); -} -typedef ReferenceCaller1 WindowPositionTrackerImportStringCaller; - -inline void WindowPositionTracker_exportString( const WindowPositionTracker& self, const StringImportCallback& importer ){ - WindowPosition_Write( self.getPosition(), importer ); -} -typedef ConstReferenceCaller1 WindowPositionTrackerExportStringCaller; - - - -#endif diff --git a/tools/urt/libs/gtkutil/xorrectangle.cpp b/tools/urt/libs/gtkutil/xorrectangle.cpp deleted file mode 100644 index 7843fc6..0000000 --- a/tools/urt/libs/gtkutil/xorrectangle.cpp +++ /dev/null @@ -1,2 +0,0 @@ - -#include "xorrectangle.h" diff --git a/tools/urt/libs/gtkutil/xorrectangle.h b/tools/urt/libs/gtkutil/xorrectangle.h deleted file mode 100644 index d8b9a7d..0000000 --- a/tools/urt/libs/gtkutil/xorrectangle.h +++ /dev/null @@ -1,93 +0,0 @@ - -#if !defined ( INCLUDED_XORRECTANGLE_H ) -#define INCLUDED_XORRECTANGLE_H - -#include -#include "math/vector.h" - -class rectangle_t -{ -public: -rectangle_t() - : x( 0 ), y( 0 ), w( 0 ), h( 0 ) -{} -rectangle_t( float _x, float _y, float _w, float _h ) - : x( _x ), y( _y ), w( _w ), h( _h ) -{} -float x; -float y; -float w; -float h; -}; - -struct Coord2D -{ - float x, y; - Coord2D( float _x, float _y ) - : x( _x ), y( _y ){ - } -}; - -inline Coord2D coord2d_device2screen( const Coord2D& coord, unsigned int width, unsigned int height ){ - return Coord2D( ( ( coord.x + 1.0f ) * 0.5f ) * width, ( ( coord.y + 1.0f ) * 0.5f ) * height ); -} - -inline rectangle_t rectangle_from_area( const float min[2], const float max[2], unsigned int width, unsigned int height ){ - Coord2D botleft( coord2d_device2screen( Coord2D( min[0], min[1] ), width, height ) ); - Coord2D topright( coord2d_device2screen( Coord2D( max[0], max[1] ), width, height ) ); - return rectangle_t( botleft.x, botleft.y, topright.x - botleft.x, topright.y - botleft.y ); -} - -class XORRectangle -{ - -rectangle_t m_rectangle; - -GtkWidget* m_widget; -GdkGC* m_gc; - -bool initialised() const { - return m_gc != 0; -} -void lazy_init(){ - if ( !initialised() ) { - m_gc = gdk_gc_new( m_widget->window ); - - GdkColor color = { 0, 0xffff, 0xffff, 0xffff, }; - GdkColormap* colormap = gdk_window_get_colormap( m_widget->window ); - gdk_colormap_alloc_color( colormap, &color, FALSE, TRUE ); - gdk_gc_copy( m_gc, m_widget->style->white_gc ); - gdk_gc_set_foreground( m_gc, &color ); - gdk_gc_set_background( m_gc, &color ); - - gdk_gc_set_function( m_gc, GDK_INVERT ); - } -} -void draw() const { - const int x = float_to_integer( m_rectangle.x ); - const int y = float_to_integer( m_rectangle.y ); - const int w = float_to_integer( m_rectangle.w ); - const int h = float_to_integer( m_rectangle.h ); - gdk_draw_rectangle( m_widget->window, m_gc, FALSE, x, -( h ) - ( y - m_widget->allocation.height ), w, h ); -} - -public: -XORRectangle( GtkWidget* widget ) : m_widget( widget ), m_gc( 0 ){ -} -~XORRectangle(){ - if ( initialised() ) { - gdk_gc_unref( m_gc ); - } -} -void set( rectangle_t rectangle ){ - if ( GTK_WIDGET_REALIZED( m_widget ) ) { - lazy_init(); - draw(); - m_rectangle = rectangle; - draw(); - } -} -}; - - -#endif diff --git a/tools/urt/libs/imagelib.cpp b/tools/urt/libs/imagelib.cpp deleted file mode 100644 index 9eb4f22..0000000 --- a/tools/urt/libs/imagelib.cpp +++ /dev/null @@ -1,2 +0,0 @@ - -#include "imagelib.h" diff --git a/tools/urt/libs/imagelib.h b/tools/urt/libs/imagelib.h deleted file mode 100644 index 08cef66..0000000 --- a/tools/urt/libs/imagelib.h +++ /dev/null @@ -1,114 +0,0 @@ - -#if !defined( INCLUDED_IMAGELIB_H ) -#define INCLUDED_IMAGELIB_H - -#include "iimage.h" -#include "iarchive.h" -#include "idatastream.h" -#include - -struct RGBAPixel -{ - unsigned char red, green, blue, alpha; -}; - -class RGBAImage : public Image -{ -RGBAImage( const RGBAImage& other ); -RGBAImage& operator=( const RGBAImage& other ); -public: -RGBAPixel* pixels; -unsigned int width, height; - -RGBAImage( unsigned int _width, unsigned int _height ) - : pixels( new RGBAPixel[_width * _height] ), width( _width ), height( _height ){ -} -~RGBAImage(){ - delete pixels; -} - -void release(){ - delete this; -} -byte* getRGBAPixels() const { - return reinterpret_cast( pixels ); -} -unsigned int getWidth() const { - return width; -} -unsigned int getHeight() const { - return height; -} -}; - -class RGBAImageFlags : public RGBAImage -{ -public: -int m_surfaceFlags; -int m_contentFlags; -int m_value; -RGBAImageFlags( unsigned short _width, unsigned short _height, int surfaceFlags, short contentFlags, int value ) : - RGBAImage( _width, _height ), m_surfaceFlags( surfaceFlags ), m_contentFlags( contentFlags ), m_value( value ){ -} - -int getSurfaceFlags() const { - return m_surfaceFlags; -} -int getContentFlags() const { - return m_contentFlags; -} -int getValue() const { - return m_value; -} -}; - - -inline InputStream::byte_type* ArchiveFile_loadBuffer( ArchiveFile& file, std::size_t& length ){ - InputStream::byte_type* buffer = (InputStream::byte_type*)malloc( file.size() + 1 ); - length = file.getInputStream().read( buffer, file.size() ); - buffer[file.size()] = 0; - return buffer; -} - -inline void ArchiveFile_freeBuffer( InputStream::byte_type* buffer ){ - free( buffer ); -} - -class ScopedArchiveBuffer -{ -public: -std::size_t length; -InputStream::byte_type* buffer; - -ScopedArchiveBuffer( ArchiveFile& file ){ - buffer = ArchiveFile_loadBuffer( file, length ); -} -~ScopedArchiveBuffer(){ - ArchiveFile_freeBuffer( buffer ); -} -}; - -class PointerInputStream : public InputStream -{ -const byte* m_read; -public: -PointerInputStream( const byte* pointer ) - : m_read( pointer ){ -} -std::size_t read( byte* buffer, std::size_t length ){ - const byte* end = m_read + length; - while ( m_read != end ) - { - *buffer++ = *m_read++; - } - return length; -} -void seek( std::size_t offset ){ - m_read += offset; -} -const byte* get(){ - return m_read; -} -}; - -#endif diff --git a/tools/urt/libs/instancelib.cpp b/tools/urt/libs/instancelib.cpp deleted file mode 100644 index 5fbde87..0000000 --- a/tools/urt/libs/instancelib.cpp +++ /dev/null @@ -1,2 +0,0 @@ - -#include "instancelib.h" diff --git a/tools/urt/libs/instancelib.h b/tools/urt/libs/instancelib.h deleted file mode 100644 index 3957c3b..0000000 --- a/tools/urt/libs/instancelib.h +++ /dev/null @@ -1,128 +0,0 @@ - -#if !defined ( INCLUDED_INSTANCELIB_H ) -#define INCLUDED_INSTANCELIB_H - -#include "debugging/debugging.h" - -#include "iscenegraph.h" - -#include "scenelib.h" -#include "generic/reference.h" -#include "generic/callback.h" -#include - -class InstanceSubgraphWalker : public scene::Traversable::Walker -{ -scene::Instantiable::Observer* m_observer; -mutable scene::Path m_path; -mutable Stack m_parent; -public: -InstanceSubgraphWalker( scene::Instantiable::Observer* observer, const scene::Path& path, scene::Instance* parent ) - : m_observer( observer ), m_path( path ), m_parent( parent ){ -} -bool pre( scene::Node& node ) const { - m_path.push( makeReference( node ) ); - scene::Instance* instance = Node_getInstantiable( node )->create( m_path, m_parent.top() ); - m_observer->insert( instance ); - Node_getInstantiable( node )->insert( m_observer, m_path, instance ); - m_parent.push( instance ); - return true; -} -void post( scene::Node& node ) const { - m_path.pop(); - m_parent.pop(); -} -}; - -class UninstanceSubgraphWalker : public scene::Traversable::Walker -{ -scene::Instantiable::Observer* m_observer; -mutable scene::Path m_path; -public: -UninstanceSubgraphWalker( scene::Instantiable::Observer* observer, const scene::Path& parent ) - : m_observer( observer ), m_path( parent ){ -} -bool pre( scene::Node& node ) const { - m_path.push( makeReference( node ) ); - return true; -} -void post( scene::Node& node ) const { - scene::Instance* instance = Node_getInstantiable( node )->erase( m_observer, m_path ); - m_observer->erase( instance ); - delete instance; - m_path.pop(); -} -}; - -class Instances : public scene::Traversable::Observer -{ -typedef std::pair CachePath; - -typedef CachePath key_type; - -typedef std::map InstanceMap; -InstanceMap m_instances; -public: - -typedef InstanceMap::iterator iterator; - -iterator begin(){ - return m_instances.begin(); -} -iterator end(){ - return m_instances.end(); -} - -// traverse observer -void insert( scene::Node& child ){ - for ( iterator i = begin(); i != end(); ++i ) - { - Node_traverseSubgraph( child, InstanceSubgraphWalker( ( *i ).first.first, ( *i ).first.second, ( *i ).second ) ); - ( *i ).second->boundsChanged(); - } -} -void erase( scene::Node& child ){ - for ( iterator i = begin(); i != end(); ++i ) - { - Node_traverseSubgraph( child, UninstanceSubgraphWalker( ( *i ).first.first, ( *i ).first.second ) ); - ( *i ).second->boundsChanged(); - } -} - -// instance -void forEachInstance( const scene::Instantiable::Visitor& visitor ){ - for ( iterator i = begin(); i != end(); ++i ) - { - visitor.visit( *( *i ).second ); - } -} - -void insert( scene::Instantiable::Observer* observer, const scene::Path& path, scene::Instance* instance ){ - ASSERT_MESSAGE( m_instances.find( key_type( observer, PathConstReference( instance->path() ) ) ) == m_instances.end(), "Instances::insert - element already exists" ); - m_instances.insert( InstanceMap::value_type( key_type( observer, PathConstReference( instance->path() ) ), instance ) ); -} -scene::Instance* erase( scene::Instantiable::Observer* observer, const scene::Path& path ){ - ASSERT_MESSAGE( m_instances.find( key_type( observer, PathConstReference( path ) ) ) != m_instances.end(), "Instances::erase - failed to find element" ); - InstanceMap::iterator i = m_instances.find( key_type( observer, PathConstReference( path ) ) ); - scene::Instance* instance = i->second; - m_instances.erase( i ); - return instance; -} - -void transformChanged(){ - for ( InstanceMap::iterator i = m_instances.begin(); i != m_instances.end(); ++i ) - { - ( *i ).second->transformChanged(); - } -} -typedef MemberCaller TransformChangedCaller; -void boundsChanged(){ - for ( InstanceMap::iterator i = m_instances.begin(); i != m_instances.end(); ++i ) - { - ( *i ).second->boundsChanged(); - } -} -typedef MemberCaller BoundsChangedCaller; -}; - -#endif diff --git a/tools/urt/libs/jpeg6/jchuff.h b/tools/urt/libs/jpeg6/jchuff.h deleted file mode 100644 index dbf52b3..0000000 --- a/tools/urt/libs/jpeg6/jchuff.h +++ /dev/null @@ -1,67 +0,0 @@ -/* - - * jchuff.h - - * - - * Copyright (C) 1991-1995, Thomas G. Lane. - - * This file is part of the Independent JPEG Group's software. - - * For conditions of distribution and use, see the accompanying README file. - - * - - * This file contains declarations for Huffman entropy encoding routines - - * that are shared between the sequential encoder (jchuff.c) and the - - * progressive encoder (jcphuff.c). No other modules need to see these. - - */ - - - -/* Derived data constructed for each Huffman table */ - - - -typedef struct { - - unsigned int ehufco[256]; /* code for each symbol */ - - char ehufsi[256]; /* length of code for each symbol */ - - /* If no code has been allocated for a symbol S, ehufsi[S] contains 0 */ - -} c_derived_tbl; - - - -/* Short forms of external names for systems with brain-damaged linkers. */ - - - -#ifdef NEED_SHORT_EXTERNAL_NAMES - -#define jpeg_make_c_derived_tbl jMkCDerived - -#define jpeg_gen_optimal_table jGenOptTbl - -#endif /* NEED_SHORT_EXTERNAL_NAMES */ - - - -/* Expand a Huffman table definition into the derived format */ - -EXTERN void jpeg_make_c_derived_tbl JPP( ( j_compress_ptr cinfo, - - JHUFF_TBL * htbl, c_derived_tbl * *pdtbl ) ); - - - -/* Generate an optimal table definition given the specified counts */ - -EXTERN void jpeg_gen_optimal_table JPP( ( j_compress_ptr cinfo, - - JHUFF_TBL * htbl, long freq[] ) ); diff --git a/tools/urt/libs/jpeg6/jcomapi.cpp b/tools/urt/libs/jpeg6/jcomapi.cpp deleted file mode 100644 index 942cd88..0000000 --- a/tools/urt/libs/jpeg6/jcomapi.cpp +++ /dev/null @@ -1,180 +0,0 @@ -/* - - * jcomapi.c - - * - - * Copyright (C) 1994, Thomas G. Lane. - - * This file is part of the Independent JPEG Group's software. - - * For conditions of distribution and use, see the accompanying README file. - - * - - * This file contains application interface routines that are used for both - - * compression and decompression. - - */ - - - -#define JPEG_INTERNALS - -#include "jinclude.h" - -#include "radiant_jpeglib.h" - - - - - -/* - - * Abort processing of a JPEG compression or decompression operation, - - * but don't destroy the object itself. - - * - - * For this, we merely clean up all the nonpermanent memory pools. - - * Note that temp files (virtual arrays) are not allowed to belong to - - * the permanent pool, so we will be able to close all temp files here. - - * Closing a data source or destination, if necessary, is the application's - - * responsibility. - - */ - - - -GLOBAL void - -jpeg_abort( j_common_ptr cinfo ){ - - int pool; - - - - /* Releasing pools in reverse order might help avoid fragmentation - - * with some (brain-damaged) malloc libraries. - - */ - - for ( pool = JPOOL_NUMPOOLS - 1; pool > JPOOL_PERMANENT; pool-- ) { - - ( *cinfo->mem->free_pool )( cinfo, pool ); - - } - - - - /* Reset overall state for possible reuse of object */ - - cinfo->global_state = ( cinfo->is_decompressor ? DSTATE_START : CSTATE_START ); - -} - - - - - -/* - - * Destruction of a JPEG object. - - * - - * Everything gets deallocated except the master jpeg_compress_struct itself - - * and the error manager struct. Both of these are supplied by the application - - * and must be freed, if necessary, by the application. (Often they are on - - * the stack and so don't need to be freed anyway.) - - * Closing a data source or destination, if necessary, is the application's - - * responsibility. - - */ - - - -GLOBAL void - -jpeg_destroy( j_common_ptr cinfo ){ - - /* We need only tell the memory manager to release everything. */ - - /* NB: mem pointer is NULL if memory mgr failed to initialize. */ - - if ( cinfo->mem != NULL ) { - - ( *cinfo->mem->self_destruct )( cinfo ); - } - - cinfo->mem = NULL; /* be safe if jpeg_destroy is called twice */ - - cinfo->global_state = 0; /* mark it destroyed */ - -} - - - - - -/* - - * Convenience routines for allocating quantization and Huffman tables. - - * (Would jutils.c be a more reasonable place to put these?) - - */ - - - -GLOBAL JQUANT_TBL * - -jpeg_alloc_quant_table( j_common_ptr cinfo ){ - - JQUANT_TBL *tbl; - - - - tbl = (JQUANT_TBL *) - - ( *cinfo->mem->alloc_small )( cinfo, JPOOL_PERMANENT, SIZEOF( JQUANT_TBL ) ); - - tbl->sent_table = FALSE; /* make sure this is false in any new table */ - - return tbl; - -} - - - - - -GLOBAL JHUFF_TBL * - -jpeg_alloc_huff_table( j_common_ptr cinfo ){ - - JHUFF_TBL *tbl; - - - - tbl = (JHUFF_TBL *) - - ( *cinfo->mem->alloc_small )( cinfo, JPOOL_PERMANENT, SIZEOF( JHUFF_TBL ) ); - - tbl->sent_table = FALSE; /* make sure this is false in any new table */ - - return tbl; - -} diff --git a/tools/urt/libs/jpeg6/jconfig.h b/tools/urt/libs/jpeg6/jconfig.h deleted file mode 100644 index f62359e..0000000 --- a/tools/urt/libs/jpeg6/jconfig.h +++ /dev/null @@ -1,81 +0,0 @@ -/* jconfig.wat --- jconfig.h for Watcom C/C++ on MS-DOS or OS/2. */ - -/* see jconfig.doc for explanations */ - - - -#define HAVE_PROTOTYPES - -#define HAVE_UNSIGNED_CHAR - -#define HAVE_UNSIGNED_SHORT - -/* #define void char */ - -/* #define const */ - -#define CHAR_IS_UNSIGNED - -#define HAVE_STDDEF_H - -#define HAVE_STDLIB_H - -#undef NEED_BSD_STRINGS - -#undef NEED_SYS_TYPES_H - -#undef NEED_FAR_POINTERS /* Watcom uses flat 32-bit addressing */ - -#undef NEED_SHORT_EXTERNAL_NAMES - -#undef INCOMPLETE_TYPES_BROKEN - - - -#define JDCT_DEFAULT JDCT_FLOAT - -#define JDCT_FASTEST JDCT_FLOAT - - - -#ifdef JPEG_INTERNALS - - - -#undef RIGHT_SHIFT_IS_UNSIGNED - - - -#endif /* JPEG_INTERNALS */ - - - -#ifdef JPEG_CJPEG_DJPEG - - - -#define BMP_SUPPORTED /* BMP image file format */ - -#define GIF_SUPPORTED /* GIF image file format */ - -#define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */ - -#undef RLE_SUPPORTED /* Utah RLE image file format */ - -#define TARGA_SUPPORTED /* Targa image file format */ - - - -#undef TWO_FILE_COMMANDLINE /* optional */ - -#define USE_SETMODE /* Needed to make one-file style work in Watcom */ - -#undef NEED_SIGNAL_CATCHER /* Define this if you use jmemname.c */ - -#undef DONT_USE_B_MODE - -#undef PROGRESS_REPORT /* optional */ - - - -#endif /* JPEG_CJPEG_DJPEG */ diff --git a/tools/urt/libs/jpeg6/jdapimin.cpp b/tools/urt/libs/jpeg6/jdapimin.cpp deleted file mode 100644 index 0d51adc..0000000 --- a/tools/urt/libs/jpeg6/jdapimin.cpp +++ /dev/null @@ -1,795 +0,0 @@ -/* - - * jdapimin.c - - * - - * Copyright (C) 1994-1995, Thomas G. Lane. - - * This file is part of the Independent JPEG Group's software. - - * For conditions of distribution and use, see the accompanying README file. - - * - - * This file contains application interface code for the decompression half - - * of the JPEG library. These are the "minimum" API routines that may be - - * needed in either the normal full-decompression case or the - - * transcoding-only case. - - * - - * Most of the routines intended to be called directly by an application - - * are in this file or in jdapistd.c. But also see jcomapi.c for routines - - * shared by compression and decompression, and jdtrans.c for the transcoding - - * case. - - */ - - - -#define JPEG_INTERNALS - -#include "jinclude.h" - -#include "radiant_jpeglib.h" - - - - - -/* - - * Initialization of a JPEG decompression object. - - * The error manager must already be set up (in case memory manager fails). - - */ - - - -GLOBAL void - -jpeg_create_decompress( j_decompress_ptr cinfo ){ - - int i; - - - - /* For debugging purposes, zero the whole master structure. - - * But error manager pointer is already there, so save and restore it. - - */ - - { - - struct jpeg_error_mgr * err = cinfo->err; - - i = sizeof( struct jpeg_decompress_struct ); - - i = SIZEOF( struct jpeg_decompress_struct ); - - MEMZERO( cinfo, SIZEOF( struct jpeg_decompress_struct ) ); - - cinfo->err = err; - - } - - cinfo->is_decompressor = TRUE; - - - - /* Initialize a memory manager instance for this object */ - - jinit_memory_mgr( (j_common_ptr) cinfo ); - - - - /* Zero out pointers to permanent structures. */ - - cinfo->progress = NULL; - - cinfo->src = NULL; - - - - for ( i = 0; i < NUM_QUANT_TBLS; i++ ) - - cinfo->quant_tbl_ptrs[i] = NULL; - - - - for ( i = 0; i < NUM_HUFF_TBLS; i++ ) { - - cinfo->dc_huff_tbl_ptrs[i] = NULL; - - cinfo->ac_huff_tbl_ptrs[i] = NULL; - - } - - - - /* Initialize marker processor so application can override methods - - * for COM, APPn markers before calling jpeg_read_header. - - */ - - jinit_marker_reader( cinfo ); - - - - /* And initialize the overall input controller. */ - - jinit_input_controller( cinfo ); - - - - /* OK, I'm ready */ - - cinfo->global_state = DSTATE_START; - -} - - - - - -/* - - * Destruction of a JPEG decompression object - - */ - - - -GLOBAL void - -jpeg_destroy_decompress( j_decompress_ptr cinfo ){ - - jpeg_destroy( (j_common_ptr) cinfo ); /* use common routine */ - -} - - - - - -/* - - * Abort processing of a JPEG decompression operation, - - * but don't destroy the object itself. - - */ - - - -GLOBAL void - -jpeg_abort_decompress( j_decompress_ptr cinfo ){ - - jpeg_abort( (j_common_ptr) cinfo ); /* use common routine */ - -} - - - - - -/* - - * Install a special processing method for COM or APPn markers. - - */ - - - -GLOBAL void - -jpeg_set_marker_processor( j_decompress_ptr cinfo, int marker_code, - - jpeg_marker_parser_method routine ){ - - if ( marker_code == JPEG_COM ) { - - cinfo->marker->process_COM = routine; - } - - else if ( marker_code >= JPEG_APP0 && marker_code <= JPEG_APP0 + 15 ) { - - cinfo->marker->process_APPn[marker_code - JPEG_APP0] = routine; - } - - else{ - - ERREXIT1( cinfo, JERR_UNKNOWN_MARKER, marker_code ); - } - -} - - - - - -/* - - * Set default decompression parameters. - - */ - - - -LOCAL void - -default_decompress_parms( j_decompress_ptr cinfo ){ - - /* Guess the input colorspace, and set output colorspace accordingly. */ - - /* (Wish JPEG committee had provided a real way to specify this...) */ - - /* Note application may override our guesses. */ - - switch ( cinfo->num_components ) { - - case 1: - - cinfo->jpeg_color_space = JCS_GRAYSCALE; - - cinfo->out_color_space = JCS_GRAYSCALE; - - break; - - - - case 3: - - if ( cinfo->saw_JFIF_marker ) { - - cinfo->jpeg_color_space = JCS_YCbCr; /* JFIF implies YCbCr */ - - } - else if ( cinfo->saw_Adobe_marker ) { - - switch ( cinfo->Adobe_transform ) { - - case 0: - - cinfo->jpeg_color_space = JCS_RGB; - - break; - - case 1: - - cinfo->jpeg_color_space = JCS_YCbCr; - - break; - - default: - - WARNMS1( cinfo, JWRN_ADOBE_XFORM, cinfo->Adobe_transform ); - - cinfo->jpeg_color_space = JCS_YCbCr; /* assume it's YCbCr */ - - break; - - } - - } - else { - - /* Saw no special markers, try to guess from the component IDs */ - - int cid0 = cinfo->comp_info[0].component_id; - - int cid1 = cinfo->comp_info[1].component_id; - - int cid2 = cinfo->comp_info[2].component_id; - - - - if ( cid0 == 1 && cid1 == 2 && cid2 == 3 ) { - - cinfo->jpeg_color_space = JCS_YCbCr; /* assume JFIF w/out marker */ - - } - else if ( cid0 == 82 && cid1 == 71 && cid2 == 66 ) { - - cinfo->jpeg_color_space = JCS_RGB; /* ASCII 'R', 'G', 'B' */ - - } - else { - - TRACEMS3( cinfo, 1, JTRC_UNKNOWN_IDS, cid0, cid1, cid2 ); - - cinfo->jpeg_color_space = JCS_YCbCr; /* assume it's YCbCr */ - - } - - } - - /* Always guess RGB is proper output colorspace. */ - - cinfo->out_color_space = JCS_RGB; - - break; - - - - case 4: - - if ( cinfo->saw_Adobe_marker ) { - - switch ( cinfo->Adobe_transform ) { - - case 0: - - cinfo->jpeg_color_space = JCS_CMYK; - - break; - - case 2: - - cinfo->jpeg_color_space = JCS_YCCK; - - break; - - default: - - WARNMS1( cinfo, JWRN_ADOBE_XFORM, cinfo->Adobe_transform ); - - cinfo->jpeg_color_space = JCS_YCCK; /* assume it's YCCK */ - - break; - - } - - } - else { - - /* No special markers, assume straight CMYK. */ - - cinfo->jpeg_color_space = JCS_CMYK; - - } - - cinfo->out_color_space = JCS_CMYK; - - break; - - - - default: - - cinfo->jpeg_color_space = JCS_UNKNOWN; - - cinfo->out_color_space = JCS_UNKNOWN; - - break; - - } - - - - /* Set defaults for other decompression parameters. */ - - cinfo->scale_num = 1; /* 1:1 scaling */ - - cinfo->scale_denom = 1; - - cinfo->output_gamma = 1.0; - - cinfo->buffered_image = FALSE; - - cinfo->raw_data_out = FALSE; - - cinfo->dct_method = JDCT_DEFAULT; - - cinfo->do_fancy_upsampling = TRUE; - - cinfo->do_block_smoothing = TRUE; - - cinfo->quantize_colors = FALSE; - - /* We set these in case application only sets quantize_colors. */ - - cinfo->dither_mode = JDITHER_FS; - -#ifdef QUANT_2PASS_SUPPORTED - - cinfo->two_pass_quantize = TRUE; - -#else - - cinfo->two_pass_quantize = FALSE; - -#endif - - cinfo->desired_number_of_colors = 256; - - cinfo->colormap = NULL; - - /* Initialize for no mode change in buffered-image mode. */ - - cinfo->enable_1pass_quant = FALSE; - - cinfo->enable_external_quant = FALSE; - - cinfo->enable_2pass_quant = FALSE; - -} - - - - - -/* - - * Decompression startup: read start of JPEG datastream to see what's there. - - * Need only initialize JPEG object and supply a data source before calling. - - * - - * This routine will read as far as the first SOS marker (ie, actual start of - - * compressed data), and will save all tables and parameters in the JPEG - - * object. It will also initialize the decompression parameters to default - - * values, and finally return JPEG_HEADER_OK. On return, the application may - - * adjust the decompression parameters and then call jpeg_start_decompress. - - * (Or, if the application only wanted to determine the image parameters, - - * the data need not be decompressed. In that case, call jpeg_abort or - - * jpeg_destroy to release any temporary space.) - - * If an abbreviated (tables only) datastream is presented, the routine will - - * return JPEG_HEADER_TABLES_ONLY upon reaching EOI. The application may then - - * re-use the JPEG object to read the abbreviated image datastream(s). - - * It is unnecessary (but OK) to call jpeg_abort in this case. - - * The JPEG_SUSPENDED return code only occurs if the data source module - - * requests suspension of the decompressor. In this case the application - - * should load more source data and then re-call jpeg_read_header to resume - - * processing. - - * If a non-suspending data source is used and require_image is TRUE, then the - - * return code need not be inspected since only JPEG_HEADER_OK is possible. - - * - - * This routine is now just a front end to jpeg_consume_input, with some - - * extra error checking. - - */ - - - -GLOBAL int - -jpeg_read_header( j_decompress_ptr cinfo, boolean require_image ){ - - int retcode; - - - - if ( cinfo->global_state != DSTATE_START && - - cinfo->global_state != DSTATE_INHEADER ) { - - ERREXIT1( cinfo, JERR_BAD_STATE, cinfo->global_state ); - } - - - - retcode = jpeg_consume_input( cinfo ); - - - - switch ( retcode ) { - - case JPEG_REACHED_SOS: - - retcode = JPEG_HEADER_OK; - - break; - - case JPEG_REACHED_EOI: - - if ( require_image ) { /* Complain if application wanted an image */ - - ERREXIT( cinfo, JERR_NO_IMAGE ); - } - - /* Reset to start state; it would be safer to require the application to - - * call jpeg_abort, but we can't change it now for compatibility reasons. - - * A side effect is to free any temporary memory (there shouldn't be any). - - */ - - jpeg_abort( (j_common_ptr) cinfo ); /* sets state = DSTATE_START */ - - retcode = JPEG_HEADER_TABLES_ONLY; - - break; - - case JPEG_SUSPENDED: - - /* no work */ - - break; - - } - - - - return retcode; - -} - - - - - -/* - - * Consume data in advance of what the decompressor requires. - - * This can be called at any time once the decompressor object has - - * been created and a data source has been set up. - - * - - * This routine is essentially a state machine that handles a couple - - * of critical state-transition actions, namely initial setup and - - * transition from header scanning to ready-for-start_decompress. - - * All the actual input is done via the input controller's consume_input - - * method. - - */ - - - -GLOBAL int - -jpeg_consume_input( j_decompress_ptr cinfo ){ - - int retcode = JPEG_SUSPENDED; - - - - /* NB: every possible DSTATE value should be listed in this switch */ - - switch ( cinfo->global_state ) { - - case DSTATE_START: - - /* Start-of-datastream actions: reset appropriate modules */ - - ( *cinfo->inputctl->reset_input_controller )( cinfo ); - - /* Initialize application's data source module */ - - ( *cinfo->src->init_source )( cinfo ); - - cinfo->global_state = DSTATE_INHEADER; - - /*FALLTHROUGH*/ - - case DSTATE_INHEADER: - - retcode = ( *cinfo->inputctl->consume_input )( cinfo ); - - if ( retcode == JPEG_REACHED_SOS ) { /* Found SOS, prepare to decompress */ - - /* Set up default parameters based on header data */ - - default_decompress_parms( cinfo ); - - /* Set global state: ready for start_decompress */ - - cinfo->global_state = DSTATE_READY; - - } - - break; - - case DSTATE_READY: - - /* Can't advance past first SOS until start_decompress is called */ - - retcode = JPEG_REACHED_SOS; - - break; - - case DSTATE_PRELOAD: - - case DSTATE_PRESCAN: - - case DSTATE_SCANNING: - - case DSTATE_RAW_OK: - - case DSTATE_BUFIMAGE: - - case DSTATE_BUFPOST: - - case DSTATE_STOPPING: - - retcode = ( *cinfo->inputctl->consume_input )( cinfo ); - - break; - - default: - - ERREXIT1( cinfo, JERR_BAD_STATE, cinfo->global_state ); - - } - - return retcode; - -} - - - - - -/* - - * Have we finished reading the input file? - - */ - - - -GLOBAL boolean - -jpeg_input_complete( j_decompress_ptr cinfo ){ - - /* Check for valid jpeg object */ - - if ( cinfo->global_state < DSTATE_START || - - cinfo->global_state > DSTATE_STOPPING ) { - - ERREXIT1( cinfo, JERR_BAD_STATE, cinfo->global_state ); - } - - return cinfo->inputctl->eoi_reached; - -} - - - - - -/* - - * Is there more than one scan? - - */ - - - -GLOBAL boolean - -jpeg_has_multiple_scans( j_decompress_ptr cinfo ){ - - /* Only valid after jpeg_read_header completes */ - - if ( cinfo->global_state < DSTATE_READY || - - cinfo->global_state > DSTATE_STOPPING ) { - - ERREXIT1( cinfo, JERR_BAD_STATE, cinfo->global_state ); - } - - return cinfo->inputctl->has_multiple_scans; - -} - - - - - -/* - - * Finish JPEG decompression. - - * - - * This will normally just verify the file trailer and release temp storage. - - * - - * Returns FALSE if suspended. The return value need be inspected only if - - * a suspending data source is used. - - */ - - - -GLOBAL boolean - -jpeg_finish_decompress( j_decompress_ptr cinfo ){ - - if ( ( cinfo->global_state == DSTATE_SCANNING || - - cinfo->global_state == DSTATE_RAW_OK ) && !cinfo->buffered_image ) { - - /* Terminate final pass of non-buffered mode */ - - if ( cinfo->output_scanline < cinfo->output_height ) { - - ERREXIT( cinfo, JERR_TOO_LITTLE_DATA ); - } - - ( *cinfo->master->finish_output_pass )( cinfo ); - - cinfo->global_state = DSTATE_STOPPING; - - } - else if ( cinfo->global_state == DSTATE_BUFIMAGE ) { - - /* Finishing after a buffered-image operation */ - - cinfo->global_state = DSTATE_STOPPING; - - } - else if ( cinfo->global_state != DSTATE_STOPPING ) { - - /* STOPPING = repeat call after a suspension, anything else is error */ - - ERREXIT1( cinfo, JERR_BAD_STATE, cinfo->global_state ); - - } - - /* Read until EOI */ - - while ( !cinfo->inputctl->eoi_reached ) { - - if ( ( *cinfo->inputctl->consume_input )( cinfo ) == JPEG_SUSPENDED ) { - - return FALSE; /* Suspend, come back later */ - - } - } - - /* Do final cleanup */ - - ( *cinfo->src->term_source )( cinfo ); - - /* We can use jpeg_abort to release memory and reset global_state */ - - jpeg_abort( (j_common_ptr) cinfo ); - - return TRUE; - -} diff --git a/tools/urt/libs/jpeg6/jdapistd.cpp b/tools/urt/libs/jpeg6/jdapistd.cpp deleted file mode 100644 index 3f0b11d..0000000 --- a/tools/urt/libs/jpeg6/jdapistd.cpp +++ /dev/null @@ -1,552 +0,0 @@ -/* - - * jdapistd.c - - * - - * Copyright (C) 1994-1995, Thomas G. Lane. - - * This file is part of the Independent JPEG Group's software. - - * For conditions of distribution and use, see the accompanying README file. - - * - - * This file contains application interface code for the decompression half - - * of the JPEG library. These are the "standard" API routines that are - - * used in the normal full-decompression case. They are not used by a - - * transcoding-only application. Note that if an application links in - - * jpeg_start_decompress, it will end up linking in the entire decompressor. - - * We thus must separate this file from jdapimin.c to avoid linking the - - * whole decompression library into a transcoder. - - */ - - - -#define JPEG_INTERNALS - -#include "jinclude.h" - -#include "radiant_jpeglib.h" - - - - - -/* Forward declarations */ - -LOCAL boolean output_pass_setup JPP( (j_decompress_ptr cinfo) ); - - - - - -/* - - * Decompression initialization. - - * jpeg_read_header must be completed before calling this. - - * - - * If a multipass operating mode was selected, this will do all but the - - * last pass, and thus may take a great deal of time. - - * - - * Returns FALSE if suspended. The return value need be inspected only if - - * a suspending data source is used. - - */ - - - -GLOBAL boolean - -jpeg_start_decompress( j_decompress_ptr cinfo ){ - - if ( cinfo->global_state == DSTATE_READY ) { - - /* First call: initialize master control, select active modules */ - - jinit_master_decompress( cinfo ); - - if ( cinfo->buffered_image ) { - - /* No more work here; expecting jpeg_start_output next */ - - cinfo->global_state = DSTATE_BUFIMAGE; - - return TRUE; - - } - - cinfo->global_state = DSTATE_PRELOAD; - - } - - if ( cinfo->global_state == DSTATE_PRELOAD ) { - - /* If file has multiple scans, absorb them all into the coef buffer */ - - if ( cinfo->inputctl->has_multiple_scans ) { - -#ifdef D_MULTISCAN_FILES_SUPPORTED - - for (;; ) { - - int retcode; - - /* Call progress monitor hook if present */ - - if ( cinfo->progress != NULL ) { - - ( *cinfo->progress->progress_monitor )( (j_common_ptr) cinfo ); - } - - /* Absorb some more input */ - - retcode = ( *cinfo->inputctl->consume_input )( cinfo ); - - if ( retcode == JPEG_SUSPENDED ) { - - return FALSE; - } - - if ( retcode == JPEG_REACHED_EOI ) { - - break; - } - - /* Advance progress counter if appropriate */ - - if ( cinfo->progress != NULL && - - ( retcode == JPEG_ROW_COMPLETED || retcode == JPEG_REACHED_SOS ) ) { - - if ( ++cinfo->progress->pass_counter >= cinfo->progress->pass_limit ) { - - /* jdmaster underestimated number of scans; ratchet up one scan */ - - cinfo->progress->pass_limit += (long) cinfo->total_iMCU_rows; - - } - - } - - } - -#else - - ERREXIT( cinfo, JERR_NOT_COMPILED ); - -#endif /* D_MULTISCAN_FILES_SUPPORTED */ - - } - - cinfo->output_scan_number = cinfo->input_scan_number; - - } - else if ( cinfo->global_state != DSTATE_PRESCAN ) { - - ERREXIT1( cinfo, JERR_BAD_STATE, cinfo->global_state ); - } - - /* Perform any dummy output passes, and set up for the final pass */ - - return output_pass_setup( cinfo ); - -} - - - - - -/* - - * Set up for an output pass, and perform any dummy pass(es) needed. - - * Common subroutine for jpeg_start_decompress and jpeg_start_output. - - * Entry: global_state = DSTATE_PRESCAN only if previously suspended. - - * Exit: If done, returns TRUE and sets global_state for proper output mode. - - * If suspended, returns FALSE and sets global_state = DSTATE_PRESCAN. - - */ - - - -LOCAL boolean - -output_pass_setup( j_decompress_ptr cinfo ){ - - if ( cinfo->global_state != DSTATE_PRESCAN ) { - - /* First call: do pass setup */ - - ( *cinfo->master->prepare_for_output_pass )( cinfo ); - - cinfo->output_scanline = 0; - - cinfo->global_state = DSTATE_PRESCAN; - - } - - /* Loop over any required dummy passes */ - - while ( cinfo->master->is_dummy_pass ) { - -#ifdef QUANT_2PASS_SUPPORTED - - /* Crank through the dummy pass */ - - while ( cinfo->output_scanline < cinfo->output_height ) { - - JDIMENSION last_scanline; - - /* Call progress monitor hook if present */ - - if ( cinfo->progress != NULL ) { - - cinfo->progress->pass_counter = (long) cinfo->output_scanline; - - cinfo->progress->pass_limit = (long) cinfo->output_height; - - ( *cinfo->progress->progress_monitor )( (j_common_ptr) cinfo ); - - } - - /* Process some data */ - - last_scanline = cinfo->output_scanline; - - ( *cinfo->main->process_data )( cinfo, (JSAMPARRAY) NULL, - - &cinfo->output_scanline, (JDIMENSION) 0 ); - - if ( cinfo->output_scanline == last_scanline ) { - - return FALSE; /* No progress made, must suspend */ - - } - } - - /* Finish up dummy pass, and set up for another one */ - - ( *cinfo->master->finish_output_pass )( cinfo ); - - ( *cinfo->master->prepare_for_output_pass )( cinfo ); - - cinfo->output_scanline = 0; - -#else - - ERREXIT( cinfo, JERR_NOT_COMPILED ); - -#endif /* QUANT_2PASS_SUPPORTED */ - - } - - /* Ready for application to drive output pass through - - * jpeg_read_scanlines or jpeg_read_raw_data. - - */ - - cinfo->global_state = cinfo->raw_data_out ? DSTATE_RAW_OK : DSTATE_SCANNING; - - return TRUE; - -} - - - - - -/* - - * Read some scanlines of data from the JPEG decompressor. - - * - - * The return value will be the number of lines actually read. - - * This may be less than the number requested in several cases, - - * including bottom of image, data source suspension, and operating - - * modes that emit multiple scanlines at a time. - - * - - * Note: we warn about excess calls to jpeg_read_scanlines() since - - * this likely signals an application programmer error. However, - - * an oversize buffer (max_lines > scanlines remaining) is not an error. - - */ - - - -GLOBAL JDIMENSION - -jpeg_read_scanlines( j_decompress_ptr cinfo, JSAMPARRAY scanlines, - - JDIMENSION max_lines ){ - - JDIMENSION row_ctr; - - - - if ( cinfo->global_state != DSTATE_SCANNING ) { - - ERREXIT1( cinfo, JERR_BAD_STATE, cinfo->global_state ); - } - - if ( cinfo->output_scanline >= cinfo->output_height ) { - - WARNMS( cinfo, JWRN_TOO_MUCH_DATA ); - - return 0; - - } - - - - /* Call progress monitor hook if present */ - - if ( cinfo->progress != NULL ) { - - cinfo->progress->pass_counter = (long) cinfo->output_scanline; - - cinfo->progress->pass_limit = (long) cinfo->output_height; - - ( *cinfo->progress->progress_monitor )( (j_common_ptr) cinfo ); - - } - - - - /* Process some data */ - - row_ctr = 0; - - ( *cinfo->main->process_data )( cinfo, scanlines, &row_ctr, max_lines ); - - cinfo->output_scanline += row_ctr; - - return row_ctr; - -} - - - - - -/* - - * Alternate entry point to read raw data. - - * Processes exactly one iMCU row per call, unless suspended. - - */ - - - -GLOBAL JDIMENSION - -jpeg_read_raw_data( j_decompress_ptr cinfo, JSAMPIMAGE data, - - JDIMENSION max_lines ){ - - JDIMENSION lines_per_iMCU_row; - - - - if ( cinfo->global_state != DSTATE_RAW_OK ) { - - ERREXIT1( cinfo, JERR_BAD_STATE, cinfo->global_state ); - } - - if ( cinfo->output_scanline >= cinfo->output_height ) { - - WARNMS( cinfo, JWRN_TOO_MUCH_DATA ); - - return 0; - - } - - - - /* Call progress monitor hook if present */ - - if ( cinfo->progress != NULL ) { - - cinfo->progress->pass_counter = (long) cinfo->output_scanline; - - cinfo->progress->pass_limit = (long) cinfo->output_height; - - ( *cinfo->progress->progress_monitor )( (j_common_ptr) cinfo ); - - } - - - - /* Verify that at least one iMCU row can be returned. */ - - lines_per_iMCU_row = cinfo->max_v_samp_factor * cinfo->min_DCT_scaled_size; - - if ( max_lines < lines_per_iMCU_row ) { - - ERREXIT( cinfo, JERR_BUFFER_SIZE ); - } - - - - /* Decompress directly into user's buffer. */ - - if ( !( *cinfo->coef->decompress_data )( cinfo, data ) ) { - - return 0; /* suspension forced, can do nothing more */ - - - - } - /* OK, we processed one iMCU row. */ - - cinfo->output_scanline += lines_per_iMCU_row; - - return lines_per_iMCU_row; - -} - - - - - -/* Additional entry points for buffered-image mode. */ - - - -#ifdef D_MULTISCAN_FILES_SUPPORTED - - - -/* - - * Initialize for an output pass in buffered-image mode. - - */ - - - -GLOBAL boolean - -jpeg_start_output( j_decompress_ptr cinfo, int scan_number ){ - - if ( cinfo->global_state != DSTATE_BUFIMAGE && - - cinfo->global_state != DSTATE_PRESCAN ) { - - ERREXIT1( cinfo, JERR_BAD_STATE, cinfo->global_state ); - } - - /* Limit scan number to valid range */ - - if ( scan_number <= 0 ) { - - scan_number = 1; - } - - if ( cinfo->inputctl->eoi_reached && - - scan_number > cinfo->input_scan_number ) { - - scan_number = cinfo->input_scan_number; - } - - cinfo->output_scan_number = scan_number; - - /* Perform any dummy output passes, and set up for the real pass */ - - return output_pass_setup( cinfo ); - -} - - - - - -/* - - * Finish up after an output pass in buffered-image mode. - - * - - * Returns FALSE if suspended. The return value need be inspected only if - - * a suspending data source is used. - - */ - - - -GLOBAL boolean - -jpeg_finish_output( j_decompress_ptr cinfo ){ - - if ( ( cinfo->global_state == DSTATE_SCANNING || - - cinfo->global_state == DSTATE_RAW_OK ) && cinfo->buffered_image ) { - - /* Terminate this pass. */ - - /* We do not require the whole pass to have been completed. */ - - ( *cinfo->master->finish_output_pass )( cinfo ); - - cinfo->global_state = DSTATE_BUFPOST; - - } - else if ( cinfo->global_state != DSTATE_BUFPOST ) { - - /* BUFPOST = repeat call after a suspension, anything else is error */ - - ERREXIT1( cinfo, JERR_BAD_STATE, cinfo->global_state ); - - } - - /* Read markers looking for SOS or EOI */ - - while ( cinfo->input_scan_number <= cinfo->output_scan_number && - - !cinfo->inputctl->eoi_reached ) { - - if ( ( *cinfo->inputctl->consume_input )( cinfo ) == JPEG_SUSPENDED ) { - - return FALSE; /* Suspend, come back later */ - - } - } - - cinfo->global_state = DSTATE_BUFIMAGE; - - return TRUE; - -} - - - -#endif /* D_MULTISCAN_FILES_SUPPORTED */ diff --git a/tools/urt/libs/jpeg6/jdatasrc.cpp b/tools/urt/libs/jpeg6/jdatasrc.cpp deleted file mode 100644 index 53a1d87..0000000 --- a/tools/urt/libs/jpeg6/jdatasrc.cpp +++ /dev/null @@ -1,211 +0,0 @@ -/* - * jdatasrc.c - * - * Copyright (C) 1994, Thomas G. Lane. - * This file is part of the Independent JPEG Group's software. - * For conditions of distribution and use, see the accompanying README file. - * - * This file contains decompression data source routines for the case of - * reading JPEG data from a file (or any stdio stream). While these routines - * are sufficient for most applications, some will want to use a different - * source manager. - * IMPORTANT: we assume that fread() will correctly transcribe an array of - * JOCTETs from 8-bit-wide elements on external storage. If char is wider - * than 8 bits on your machine, you may need to do some tweaking. - */ - - -/* this is not a core library module, so it doesn't define JPEG_INTERNALS */ -#include "jinclude.h" -#include "radiant_jpeglib.h" -#include "jerror.h" - -//extern int leo_buf_size; // FIXME ? merged in from Alpha - replaced by my_source_mgr->src_size - -/* Expanded data source object for stdio input */ - -typedef struct { - struct jpeg_source_mgr pub; /* public fields */ - int src_size; // FIXME ? merged from Alpha - unsigned char *infile; /* source stream */ - JOCTET * buffer; /* start of buffer */ - boolean start_of_file; /* have we gotten any data yet? */ -} my_source_mgr; - -typedef my_source_mgr * my_src_ptr; - -#define INPUT_BUF_SIZE 4096 /* choose an efficiently fread'able size */ - - -/* - * Initialize source --- called by jpeg_read_header - * before any data is actually read. - */ - -METHODDEF void -init_source( j_decompress_ptr cinfo ){ - my_src_ptr src = (my_src_ptr) cinfo->src; - - /* We reset the empty-input-file flag for each image, - * but we don't clear the input buffer. - * This is correct behavior for reading a series of images from one source. - */ - src->start_of_file = TRUE; -} - - -/* - * Fill the input buffer --- called whenever buffer is emptied. - * - * In typical applications, this should read fresh data into the buffer - * (ignoring the current state of next_input_byte & bytes_in_buffer), - * reset the pointer & count to the start of the buffer, and return TRUE - * indicating that the buffer has been reloaded. It is not necessary to - * fill the buffer entirely, only to obtain at least one more byte. - * - * There is no such thing as an EOF return. If the end of the file has been - * reached, the routine has a choice of ERREXIT() or inserting fake data into - * the buffer. In most cases, generating a warning message and inserting a - * fake EOI marker is the best course of action --- this will allow the - * decompressor to output however much of the image is there. However, - * the resulting error message is misleading if the real problem is an empty - * input file, so we handle that case specially. - * - * In applications that need to be able to suspend compression due to input - * not being available yet, a FALSE return indicates that no more data can be - * obtained right now, but more may be forthcoming later. In this situation, - * the decompressor will return to its caller (with an indication of the - * number of scanlines it has read, if any). The application should resume - * decompression after it has loaded more data into the input buffer. Note - * that there are substantial restrictions on the use of suspension --- see - * the documentation. - * - * When suspending, the decompressor will back up to a convenient restart point - * (typically the start of the current MCU). next_input_byte & bytes_in_buffer - * indicate where the restart point will be if the current call returns FALSE. - * Data beyond this point must be rescanned after resumption, so move it to - * the front of the buffer rather than discarding it. - */ - -METHODDEF boolean -// FIXME ? merged in from Alpha -fill_input_buffer( j_decompress_ptr cinfo ){ - my_src_ptr src = (my_src_ptr) cinfo->src; - size_t nbytes; - - if ( src->src_size > INPUT_BUF_SIZE ) { - nbytes = INPUT_BUF_SIZE; - } - else{ - nbytes = src->src_size; - } - - memcpy( src->buffer, src->infile, nbytes ); - - src->infile += nbytes; - src->src_size -= nbytes; - - src->pub.next_input_byte = src->buffer; - src->pub.bytes_in_buffer = nbytes; - src->start_of_file = FALSE; - - return TRUE; -} - - -/* - * Skip data --- used to skip over a potentially large amount of - * uninteresting data (such as an APPn marker). - * - * Writers of suspendable-input applications must note that skip_input_data - * is not granted the right to give a suspension return. If the skip extends - * beyond the data currently in the buffer, the buffer can be marked empty so - * that the next read will cause a fill_input_buffer call that can suspend. - * Arranging for additional bytes to be discarded before reloading the input - * buffer is the application writer's problem. - */ - -METHODDEF void -skip_input_data( j_decompress_ptr cinfo, long num_bytes ){ - my_src_ptr src = (my_src_ptr) cinfo->src; - - /* Just a dumb implementation for now. Could use fseek() except - * it doesn't work on pipes. Not clear that being smart is worth - * any trouble anyway --- large skips are infrequent. - */ - if ( num_bytes > 0 ) { - while ( num_bytes > (long) src->pub.bytes_in_buffer ) { - num_bytes -= (long) src->pub.bytes_in_buffer; - (void) fill_input_buffer( cinfo ); - /* note we assume that fill_input_buffer will never return FALSE, - * so suspension need not be handled. - */ - } - src->pub.next_input_byte += (size_t) num_bytes; - src->pub.bytes_in_buffer -= (size_t) num_bytes; - } -} - - -/* - * An additional method that can be provided by data source modules is the - * resync_to_restart method for error recovery in the presence of RST markers. - * For the moment, this source module just uses the default resync method - * provided by the JPEG library. That method assumes that no backtracking - * is possible. - */ - - -/* - * Terminate source --- called by jpeg_finish_decompress - * after all data has been read. Often a no-op. - * - * NB: *not* called by jpeg_abort or jpeg_destroy; surrounding - * application must deal with any cleanup that should happen even - * for error exit. - */ - -METHODDEF void -term_source( j_decompress_ptr cinfo ){ - /* no work necessary here */ -} - - -/* - * Prepare for input from a stdio stream. - * The caller must have already opened the stream, and is responsible - * for closing it after finishing decompression. - */ - -GLOBAL void -jpeg_stdio_src( j_decompress_ptr cinfo, unsigned char *infile, int bufsize ){ - my_src_ptr src; - - /* The source object and input buffer are made permanent so that a series - * of JPEG images can be read from the same file by calling jpeg_stdio_src - * only before the first one. (If we discarded the buffer at the end of - * one image, we'd likely lose the start of the next one.) - * This makes it unsafe to use this manager and a different source - * manager serially with the same JPEG object. Caveat programmer. - */ - if ( cinfo->src == NULL ) { /* first time for this JPEG object? */ - cinfo->src = (struct jpeg_source_mgr *) - ( *cinfo->mem->alloc_small )( (j_common_ptr) cinfo, JPOOL_PERMANENT, - SIZEOF( my_source_mgr ) ); - src = (my_src_ptr) cinfo->src; - src->buffer = (JOCTET *) - ( *cinfo->mem->alloc_small )( (j_common_ptr) cinfo, JPOOL_PERMANENT, - INPUT_BUF_SIZE * SIZEOF( JOCTET ) ); - } - - src = (my_src_ptr) cinfo->src; - src->pub.init_source = init_source; - src->pub.fill_input_buffer = fill_input_buffer; - src->pub.skip_input_data = skip_input_data; - src->pub.resync_to_restart = jpeg_resync_to_restart; /* use default method */ - src->pub.term_source = term_source; - src->infile = infile; - src->src_size = bufsize; // FIXME ? merged from Alpha - src->pub.bytes_in_buffer = 0; /* forces fill_input_buffer on first read */ - src->pub.next_input_byte = NULL; /* until buffer loaded */ -} diff --git a/tools/urt/libs/jpeg6/jdcoefct.cpp b/tools/urt/libs/jpeg6/jdcoefct.cpp deleted file mode 100644 index 1470a3d..0000000 --- a/tools/urt/libs/jpeg6/jdcoefct.cpp +++ /dev/null @@ -1,1474 +0,0 @@ -/* - - * jdcoefct.c - - * - - * Copyright (C) 1994-1995, Thomas G. Lane. - - * This file is part of the Independent JPEG Group's software. - - * For conditions of distribution and use, see the accompanying README file. - - * - - * This file contains the coefficient buffer controller for decompression. - - * This controller is the top level of the JPEG decompressor proper. - - * The coefficient buffer lies between entropy decoding and inverse-DCT steps. - - * - - * In buffered-image mode, this controller is the interface between - - * input-oriented processing and output-oriented processing. - - * Also, the input side (only) is used when reading a file for transcoding. - - */ - - - -#define JPEG_INTERNALS - -#include "jinclude.h" - -#include "radiant_jpeglib.h" - - - -/* Block smoothing is only applicable for progressive JPEG, so: */ - -#ifndef D_PROGRESSIVE_SUPPORTED - -#undef BLOCK_SMOOTHING_SUPPORTED - -#endif - - - -/* Private buffer controller object */ - - - -typedef struct { - - struct jpeg_d_coef_controller pub; /* public fields */ - - - - /* These variables keep track of the current location of the input side. */ - - /* cinfo->input_iMCU_row is also used for this. */ - - JDIMENSION MCU_ctr; /* counts MCUs processed in current row */ - - int MCU_vert_offset; /* counts MCU rows within iMCU row */ - - int MCU_rows_per_iMCU_row; /* number of such rows needed */ - - - - /* The output side's location is represented by cinfo->output_iMCU_row. */ - - - - /* In single-pass modes, it's sufficient to buffer just one MCU. - - * We allocate a workspace of D_MAX_BLOCKS_IN_MCU coefficient blocks, - - * and let the entropy decoder write into that workspace each time. - - * (On 80x86, the workspace is FAR even though it's not really very big; - - * this is to keep the module interfaces unchanged when a large coefficient - - * buffer is necessary.) - - * In multi-pass modes, this array points to the current MCU's blocks - - * within the virtual arrays; it is used only by the input side. - - */ - - JBLOCKROW MCU_buffer[D_MAX_BLOCKS_IN_MCU]; - - - -#ifdef D_MULTISCAN_FILES_SUPPORTED - - /* In multi-pass modes, we need a virtual block array for each component. */ - - jvirt_barray_ptr whole_image[MAX_COMPONENTS]; - -#endif - - - -#ifdef BLOCK_SMOOTHING_SUPPORTED - - /* When doing block smoothing, we latch coefficient Al values here */ - - int * coef_bits_latch; - -#define SAVED_COEFS 6 /* we save coef_bits[0..5] */ - -#endif - -} my_coef_controller; - - - -typedef my_coef_controller * my_coef_ptr; - - - -/* Forward declarations */ - -METHODDEF int decompress_onepass - -JPP( ( j_decompress_ptr cinfo, JSAMPIMAGE output_buf ) ); - -#ifdef D_MULTISCAN_FILES_SUPPORTED - -METHODDEF int decompress_data - -JPP( ( j_decompress_ptr cinfo, JSAMPIMAGE output_buf ) ); - -#endif - -#ifdef BLOCK_SMOOTHING_SUPPORTED - -LOCAL boolean smoothing_ok JPP( (j_decompress_ptr cinfo) ); - -METHODDEF int decompress_smooth_data - -JPP( ( j_decompress_ptr cinfo, JSAMPIMAGE output_buf ) ); - -#endif - - - - - -LOCAL void - -start_iMCU_row( j_decompress_ptr cinfo ){ -/* Reset within-iMCU-row counters for a new row (input side) */ - - my_coef_ptr coef = (my_coef_ptr) cinfo->coef; - - - - /* In an interleaved scan, an MCU row is the same as an iMCU row. - - * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows. - - * But at the bottom of the image, process only what's left. - - */ - - if ( cinfo->comps_in_scan > 1 ) { - - coef->MCU_rows_per_iMCU_row = 1; - - } - else { - - if ( cinfo->input_iMCU_row < ( cinfo->total_iMCU_rows - 1 ) ) { - - coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor; - } - - else{ - - coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height; - } - - } - - - - coef->MCU_ctr = 0; - - coef->MCU_vert_offset = 0; - -} - - - - - -/* - - * Initialize for an input processing pass. - - */ - - - -METHODDEF void - -start_input_pass( j_decompress_ptr cinfo ){ - - cinfo->input_iMCU_row = 0; - - start_iMCU_row( cinfo ); - -} - - - - - -/* - - * Initialize for an output processing pass. - - */ - - - -METHODDEF void - -start_output_pass( j_decompress_ptr cinfo ){ - -#ifdef BLOCK_SMOOTHING_SUPPORTED - - my_coef_ptr coef = (my_coef_ptr) cinfo->coef; - - - - /* If multipass, check to see whether to use block smoothing on this pass */ - - if ( coef->pub.coef_arrays != NULL ) { - - if ( cinfo->do_block_smoothing && smoothing_ok( cinfo ) ) { - - coef->pub.decompress_data = decompress_smooth_data; - } - - else{ - - coef->pub.decompress_data = decompress_data; - } - - } - -#endif - - cinfo->output_iMCU_row = 0; - -} - - - - - -/* - - * Decompress and return some data in the single-pass case. - - * Always attempts to emit one fully interleaved MCU row ("iMCU" row). - - * Input and output must run in lockstep since we have only a one-MCU buffer. - - * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED. - - * - - * NB: output_buf contains a plane for each component in image. - - * For single pass, this is the same as the components in the scan. - - */ - - - -METHODDEF int - -decompress_onepass( j_decompress_ptr cinfo, JSAMPIMAGE output_buf ){ - - my_coef_ptr coef = (my_coef_ptr) cinfo->coef; - - JDIMENSION MCU_col_num; /* index of current MCU within row */ - - JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1; - - JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1; - - int blkn, ci, xindex, yindex, yoffset, useful_width; - - JSAMPARRAY output_ptr; - - JDIMENSION start_col, output_col; - - jpeg_component_info *compptr; - - inverse_DCT_method_ptr inverse_DCT; - - - - /* Loop to process as much as one whole iMCU row */ - - for ( yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row; - - yoffset++ ) { - - for ( MCU_col_num = coef->MCU_ctr; MCU_col_num <= last_MCU_col; - - MCU_col_num++ ) { - - /* Try to fetch an MCU. Entropy decoder expects buffer to be zeroed. */ - - jzero_far( (void FAR *) coef->MCU_buffer[0], - - (size_t) ( cinfo->blocks_in_MCU * SIZEOF( JBLOCK ) ) ); - - if ( !( *cinfo->entropy->decode_mcu )( cinfo, coef->MCU_buffer ) ) { - - /* Suspension forced; update state counters and exit */ - - coef->MCU_vert_offset = yoffset; - - coef->MCU_ctr = MCU_col_num; - - return JPEG_SUSPENDED; - - } - - /* Determine where data should go in output_buf and do the IDCT thing. - - * We skip dummy blocks at the right and bottom edges (but blkn gets - - * incremented past them!). Note the inner loop relies on having - - * allocated the MCU_buffer[] blocks sequentially. - - */ - - blkn = 0; /* index of current DCT block within MCU */ - - for ( ci = 0; ci < cinfo->comps_in_scan; ci++ ) { - - compptr = cinfo->cur_comp_info[ci]; - - /* Don't bother to IDCT an uninteresting component. */ - - if ( !compptr->component_needed ) { - - blkn += compptr->MCU_blocks; - - continue; - - } - - inverse_DCT = cinfo->idct->inverse_DCT[compptr->component_index]; - - useful_width = ( MCU_col_num < last_MCU_col ) ? compptr->MCU_width - - : compptr->last_col_width; - - output_ptr = output_buf[ci] + yoffset * compptr->DCT_scaled_size; - - start_col = MCU_col_num * compptr->MCU_sample_width; - - for ( yindex = 0; yindex < compptr->MCU_height; yindex++ ) { - - if ( cinfo->input_iMCU_row < last_iMCU_row || - - yoffset + yindex < compptr->last_row_height ) { - - output_col = start_col; - - for ( xindex = 0; xindex < useful_width; xindex++ ) { - - ( *inverse_DCT )( cinfo, compptr, - - (JCOEFPTR) coef->MCU_buffer[blkn + xindex], - - output_ptr, output_col ); - - output_col += compptr->DCT_scaled_size; - - } - - } - - blkn += compptr->MCU_width; - - output_ptr += compptr->DCT_scaled_size; - - } - - } - - } - - /* Completed an MCU row, but perhaps not an iMCU row */ - - coef->MCU_ctr = 0; - - } - - /* Completed the iMCU row, advance counters for next one */ - - cinfo->output_iMCU_row++; - - if ( ++( cinfo->input_iMCU_row ) < cinfo->total_iMCU_rows ) { - - start_iMCU_row( cinfo ); - - return JPEG_ROW_COMPLETED; - - } - - /* Completed the scan */ - - ( *cinfo->inputctl->finish_input_pass )( cinfo ); - - return JPEG_SCAN_COMPLETED; - -} - - - - - -/* - - * Dummy consume-input routine for single-pass operation. - - */ - - - -METHODDEF int - -dummy_consume_data( j_decompress_ptr cinfo ){ - - return JPEG_SUSPENDED; /* Always indicate nothing was done */ - -} - - - - - -#ifdef D_MULTISCAN_FILES_SUPPORTED - - - -/* - - * Consume input data and store it in the full-image coefficient buffer. - - * We read as much as one fully interleaved MCU row ("iMCU" row) per call, - - * ie, v_samp_factor block rows for each component in the scan. - - * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED. - - */ - - - -METHODDEF int - -consume_data( j_decompress_ptr cinfo ){ - - my_coef_ptr coef = (my_coef_ptr) cinfo->coef; - - JDIMENSION MCU_col_num; /* index of current MCU within row */ - - int blkn, ci, xindex, yindex, yoffset; - - JDIMENSION start_col; - - JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN]; - - JBLOCKROW buffer_ptr; - - jpeg_component_info *compptr; - - - - /* Align the virtual buffers for the components used in this scan. */ - - for ( ci = 0; ci < cinfo->comps_in_scan; ci++ ) { - - compptr = cinfo->cur_comp_info[ci]; - - buffer[ci] = ( *cinfo->mem->access_virt_barray ) - - ( (j_common_ptr) cinfo, coef->whole_image[compptr->component_index], - - cinfo->input_iMCU_row * compptr->v_samp_factor, - - (JDIMENSION) compptr->v_samp_factor, TRUE ); - - /* Note: entropy decoder expects buffer to be zeroed, - - * but this is handled automatically by the memory manager - - * because we requested a pre-zeroed array. - - */ - - } - - - - /* Loop to process one whole iMCU row */ - - for ( yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row; - - yoffset++ ) { - - for ( MCU_col_num = coef->MCU_ctr; MCU_col_num < cinfo->MCUs_per_row; - - MCU_col_num++ ) { - - /* Construct list of pointers to DCT blocks belonging to this MCU */ - - blkn = 0; /* index of current DCT block within MCU */ - - for ( ci = 0; ci < cinfo->comps_in_scan; ci++ ) { - - compptr = cinfo->cur_comp_info[ci]; - - start_col = MCU_col_num * compptr->MCU_width; - - for ( yindex = 0; yindex < compptr->MCU_height; yindex++ ) { - - buffer_ptr = buffer[ci][yindex + yoffset] + start_col; - - for ( xindex = 0; xindex < compptr->MCU_width; xindex++ ) { - - coef->MCU_buffer[blkn++] = buffer_ptr++; - - } - - } - - } - - /* Try to fetch the MCU. */ - - if ( !( *cinfo->entropy->decode_mcu )( cinfo, coef->MCU_buffer ) ) { - - /* Suspension forced; update state counters and exit */ - - coef->MCU_vert_offset = yoffset; - - coef->MCU_ctr = MCU_col_num; - - return JPEG_SUSPENDED; - - } - - } - - /* Completed an MCU row, but perhaps not an iMCU row */ - - coef->MCU_ctr = 0; - - } - - /* Completed the iMCU row, advance counters for next one */ - - if ( ++( cinfo->input_iMCU_row ) < cinfo->total_iMCU_rows ) { - - start_iMCU_row( cinfo ); - - return JPEG_ROW_COMPLETED; - - } - - /* Completed the scan */ - - ( *cinfo->inputctl->finish_input_pass )( cinfo ); - - return JPEG_SCAN_COMPLETED; - -} - - - - - -/* - - * Decompress and return some data in the multi-pass case. - - * Always attempts to emit one fully interleaved MCU row ("iMCU" row). - - * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED. - - * - - * NB: output_buf contains a plane for each component in image. - - */ - - - -METHODDEF int - -decompress_data( j_decompress_ptr cinfo, JSAMPIMAGE output_buf ){ - - my_coef_ptr coef = (my_coef_ptr) cinfo->coef; - - JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1; - - JDIMENSION block_num; - - int ci, block_row, block_rows; - - JBLOCKARRAY buffer; - - JBLOCKROW buffer_ptr; - - JSAMPARRAY output_ptr; - - JDIMENSION output_col; - - jpeg_component_info *compptr; - - inverse_DCT_method_ptr inverse_DCT; - - - - /* Force some input to be done if we are getting ahead of the input. */ - - while ( cinfo->input_scan_number < cinfo->output_scan_number || - - ( cinfo->input_scan_number == cinfo->output_scan_number && - - cinfo->input_iMCU_row <= cinfo->output_iMCU_row ) ) { - - if ( ( *cinfo->inputctl->consume_input )( cinfo ) == JPEG_SUSPENDED ) { - - return JPEG_SUSPENDED; - } - - } - - - - /* OK, output from the virtual arrays. */ - - for ( ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components; - - ci++, compptr++ ) { - - /* Don't bother to IDCT an uninteresting component. */ - - if ( !compptr->component_needed ) { - - continue; - } - - /* Align the virtual buffer for this component. */ - - buffer = ( *cinfo->mem->access_virt_barray ) - - ( (j_common_ptr) cinfo, coef->whole_image[ci], - - cinfo->output_iMCU_row * compptr->v_samp_factor, - - (JDIMENSION) compptr->v_samp_factor, FALSE ); - - /* Count non-dummy DCT block rows in this iMCU row. */ - - if ( cinfo->output_iMCU_row < last_iMCU_row ) { - - block_rows = compptr->v_samp_factor; - } - - else { - - /* NB: can't use last_row_height here; it is input-side-dependent! */ - - block_rows = (int) ( compptr->height_in_blocks % compptr->v_samp_factor ); - - if ( block_rows == 0 ) { - block_rows = compptr->v_samp_factor; - } - - } - - inverse_DCT = cinfo->idct->inverse_DCT[ci]; - - output_ptr = output_buf[ci]; - - /* Loop over all DCT blocks to be processed. */ - - for ( block_row = 0; block_row < block_rows; block_row++ ) { - - buffer_ptr = buffer[block_row]; - - output_col = 0; - - for ( block_num = 0; block_num < compptr->width_in_blocks; block_num++ ) { - - ( *inverse_DCT )( cinfo, compptr, (JCOEFPTR) buffer_ptr, - - output_ptr, output_col ); - - buffer_ptr++; - - output_col += compptr->DCT_scaled_size; - - } - - output_ptr += compptr->DCT_scaled_size; - - } - - } - - - - if ( ++( cinfo->output_iMCU_row ) < cinfo->total_iMCU_rows ) { - - return JPEG_ROW_COMPLETED; - } - - return JPEG_SCAN_COMPLETED; - -} - - - -#endif /* D_MULTISCAN_FILES_SUPPORTED */ - - - - - -#ifdef BLOCK_SMOOTHING_SUPPORTED - - - -/* - - * This code applies interblock smoothing as described by section K.8 - - * of the JPEG standard: the first 5 AC coefficients are estimated from - - * the DC values of a DCT block and its 8 neighboring blocks. - - * We apply smoothing only for progressive JPEG decoding, and only if - - * the coefficients it can estimate are not yet known to full precision. - - */ - - - -/* - - * Determine whether block smoothing is applicable and safe. - - * We also latch the current states of the coef_bits[] entries for the - - * AC coefficients; otherwise, if the input side of the decompressor - - * advances into a new scan, we might think the coefficients are known - - * more accurately than they really are. - - */ - - - -LOCAL boolean - -smoothing_ok( j_decompress_ptr cinfo ){ - - my_coef_ptr coef = (my_coef_ptr) cinfo->coef; - - boolean smoothing_useful = FALSE; - - int ci, coefi; - - jpeg_component_info *compptr; - - JQUANT_TBL * qtable; - - int * coef_bits; - - int * coef_bits_latch; - - - - if ( !cinfo->progressive_mode || cinfo->coef_bits == NULL ) { - - return FALSE; - } - - - - /* Allocate latch area if not already done */ - - if ( coef->coef_bits_latch == NULL ) { - - coef->coef_bits_latch = (int *) - - ( *cinfo->mem->alloc_small )( (j_common_ptr) cinfo, JPOOL_IMAGE, - - cinfo->num_components * - - ( SAVED_COEFS * SIZEOF( int ) ) ); - } - - coef_bits_latch = coef->coef_bits_latch; - - - - for ( ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components; - - ci++, compptr++ ) { - - /* All components' quantization values must already be latched. */ - - if ( ( qtable = compptr->quant_table ) == NULL ) { - - return FALSE; - } - - /* Verify DC & first 5 AC quantizers are nonzero to avoid zero-divide. */ - - for ( coefi = 0; coefi <= 5; coefi++ ) { - - if ( qtable->quantval[coefi] == 0 ) { - - return FALSE; - } - - } - - /* DC values must be at least partly known for all components. */ - - coef_bits = cinfo->coef_bits[ci]; - - if ( coef_bits[0] < 0 ) { - - return FALSE; - } - - /* Block smoothing is helpful if some AC coefficients remain inaccurate. */ - - for ( coefi = 1; coefi <= 5; coefi++ ) { - - coef_bits_latch[coefi] = coef_bits[coefi]; - - if ( coef_bits[coefi] != 0 ) { - - smoothing_useful = TRUE; - } - - } - - coef_bits_latch += SAVED_COEFS; - - } - - - - return smoothing_useful; - -} - - - - - -/* - - * Variant of decompress_data for use when doing block smoothing. - - */ - - - -METHODDEF int - -decompress_smooth_data( j_decompress_ptr cinfo, JSAMPIMAGE output_buf ){ - - my_coef_ptr coef = (my_coef_ptr) cinfo->coef; - - JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1; - - JDIMENSION block_num, last_block_column; - - int ci, block_row, block_rows, access_rows; - - JBLOCKARRAY buffer; - - JBLOCKROW buffer_ptr, prev_block_row, next_block_row; - - JSAMPARRAY output_ptr; - - JDIMENSION output_col; - - jpeg_component_info *compptr; - - inverse_DCT_method_ptr inverse_DCT; - - boolean first_row, last_row; - - JBLOCK workspace; - - int *coef_bits; - - JQUANT_TBL *quanttbl; - - INT32 Q00,Q01,Q02,Q10,Q11,Q20, num; - - int DC1,DC2,DC3,DC4,DC5,DC6,DC7,DC8,DC9; - - int Al, pred; - - - - /* Force some input to be done if we are getting ahead of the input. */ - - while ( cinfo->input_scan_number <= cinfo->output_scan_number && - - !cinfo->inputctl->eoi_reached ) { - - if ( cinfo->input_scan_number == cinfo->output_scan_number ) { - - /* If input is working on current scan, we ordinarily want it to - - * have completed the current row. But if input scan is DC, - - * we want it to keep one row ahead so that next block row's DC - - * values are up to date. - - */ - - JDIMENSION delta = ( cinfo->Ss == 0 ) ? 1 : 0; - - if ( cinfo->input_iMCU_row > cinfo->output_iMCU_row + delta ) { - - break; - } - - } - - if ( ( *cinfo->inputctl->consume_input )( cinfo ) == JPEG_SUSPENDED ) { - - return JPEG_SUSPENDED; - } - - } - - - - /* OK, output from the virtual arrays. */ - - for ( ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components; - - ci++, compptr++ ) { - - /* Don't bother to IDCT an uninteresting component. */ - - if ( !compptr->component_needed ) { - - continue; - } - - /* Count non-dummy DCT block rows in this iMCU row. */ - - if ( cinfo->output_iMCU_row < last_iMCU_row ) { - - block_rows = compptr->v_samp_factor; - - access_rows = block_rows * 2; /* this and next iMCU row */ - - last_row = FALSE; - - } - else { - - /* NB: can't use last_row_height here; it is input-side-dependent! */ - - block_rows = (int) ( compptr->height_in_blocks % compptr->v_samp_factor ); - - if ( block_rows == 0 ) { - block_rows = compptr->v_samp_factor; - } - - access_rows = block_rows; /* this iMCU row only */ - - last_row = TRUE; - - } - - /* Align the virtual buffer for this component. */ - - if ( cinfo->output_iMCU_row > 0 ) { - - access_rows += compptr->v_samp_factor; /* prior iMCU row too */ - - buffer = ( *cinfo->mem->access_virt_barray ) - - ( (j_common_ptr) cinfo, coef->whole_image[ci], - - ( cinfo->output_iMCU_row - 1 ) * compptr->v_samp_factor, - - (JDIMENSION) access_rows, FALSE ); - - buffer += compptr->v_samp_factor; /* point to current iMCU row */ - - first_row = FALSE; - - } - else { - - buffer = ( *cinfo->mem->access_virt_barray ) - - ( (j_common_ptr) cinfo, coef->whole_image[ci], - - (JDIMENSION) 0, (JDIMENSION) access_rows, FALSE ); - - first_row = TRUE; - - } - - /* Fetch component-dependent info */ - - coef_bits = coef->coef_bits_latch + ( ci * SAVED_COEFS ); - - quanttbl = compptr->quant_table; - - Q00 = quanttbl->quantval[0]; - - Q01 = quanttbl->quantval[1]; - - Q10 = quanttbl->quantval[2]; - - Q20 = quanttbl->quantval[3]; - - Q11 = quanttbl->quantval[4]; - - Q02 = quanttbl->quantval[5]; - - inverse_DCT = cinfo->idct->inverse_DCT[ci]; - - output_ptr = output_buf[ci]; - - /* Loop over all DCT blocks to be processed. */ - - for ( block_row = 0; block_row < block_rows; block_row++ ) { - - buffer_ptr = buffer[block_row]; - - if ( first_row && block_row == 0 ) { - - prev_block_row = buffer_ptr; - } - - else{ - - prev_block_row = buffer[block_row - 1]; - } - - if ( last_row && block_row == block_rows - 1 ) { - - next_block_row = buffer_ptr; - } - - else{ - - next_block_row = buffer[block_row + 1]; - } - - /* We fetch the surrounding DC values using a sliding-register approach. - - * Initialize all nine here so as to do the right thing on narrow pics. - - */ - - DC1 = DC2 = DC3 = (int) prev_block_row[0][0]; - - DC4 = DC5 = DC6 = (int) buffer_ptr[0][0]; - - DC7 = DC8 = DC9 = (int) next_block_row[0][0]; - - output_col = 0; - - last_block_column = compptr->width_in_blocks - 1; - - for ( block_num = 0; block_num <= last_block_column; block_num++ ) { - - /* Fetch current DCT block into workspace so we can modify it. */ - - jcopy_block_row( buffer_ptr, (JBLOCKROW) workspace, (JDIMENSION) 1 ); - - /* Update DC values */ - - if ( block_num < last_block_column ) { - - DC3 = (int) prev_block_row[1][0]; - - DC6 = (int) buffer_ptr[1][0]; - - DC9 = (int) next_block_row[1][0]; - - } - - /* Compute coefficient estimates per K.8. - - * An estimate is applied only if coefficient is still zero, - - * and is not known to be fully accurate. - - */ - - /* AC01 */ - - if ( ( Al = coef_bits[1] ) != 0 && workspace[1] == 0 ) { - - num = 36 * Q00 * ( DC4 - DC6 ); - - if ( num >= 0 ) { - - pred = (int) ( ( ( Q01 << 7 ) + num ) / ( Q01 << 8 ) ); - - if ( Al > 0 && pred >= ( 1 << Al ) ) { - - pred = ( 1 << Al ) - 1; - } - - } - else { - - pred = (int) ( ( ( Q01 << 7 ) - num ) / ( Q01 << 8 ) ); - - if ( Al > 0 && pred >= ( 1 << Al ) ) { - - pred = ( 1 << Al ) - 1; - } - - pred = -pred; - - } - - workspace[1] = (JCOEF) pred; - - } - - /* AC10 */ - - if ( ( Al = coef_bits[2] ) != 0 && workspace[8] == 0 ) { - - num = 36 * Q00 * ( DC2 - DC8 ); - - if ( num >= 0 ) { - - pred = (int) ( ( ( Q10 << 7 ) + num ) / ( Q10 << 8 ) ); - - if ( Al > 0 && pred >= ( 1 << Al ) ) { - - pred = ( 1 << Al ) - 1; - } - - } - else { - - pred = (int) ( ( ( Q10 << 7 ) - num ) / ( Q10 << 8 ) ); - - if ( Al > 0 && pred >= ( 1 << Al ) ) { - - pred = ( 1 << Al ) - 1; - } - - pred = -pred; - - } - - workspace[8] = (JCOEF) pred; - - } - - /* AC20 */ - - if ( ( Al = coef_bits[3] ) != 0 && workspace[16] == 0 ) { - - num = 9 * Q00 * ( DC2 + DC8 - 2 * DC5 ); - - if ( num >= 0 ) { - - pred = (int) ( ( ( Q20 << 7 ) + num ) / ( Q20 << 8 ) ); - - if ( Al > 0 && pred >= ( 1 << Al ) ) { - - pred = ( 1 << Al ) - 1; - } - - } - else { - - pred = (int) ( ( ( Q20 << 7 ) - num ) / ( Q20 << 8 ) ); - - if ( Al > 0 && pred >= ( 1 << Al ) ) { - - pred = ( 1 << Al ) - 1; - } - - pred = -pred; - - } - - workspace[16] = (JCOEF) pred; - - } - - /* AC11 */ - - if ( ( Al = coef_bits[4] ) != 0 && workspace[9] == 0 ) { - - num = 5 * Q00 * ( DC1 - DC3 - DC7 + DC9 ); - - if ( num >= 0 ) { - - pred = (int) ( ( ( Q11 << 7 ) + num ) / ( Q11 << 8 ) ); - - if ( Al > 0 && pred >= ( 1 << Al ) ) { - - pred = ( 1 << Al ) - 1; - } - - } - else { - - pred = (int) ( ( ( Q11 << 7 ) - num ) / ( Q11 << 8 ) ); - - if ( Al > 0 && pred >= ( 1 << Al ) ) { - - pred = ( 1 << Al ) - 1; - } - - pred = -pred; - - } - - workspace[9] = (JCOEF) pred; - - } - - /* AC02 */ - - if ( ( Al = coef_bits[5] ) != 0 && workspace[2] == 0 ) { - - num = 9 * Q00 * ( DC4 + DC6 - 2 * DC5 ); - - if ( num >= 0 ) { - - pred = (int) ( ( ( Q02 << 7 ) + num ) / ( Q02 << 8 ) ); - - if ( Al > 0 && pred >= ( 1 << Al ) ) { - - pred = ( 1 << Al ) - 1; - } - - } - else { - - pred = (int) ( ( ( Q02 << 7 ) - num ) / ( Q02 << 8 ) ); - - if ( Al > 0 && pred >= ( 1 << Al ) ) { - - pred = ( 1 << Al ) - 1; - } - - pred = -pred; - - } - - workspace[2] = (JCOEF) pred; - - } - - /* OK, do the IDCT */ - - ( *inverse_DCT )( cinfo, compptr, (JCOEFPTR) workspace, - - output_ptr, output_col ); - - /* Advance for next column */ - - DC1 = DC2; DC2 = DC3; - - DC4 = DC5; DC5 = DC6; - - DC7 = DC8; DC8 = DC9; - - buffer_ptr++, prev_block_row++, next_block_row++; - - output_col += compptr->DCT_scaled_size; - - } - - output_ptr += compptr->DCT_scaled_size; - - } - - } - - - - if ( ++( cinfo->output_iMCU_row ) < cinfo->total_iMCU_rows ) { - - return JPEG_ROW_COMPLETED; - } - - return JPEG_SCAN_COMPLETED; - -} - - - -#endif /* BLOCK_SMOOTHING_SUPPORTED */ - - - - - -/* - - * Initialize coefficient buffer controller. - - */ - - - -GLOBAL void - -jinit_d_coef_controller( j_decompress_ptr cinfo, boolean need_full_buffer ){ - - my_coef_ptr coef; - - - - coef = (my_coef_ptr) - - ( *cinfo->mem->alloc_small )( (j_common_ptr) cinfo, JPOOL_IMAGE, - - SIZEOF( my_coef_controller ) ); - - cinfo->coef = (struct jpeg_d_coef_controller *) coef; - - coef->pub.start_input_pass = start_input_pass; - - coef->pub.start_output_pass = start_output_pass; - -#ifdef BLOCK_SMOOTHING_SUPPORTED - - coef->coef_bits_latch = NULL; - -#endif - - - - /* Create the coefficient buffer. */ - - if ( need_full_buffer ) { - -#ifdef D_MULTISCAN_FILES_SUPPORTED - - /* Allocate a full-image virtual array for each component, */ - - /* padded to a multiple of samp_factor DCT blocks in each direction. */ - - /* Note we ask for a pre-zeroed array. */ - - int ci, access_rows; - - jpeg_component_info *compptr; - - - - for ( ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components; - - ci++, compptr++ ) { - - access_rows = compptr->v_samp_factor; - -#ifdef BLOCK_SMOOTHING_SUPPORTED - - /* If block smoothing could be used, need a bigger window */ - - if ( cinfo->progressive_mode ) { - - access_rows *= 3; - } - -#endif - - coef->whole_image[ci] = ( *cinfo->mem->request_virt_barray ) - - ( (j_common_ptr) cinfo, JPOOL_IMAGE, TRUE, - - (JDIMENSION) jround_up( (long) compptr->width_in_blocks, - - (long) compptr->h_samp_factor ), - - (JDIMENSION) jround_up( (long) compptr->height_in_blocks, - - (long) compptr->v_samp_factor ), - - (JDIMENSION) access_rows ); - - } - - coef->pub.consume_data = consume_data; - - coef->pub.decompress_data = decompress_data; - - coef->pub.coef_arrays = coef->whole_image; /* link to virtual arrays */ - -#else - - ERREXIT( cinfo, JERR_NOT_COMPILED ); - -#endif - - } - else { - - /* We only need a single-MCU buffer. */ - - JBLOCKROW buffer; - - int i; - - - - buffer = (JBLOCKROW) - - ( *cinfo->mem->alloc_large )( (j_common_ptr) cinfo, JPOOL_IMAGE, - - D_MAX_BLOCKS_IN_MCU * SIZEOF( JBLOCK ) ); - - for ( i = 0; i < D_MAX_BLOCKS_IN_MCU; i++ ) { - - coef->MCU_buffer[i] = buffer + i; - - } - - coef->pub.consume_data = dummy_consume_data; - - coef->pub.decompress_data = decompress_onepass; - - coef->pub.coef_arrays = NULL; /* flag for no virtual arrays */ - - } - -} diff --git a/tools/urt/libs/jpeg6/jdcolor.cpp b/tools/urt/libs/jpeg6/jdcolor.cpp deleted file mode 100644 index 3423fc6..0000000 --- a/tools/urt/libs/jpeg6/jdcolor.cpp +++ /dev/null @@ -1,735 +0,0 @@ -/* - - * jdcolor.c - - * - - * Copyright (C) 1991-1995, Thomas G. Lane. - - * This file is part of the Independent JPEG Group's software. - - * For conditions of distribution and use, see the accompanying README file. - - * - - * This file contains output colorspace conversion routines. - - */ - - - -#define JPEG_INTERNALS - -#include "jinclude.h" - -#include "radiant_jpeglib.h" - - - - - -/* Private subobject */ - - - -typedef struct { - - struct jpeg_color_deconverter pub; /* public fields */ - - - - /* Private state for YCC->RGB conversion */ - - int * Cr_r_tab; /* => table for Cr to R conversion */ - - int * Cb_b_tab; /* => table for Cb to B conversion */ - - INT32 * Cr_g_tab; /* => table for Cr to G conversion */ - - INT32 * Cb_g_tab; /* => table for Cb to G conversion */ - -} my_color_deconverter; - - - -typedef my_color_deconverter * my_cconvert_ptr; - - - - - -/**************** YCbCr -> RGB conversion: most common case **************/ - - - -/* - - * YCbCr is defined per CCIR 601-1, except that Cb and Cr are - - * normalized to the range 0..MAXJSAMPLE rather than -0.5 .. 0.5. - - * The conversion equations to be implemented are therefore - - * R = Y + 1.40200 * Cr - - * G = Y - 0.34414 * Cb - 0.71414 * Cr - - * B = Y + 1.77200 * Cb - - * where Cb and Cr represent the incoming values less CENTERJSAMPLE. - - * (These numbers are derived from TIFF 6.0 section 21, dated 3-June-92.) - - * - - * To avoid floating-point arithmetic, we represent the fractional constants - - * as integers scaled up by 2^16 (about 4 digits precision); we have to divide - - * the products by 2^16, with appropriate rounding, to get the correct answer. - - * Notice that Y, being an integral input, does not contribute any fraction - - * so it need not participate in the rounding. - - * - - * For even more speed, we avoid doing any multiplications in the inner loop - - * by precalculating the constants times Cb and Cr for all possible values. - - * For 8-bit JSAMPLEs this is very reasonable (only 256 entries per table); - - * for 12-bit samples it is still acceptable. It's not very reasonable for - - * 16-bit samples, but if you want lossless storage you shouldn't be changing - - * colorspace anyway. - - * The Cr=>R and Cb=>B values can be rounded to integers in advance; the - - * values for the G calculation are left scaled up, since we must add them - - * together before rounding. - - */ - - - -#define SCALEBITS 16 /* speediest right-shift on some machines */ - -#define ONE_HALF ( (INT32) 1 << ( SCALEBITS - 1 ) ) - -#define FIX( x ) ( (INT32) ( ( x ) * ( 1L << SCALEBITS ) + 0.5 ) ) - - - - - -/* - - * Initialize tables for YCC->RGB colorspace conversion. - - */ - - - -LOCAL void - -build_ycc_rgb_table( j_decompress_ptr cinfo ){ - - my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert; - - int i; - - INT32 x; - - SHIFT_TEMPS - - - - cconvert->Cr_r_tab = (int *) - - ( *cinfo->mem->alloc_small )( (j_common_ptr) cinfo, JPOOL_IMAGE, - - ( MAXJSAMPLE + 1 ) * SIZEOF( int ) ); - - cconvert->Cb_b_tab = (int *) - - ( *cinfo->mem->alloc_small )( (j_common_ptr) cinfo, JPOOL_IMAGE, - - ( MAXJSAMPLE + 1 ) * SIZEOF( int ) ); - - cconvert->Cr_g_tab = (INT32 *) - - ( *cinfo->mem->alloc_small )( (j_common_ptr) cinfo, JPOOL_IMAGE, - - ( MAXJSAMPLE + 1 ) * SIZEOF( INT32 ) ); - - cconvert->Cb_g_tab = (INT32 *) - - ( *cinfo->mem->alloc_small )( (j_common_ptr) cinfo, JPOOL_IMAGE, - - ( MAXJSAMPLE + 1 ) * SIZEOF( INT32 ) ); - - - - for ( i = 0, x = -CENTERJSAMPLE; i <= MAXJSAMPLE; i++, x++ ) { - - /* i is the actual input pixel value, in the range 0..MAXJSAMPLE */ - - /* The Cb or Cr value we are thinking of is x = i - CENTERJSAMPLE */ - - /* Cr=>R value is nearest int to 1.40200 * x */ - - cconvert->Cr_r_tab[i] = (int) - - RIGHT_SHIFT( FIX( 1.40200 ) * x + ONE_HALF, SCALEBITS ); - - /* Cb=>B value is nearest int to 1.77200 * x */ - - cconvert->Cb_b_tab[i] = (int) - - RIGHT_SHIFT( FIX( 1.77200 ) * x + ONE_HALF, SCALEBITS ); - - /* Cr=>G value is scaled-up -0.71414 * x */ - - cconvert->Cr_g_tab[i] = ( -FIX( 0.71414 ) ) * x; - - /* Cb=>G value is scaled-up -0.34414 * x */ - - /* We also add in ONE_HALF so that need not do it in inner loop */ - - cconvert->Cb_g_tab[i] = ( -FIX( 0.34414 ) ) * x + ONE_HALF; - - } - -} - - - - - -/* - - * Convert some rows of samples to the output colorspace. - - * - - * Note that we change from noninterleaved, one-plane-per-component format - - * to interleaved-pixel format. The output buffer is therefore three times - - * as wide as the input buffer. - - * A starting row offset is provided only for the input buffer. The caller - - * can easily adjust the passed output_buf value to accommodate any row - - * offset required on that side. - - */ - - - -METHODDEF void - -ycc_rgb_convert( j_decompress_ptr cinfo, - - JSAMPIMAGE input_buf, JDIMENSION input_row, - - JSAMPARRAY output_buf, int num_rows ){ - - my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert; - - register int y, cb, cr; - - register JSAMPROW outptr; - - register JSAMPROW inptr0, inptr1, inptr2; - - register JDIMENSION col; - - JDIMENSION num_cols = cinfo->output_width; - - /* copy these pointers into registers if possible */ - - register JSAMPLE * range_limit = cinfo->sample_range_limit; - - register int * Crrtab = cconvert->Cr_r_tab; - - register int * Cbbtab = cconvert->Cb_b_tab; - - register INT32 * Crgtab = cconvert->Cr_g_tab; - - register INT32 * Cbgtab = cconvert->Cb_g_tab; - - SHIFT_TEMPS - - - - while ( --num_rows >= 0 ) { - - inptr0 = input_buf[0][input_row]; - - inptr1 = input_buf[1][input_row]; - - inptr2 = input_buf[2][input_row]; - - input_row++; - - outptr = *output_buf++; - - for ( col = 0; col < num_cols; col++ ) { - - y = GETJSAMPLE( inptr0[col] ); - - cb = GETJSAMPLE( inptr1[col] ); - - cr = GETJSAMPLE( inptr2[col] ); - - /* Range-limiting is essential due to noise introduced by DCT losses. */ - - outptr[RGB_RED] = range_limit[y + Crrtab[cr]]; - - outptr[RGB_GREEN] = range_limit[y + - - ( (int) RIGHT_SHIFT( Cbgtab[cb] + Crgtab[cr], - - SCALEBITS ) )]; - - outptr[RGB_BLUE] = range_limit[y + Cbbtab[cb]]; - - outptr += RGB_PIXELSIZE; - - } - - } - -} - - - - - -/**************** Cases other than YCbCr -> RGB **************/ - - - - - -/* - - * Color conversion for no colorspace change: just copy the data, - - * converting from separate-planes to interleaved representation. - - */ - - - -METHODDEF void - -null_convert( j_decompress_ptr cinfo, - - JSAMPIMAGE input_buf, JDIMENSION input_row, - - JSAMPARRAY output_buf, int num_rows ){ - - register JSAMPROW inptr, outptr; - - register JDIMENSION count; - - register int num_components = cinfo->num_components; - - JDIMENSION num_cols = cinfo->output_width; - - int ci; - - - - while ( --num_rows >= 0 ) { - - for ( ci = 0; ci < num_components; ci++ ) { - - inptr = input_buf[ci][input_row]; - - outptr = output_buf[0] + ci; - - for ( count = num_cols; count > 0; count-- ) { - - *outptr = *inptr++; /* needn't bother with GETJSAMPLE() here */ - - outptr += num_components; - - } - - } - - input_row++; - - output_buf++; - - } - -} - - - - - -/* - - * Color conversion for grayscale: just copy the data. - - * This also works for YCbCr -> grayscale conversion, in which - - * we just copy the Y (luminance) component and ignore chrominance. - - */ - - - -METHODDEF void - -grayscale_convert( j_decompress_ptr cinfo, - - JSAMPIMAGE input_buf, JDIMENSION input_row, - - JSAMPARRAY output_buf, int num_rows ){ - - jcopy_sample_rows( input_buf[0], (int) input_row, output_buf, 0, - - num_rows, cinfo->output_width ); - -} - - - - - -/* - - * Adobe-style YCCK->CMYK conversion. - - * We convert YCbCr to R=1-C, G=1-M, and B=1-Y using the same - - * conversion as above, while passing K (black) unchanged. - - * We assume build_ycc_rgb_table has been called. - - */ - - - -METHODDEF void - -ycck_cmyk_convert( j_decompress_ptr cinfo, - - JSAMPIMAGE input_buf, JDIMENSION input_row, - - JSAMPARRAY output_buf, int num_rows ){ - - my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert; - - register int y, cb, cr; - - register JSAMPROW outptr; - - register JSAMPROW inptr0, inptr1, inptr2, inptr3; - - register JDIMENSION col; - - JDIMENSION num_cols = cinfo->output_width; - - /* copy these pointers into registers if possible */ - - register JSAMPLE * range_limit = cinfo->sample_range_limit; - - register int * Crrtab = cconvert->Cr_r_tab; - - register int * Cbbtab = cconvert->Cb_b_tab; - - register INT32 * Crgtab = cconvert->Cr_g_tab; - - register INT32 * Cbgtab = cconvert->Cb_g_tab; - - SHIFT_TEMPS - - - - while ( --num_rows >= 0 ) { - - inptr0 = input_buf[0][input_row]; - - inptr1 = input_buf[1][input_row]; - - inptr2 = input_buf[2][input_row]; - - inptr3 = input_buf[3][input_row]; - - input_row++; - - outptr = *output_buf++; - - for ( col = 0; col < num_cols; col++ ) { - - y = GETJSAMPLE( inptr0[col] ); - - cb = GETJSAMPLE( inptr1[col] ); - - cr = GETJSAMPLE( inptr2[col] ); - - /* Range-limiting is essential due to noise introduced by DCT losses. */ - - outptr[0] = range_limit[MAXJSAMPLE - ( y + Crrtab[cr] )]; /* red */ - - outptr[1] = range_limit[MAXJSAMPLE - ( y + /* green */ - - ( (int) RIGHT_SHIFT( Cbgtab[cb] + Crgtab[cr], - - SCALEBITS ) ) )]; - - outptr[2] = range_limit[MAXJSAMPLE - ( y + Cbbtab[cb] )]; /* blue */ - - /* K passes through unchanged */ - - outptr[3] = inptr3[col]; /* don't need GETJSAMPLE here */ - - outptr += 4; - - } - - } - -} - - - - - -/* - - * Empty method for start_pass. - - */ - - - -METHODDEF void - -start_pass_dcolor( j_decompress_ptr cinfo ){ - - /* no work needed */ - -} - - - - - -/* - - * Module initialization routine for output colorspace conversion. - - */ - - - -GLOBAL void - -jinit_color_deconverter( j_decompress_ptr cinfo ){ - - my_cconvert_ptr cconvert; - - int ci; - - - - cconvert = (my_cconvert_ptr) - - ( *cinfo->mem->alloc_small )( (j_common_ptr) cinfo, JPOOL_IMAGE, - - SIZEOF( my_color_deconverter ) ); - - cinfo->cconvert = (struct jpeg_color_deconverter *) cconvert; - - cconvert->pub.start_pass = start_pass_dcolor; - - - - /* Make sure num_components agrees with jpeg_color_space */ - - switch ( cinfo->jpeg_color_space ) { - - case JCS_GRAYSCALE: - - if ( cinfo->num_components != 1 ) { - - ERREXIT( cinfo, JERR_BAD_J_COLORSPACE ); - } - - break; - - - - case JCS_RGB: - - case JCS_YCbCr: - - if ( cinfo->num_components != 3 ) { - - ERREXIT( cinfo, JERR_BAD_J_COLORSPACE ); - } - - break; - - - - case JCS_CMYK: - - case JCS_YCCK: - - if ( cinfo->num_components != 4 ) { - - ERREXIT( cinfo, JERR_BAD_J_COLORSPACE ); - } - - break; - - - - default: /* JCS_UNKNOWN can be anything */ - - if ( cinfo->num_components < 1 ) { - - ERREXIT( cinfo, JERR_BAD_J_COLORSPACE ); - } - - break; - - } - - - - /* Set out_color_components and conversion method based on requested space. - - * Also clear the component_needed flags for any unused components, - - * so that earlier pipeline stages can avoid useless computation. - - */ - - - - switch ( cinfo->out_color_space ) { - - case JCS_GRAYSCALE: - - cinfo->out_color_components = 1; - - if ( cinfo->jpeg_color_space == JCS_GRAYSCALE || - - cinfo->jpeg_color_space == JCS_YCbCr ) { - - cconvert->pub.color_convert = grayscale_convert; - - /* For color->grayscale conversion, only the Y (0) component is needed */ - - for ( ci = 1; ci < cinfo->num_components; ci++ ) - - cinfo->comp_info[ci].component_needed = FALSE; - - } - else{ - - ERREXIT( cinfo, JERR_CONVERSION_NOTIMPL ); - } - - break; - - - - case JCS_RGB: - - cinfo->out_color_components = RGB_PIXELSIZE; - - if ( cinfo->jpeg_color_space == JCS_YCbCr ) { - - cconvert->pub.color_convert = ycc_rgb_convert; - - build_ycc_rgb_table( cinfo ); - - } - else if ( cinfo->jpeg_color_space == JCS_RGB && RGB_PIXELSIZE == 3 ) { - - cconvert->pub.color_convert = null_convert; - - } - else{ - - ERREXIT( cinfo, JERR_CONVERSION_NOTIMPL ); - } - - break; - - - - case JCS_CMYK: - - cinfo->out_color_components = 4; - - if ( cinfo->jpeg_color_space == JCS_YCCK ) { - - cconvert->pub.color_convert = ycck_cmyk_convert; - - build_ycc_rgb_table( cinfo ); - - } - else if ( cinfo->jpeg_color_space == JCS_CMYK ) { - - cconvert->pub.color_convert = null_convert; - - } - else{ - - ERREXIT( cinfo, JERR_CONVERSION_NOTIMPL ); - } - - break; - - - - default: - - /* Permit null conversion to same output space */ - - if ( cinfo->out_color_space == cinfo->jpeg_color_space ) { - - cinfo->out_color_components = cinfo->num_components; - - cconvert->pub.color_convert = null_convert; - - } - else{ /* unsupported non-null conversion */ - - ERREXIT( cinfo, JERR_CONVERSION_NOTIMPL ); - } - - break; - - } - - - - if ( cinfo->quantize_colors ) { - - cinfo->output_components = 1; /* single colormapped output component */ - - } - else{ - - cinfo->output_components = cinfo->out_color_components; - } - -} diff --git a/tools/urt/libs/jpeg6/jdct.h b/tools/urt/libs/jpeg6/jdct.h deleted file mode 100644 index a460d90..0000000 --- a/tools/urt/libs/jpeg6/jdct.h +++ /dev/null @@ -1,351 +0,0 @@ -/* - - * jdct.h - - * - - * Copyright (C) 1994, Thomas G. Lane. - - * This file is part of the Independent JPEG Group's software. - - * For conditions of distribution and use, see the accompanying README file. - - * - - * This include file contains common declarations for the forward and - - * inverse DCT modules. These declarations are private to the DCT managers - - * (jcdctmgr.c, jddctmgr.c) and the individual DCT algorithms. - - * The individual DCT algorithms are kept in separate files to ease - - * machine-dependent tuning (e.g., assembly coding). - - */ - - - - - -/* - - * A forward DCT routine is given a pointer to a work area of type DCTELEM[]; - - * the DCT is to be performed in-place in that buffer. Type DCTELEM is int - - * for 8-bit samples, INT32 for 12-bit samples. (NOTE: Floating-point DCT - - * implementations use an array of type FAST_FLOAT, instead.) - - * The DCT inputs are expected to be signed (range +-CENTERJSAMPLE). - - * The DCT outputs are returned scaled up by a factor of 8; they therefore - - * have a range of +-8K for 8-bit data, +-128K for 12-bit data. This - - * convention improves accuracy in integer implementations and saves some - - * work in floating-point ones. - - * Quantization of the output coefficients is done by jcdctmgr.c. - - */ - - - -#if BITS_IN_JSAMPLE == 8 - -typedef int DCTELEM; /* 16 or 32 bits is fine */ - -#else - -typedef INT32 DCTELEM; /* must have 32 bits */ - -#endif - - - -typedef JMETHOD ( void, forward_DCT_method_ptr, ( DCTELEM * data ) ); - -typedef JMETHOD ( void, float_DCT_method_ptr, ( FAST_FLOAT * data ) ); - - - - - -/* - - * An inverse DCT routine is given a pointer to the input JBLOCK and a pointer - - * to an output sample array. The routine must dequantize the input data as - - * well as perform the IDCT; for dequantization, it uses the multiplier table - - * pointed to by compptr->dct_table. The output data is to be placed into the - - * sample array starting at a specified column. (Any row offset needed will - - * be applied to the array pointer before it is passed to the IDCT code.) - - * Note that the number of samples emitted by the IDCT routine is - - * DCT_scaled_size * DCT_scaled_size. - - */ - - - -/* typedef inverse_DCT_method_ptr is declared in jpegint.h */ - - - -/* - - * Each IDCT routine has its own ideas about the best dct_table element type. - - */ - - - -typedef MULTIPLIER ISLOW_MULT_TYPE; /* short or int, whichever is faster */ - -#if BITS_IN_JSAMPLE == 8 - -typedef MULTIPLIER IFAST_MULT_TYPE; /* 16 bits is OK, use short if faster */ - -#define IFAST_SCALE_BITS 2 /* fractional bits in scale factors */ - -#else - -typedef INT32 IFAST_MULT_TYPE; /* need 32 bits for scaled quantizers */ - -#define IFAST_SCALE_BITS 13 /* fractional bits in scale factors */ - -#endif - -typedef FAST_FLOAT FLOAT_MULT_TYPE; /* preferred floating type */ - - - - - -/* - - * Each IDCT routine is responsible for range-limiting its results and - - * converting them to unsigned form (0..MAXJSAMPLE). The raw outputs could - - * be quite far out of range if the input data is corrupt, so a bulletproof - - * range-limiting step is required. We use a mask-and-table-lookup method - - * to do the combined operations quickly. See the comments with - - * prepare_range_limit_table (in jdmaster.c) for more info. - - */ - - - -#define IDCT_range_limit( cinfo ) ( ( cinfo )->sample_range_limit + CENTERJSAMPLE ) - - - -#define RANGE_MASK ( MAXJSAMPLE * 4 + 3 ) /* 2 bits wider than legal samples */ - - - - - -/* Short forms of external names for systems with brain-damaged linkers. */ - - - -#ifdef NEED_SHORT_EXTERNAL_NAMES - -#define jpeg_fdct_islow jFDislow - -#define jpeg_fdct_ifast jFDifast - -#define jpeg_fdct_float jFDfloat - -#define jpeg_idct_islow jRDislow - -#define jpeg_idct_ifast jRDifast - -#define jpeg_idct_float jRDfloat - -#define jpeg_idct_4x4 jRD4x4 - -#define jpeg_idct_2x2 jRD2x2 - -#define jpeg_idct_1x1 jRD1x1 - -#endif /* NEED_SHORT_EXTERNAL_NAMES */ - - - -/* Extern declarations for the forward and inverse DCT routines. */ - - - -EXTERN void jpeg_fdct_islow JPP( ( DCTELEM * data ) ); - -EXTERN void jpeg_fdct_ifast JPP( ( DCTELEM * data ) ); - -EXTERN void jpeg_fdct_float JPP( ( FAST_FLOAT * data ) ); - - - -EXTERN void jpeg_idct_islow - -JPP( ( j_decompress_ptr cinfo, jpeg_component_info * compptr, - - JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col ) ); - -EXTERN void jpeg_idct_ifast - -JPP( ( j_decompress_ptr cinfo, jpeg_component_info * compptr, - - JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col ) ); - -EXTERN void jpeg_idct_float - -JPP( ( j_decompress_ptr cinfo, jpeg_component_info * compptr, - - JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col ) ); - -EXTERN void jpeg_idct_4x4 - -JPP( ( j_decompress_ptr cinfo, jpeg_component_info * compptr, - - JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col ) ); - -EXTERN void jpeg_idct_2x2 - -JPP( ( j_decompress_ptr cinfo, jpeg_component_info * compptr, - - JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col ) ); - -EXTERN void jpeg_idct_1x1 - -JPP( ( j_decompress_ptr cinfo, jpeg_component_info * compptr, - - JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col ) ); - - - - - -/* - - * Macros for handling fixed-point arithmetic; these are used by many - - * but not all of the DCT/IDCT modules. - - * - - * All values are expected to be of type INT32. - - * Fractional constants are scaled left by CONST_BITS bits. - - * CONST_BITS is defined within each module using these macros, - - * and may differ from one module to the next. - - */ - - - -#define ONE ( (INT32) 1 ) - -#define CONST_SCALE ( ONE << CONST_BITS ) - - - -/* Convert a positive real constant to an integer scaled by CONST_SCALE. - - * Caution: some C compilers fail to reduce "FIX(constant)" at compile time, - - * thus causing a lot of useless floating-point operations at run time. - - */ - - - -#define FIX( x ) ( (INT32) ( ( x ) * CONST_SCALE + 0.5 ) ) - - - -/* Descale and correctly round an INT32 value that's scaled by N bits. - - * We assume RIGHT_SHIFT rounds towards minus infinity, so adding - - * the fudge factor is correct for either sign of X. - - */ - - - -#define DESCALE( x,n ) RIGHT_SHIFT( ( x ) + ( ONE << ( ( n ) - 1 ) ), n ) - - - -/* Multiply an INT32 variable by an INT32 constant to yield an INT32 result. - - * This macro is used only when the two inputs will actually be no more than - - * 16 bits wide, so that a 16x16->32 bit multiply can be used instead of a - - * full 32x32 multiply. This provides a useful speedup on many machines. - - * Unfortunately there is no way to specify a 16x16->32 multiply portably - - * in C, but some C compilers will do the right thing if you provide the - - * correct combination of casts. - - */ - - - -#ifdef SHORTxSHORT_32 /* may work if 'int' is 32 bits */ - -#define MULTIPLY16C16( var,const ) ( ( (INT16) ( var ) ) * ( (INT16) ( const ) ) ) - -#endif - -#ifdef SHORTxLCONST_32 /* known to work with Microsoft C 6.0 */ - -#define MULTIPLY16C16( var,const ) ( ( (INT16) ( var ) ) * ( (INT32) ( const ) ) ) - -#endif - - - -#ifndef MULTIPLY16C16 /* default definition */ - -#define MULTIPLY16C16( var,const ) ( ( var ) * ( const ) ) - -#endif - - - -/* Same except both inputs are variables. */ - - - -#ifdef SHORTxSHORT_32 /* may work if 'int' is 32 bits */ - -#define MULTIPLY16V16( var1,var2 ) ( ( (INT16) ( var1 ) ) * ( (INT16) ( var2 ) ) ) - -#endif - - - -#ifndef MULTIPLY16V16 /* default definition */ - -#define MULTIPLY16V16( var1,var2 ) ( ( var1 ) * ( var2 ) ) - -#endif diff --git a/tools/urt/libs/jpeg6/jddctmgr.cpp b/tools/urt/libs/jpeg6/jddctmgr.cpp deleted file mode 100644 index 628f3ef..0000000 --- a/tools/urt/libs/jpeg6/jddctmgr.cpp +++ /dev/null @@ -1,537 +0,0 @@ -/* - - * jddctmgr.c - - * - - * Copyright (C) 1994-1995, Thomas G. Lane. - - * This file is part of the Independent JPEG Group's software. - - * For conditions of distribution and use, see the accompanying README file. - - * - - * This file contains the inverse-DCT management logic. - - * This code selects a particular IDCT implementation to be used, - - * and it performs related housekeeping chores. No code in this file - - * is executed per IDCT step, only during output pass setup. - - * - - * Note that the IDCT routines are responsible for performing coefficient - - * dequantization as well as the IDCT proper. This module sets up the - - * dequantization multiplier table needed by the IDCT routine. - - */ - - - -#define JPEG_INTERNALS - -#include "jinclude.h" - -#include "radiant_jpeglib.h" - -#include "jdct.h" /* Private declarations for DCT subsystem */ - - - - - -/* - - * The decompressor input side (jdinput.c) saves away the appropriate - - * quantization table for each component at the start of the first scan - - * involving that component. (This is necessary in order to correctly - - * decode files that reuse Q-table slots.) - - * When we are ready to make an output pass, the saved Q-table is converted - - * to a multiplier table that will actually be used by the IDCT routine. - - * The multiplier table contents are IDCT-method-dependent. To support - - * application changes in IDCT method between scans, we can remake the - - * multiplier tables if necessary. - - * In buffered-image mode, the first output pass may occur before any data - - * has been seen for some components, and thus before their Q-tables have - - * been saved away. To handle this case, multiplier tables are preset - - * to zeroes; the result of the IDCT will be a neutral gray level. - - */ - - - - - -/* Private subobject for this module */ - - - -typedef struct { - - struct jpeg_inverse_dct pub; /* public fields */ - - - - /* This array contains the IDCT method code that each multiplier table - - * is currently set up for, or -1 if it's not yet set up. - - * The actual multiplier tables are pointed to by dct_table in the - - * per-component comp_info structures. - - */ - - int cur_method[MAX_COMPONENTS]; - -} my_idct_controller; - - - -typedef my_idct_controller * my_idct_ptr; - - - - - -/* Allocated multiplier tables: big enough for any supported variant */ - - - -typedef union { - - ISLOW_MULT_TYPE islow_array[DCTSIZE2]; - -#ifdef DCT_IFAST_SUPPORTED - - IFAST_MULT_TYPE ifast_array[DCTSIZE2]; - -#endif - -#ifdef DCT_FLOAT_SUPPORTED - - FLOAT_MULT_TYPE float_array[DCTSIZE2]; - -#endif - -} multiplier_table; - - - - - -/* The current scaled-IDCT routines require ISLOW-style multiplier tables, - - * so be sure to compile that code if either ISLOW or SCALING is requested. - - */ - -#ifdef DCT_ISLOW_SUPPORTED - -#define PROVIDE_ISLOW_TABLES - -#else - -#ifdef IDCT_SCALING_SUPPORTED - -#define PROVIDE_ISLOW_TABLES - -#endif - -#endif - - - - - -/* - - * Prepare for an output pass. - - * Here we select the proper IDCT routine for each component and build - - * a matching multiplier table. - - */ - - - -METHODDEF void - -start_pass( j_decompress_ptr cinfo ){ - - my_idct_ptr idct = (my_idct_ptr) cinfo->idct; - - int ci, i; - - jpeg_component_info *compptr; - - int method = 0; - - inverse_DCT_method_ptr method_ptr = NULL; - - JQUANT_TBL * qtbl; - - - - for ( ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components; - - ci++, compptr++ ) { - - /* Select the proper IDCT routine for this component's scaling */ - - switch ( compptr->DCT_scaled_size ) { - -#ifdef IDCT_SCALING_SUPPORTED - - case 1: - - method_ptr = jpeg_idct_1x1; - - method = JDCT_ISLOW; /* jidctred uses islow-style table */ - - break; - - case 2: - - method_ptr = jpeg_idct_2x2; - - method = JDCT_ISLOW; /* jidctred uses islow-style table */ - - break; - - case 4: - - method_ptr = jpeg_idct_4x4; - - method = JDCT_ISLOW; /* jidctred uses islow-style table */ - - break; - -#endif - - case DCTSIZE: - - switch ( cinfo->dct_method ) { - -#ifdef DCT_ISLOW_SUPPORTED - - case JDCT_ISLOW: - - method_ptr = jpeg_idct_islow; - - method = JDCT_ISLOW; - - break; - -#endif - -#ifdef DCT_IFAST_SUPPORTED - - case JDCT_IFAST: - - method_ptr = jpeg_idct_ifast; - - method = JDCT_IFAST; - - break; - -#endif - -#ifdef DCT_FLOAT_SUPPORTED - - case JDCT_FLOAT: - - method_ptr = jpeg_idct_float; - - method = JDCT_FLOAT; - - break; - -#endif - - default: - - ERREXIT( cinfo, JERR_NOT_COMPILED ); - - break; - - } - - break; - - default: - - ERREXIT1( cinfo, JERR_BAD_DCTSIZE, compptr->DCT_scaled_size ); - - break; - - } - - idct->pub.inverse_DCT[ci] = method_ptr; - - /* Create multiplier table from quant table. - - * However, we can skip this if the component is uninteresting - - * or if we already built the table. Also, if no quant table - - * has yet been saved for the component, we leave the - - * multiplier table all-zero; we'll be reading zeroes from the - - * coefficient controller's buffer anyway. - - */ - - if ( !compptr->component_needed || idct->cur_method[ci] == method ) { - - continue; - } - - qtbl = compptr->quant_table; - - if ( qtbl == NULL ) { /* happens if no data yet for component */ - - continue; - } - - idct->cur_method[ci] = method; - - switch ( method ) { - -#ifdef PROVIDE_ISLOW_TABLES - - case JDCT_ISLOW: - - { - - /* For LL&M IDCT method, multipliers are equal to raw quantization - - * coefficients, but are stored in natural order as ints. - - */ - - ISLOW_MULT_TYPE * ismtbl = (ISLOW_MULT_TYPE *) compptr->dct_table; - - for ( i = 0; i < DCTSIZE2; i++ ) { - - ismtbl[i] = (ISLOW_MULT_TYPE) qtbl->quantval[jpeg_zigzag_order[i]]; - - } - - } - - break; - -#endif - -#ifdef DCT_IFAST_SUPPORTED - - case JDCT_IFAST: - - { - - /* For AA&N IDCT method, multipliers are equal to quantization - - * coefficients scaled by scalefactor[row]*scalefactor[col], where - - * scalefactor[0] = 1 - - * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7 - - * For integer operation, the multiplier table is to be scaled by - - * IFAST_SCALE_BITS. The multipliers are stored in natural order. - - */ - - IFAST_MULT_TYPE * ifmtbl = (IFAST_MULT_TYPE *) compptr->dct_table; - -#define CONST_BITS 14 - - static const INT16 aanscales[DCTSIZE2] = { - - /* precomputed values scaled up by 14 bits */ - - 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520, - - 22725, 31521, 29692, 26722, 22725, 17855, 12299, 6270, - - 21407, 29692, 27969, 25172, 21407, 16819, 11585, 5906, - - 19266, 26722, 25172, 22654, 19266, 15137, 10426, 5315, - - 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520, - - 12873, 17855, 16819, 15137, 12873, 10114, 6967, 3552, - - 8867, 12299, 11585, 10426, 8867, 6967, 4799, 2446, - - 4520, 6270, 5906, 5315, 4520, 3552, 2446, 1247 - - }; - - SHIFT_TEMPS - - - - for ( i = 0; i < DCTSIZE2; i++ ) { - - ifmtbl[i] = (IFAST_MULT_TYPE) - - DESCALE( MULTIPLY16V16( (INT32) qtbl->quantval[jpeg_zigzag_order[i]], - - (INT32) aanscales[i] ), - - CONST_BITS - IFAST_SCALE_BITS ); - - } - - } - - break; - -#endif - -#ifdef DCT_FLOAT_SUPPORTED - - case JDCT_FLOAT: - - { - - /* For float AA&N IDCT method, multipliers are equal to quantization - - * coefficients scaled by scalefactor[row]*scalefactor[col], where - - * scalefactor[0] = 1 - - * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7 - - * The multipliers are stored in natural order. - - */ - - FLOAT_MULT_TYPE * fmtbl = (FLOAT_MULT_TYPE *) compptr->dct_table; - - int row, col; - - static const double aanscalefactor[DCTSIZE] = { - - 1.0, 1.387039845, 1.306562965, 1.175875602, - - 1.0, 0.785694958, 0.541196100, 0.275899379 - - }; - - - - i = 0; - - for ( row = 0; row < DCTSIZE; row++ ) { - - for ( col = 0; col < DCTSIZE; col++ ) { - - fmtbl[i] = (FLOAT_MULT_TYPE) - - ( (double) qtbl->quantval[jpeg_zigzag_order[i]] * - - aanscalefactor[row] * aanscalefactor[col] ); - - i++; - - } - - } - - } - - break; - -#endif - - default: - - ERREXIT( cinfo, JERR_NOT_COMPILED ); - - break; - - } - - } - -} - - - - - -/* - - * Initialize IDCT manager. - - */ - - - -GLOBAL void - -jinit_inverse_dct( j_decompress_ptr cinfo ){ - - my_idct_ptr idct; - - int ci; - - jpeg_component_info *compptr; - - - - idct = (my_idct_ptr) - - ( *cinfo->mem->alloc_small )( (j_common_ptr) cinfo, JPOOL_IMAGE, - - SIZEOF( my_idct_controller ) ); - - cinfo->idct = (struct jpeg_inverse_dct *) idct; - - idct->pub.start_pass = start_pass; - - - - for ( ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components; - - ci++, compptr++ ) { - - /* Allocate and pre-zero a multiplier table for each component */ - - compptr->dct_table = - - ( *cinfo->mem->alloc_small )( (j_common_ptr) cinfo, JPOOL_IMAGE, - - SIZEOF( multiplier_table ) ); - - MEMZERO( compptr->dct_table, SIZEOF( multiplier_table ) ); - - /* Mark multiplier table not yet set up for any method */ - - idct->cur_method[ci] = -1; - - } - -} diff --git a/tools/urt/libs/jpeg6/jdhuff.cpp b/tools/urt/libs/jpeg6/jdhuff.cpp deleted file mode 100644 index 3b6ddaf..0000000 --- a/tools/urt/libs/jpeg6/jdhuff.cpp +++ /dev/null @@ -1,586 +0,0 @@ -/* - * jdhuff.c - * - * Copyright (C) 1991-1995, Thomas G. Lane. - * This file is part of the Independent JPEG Group's software. - * For conditions of distribution and use, see the accompanying README file. - * - * This file contains Huffman entropy decoding routines. - * - * Much of the complexity here has to do with supporting input suspension. - * If the data source module demands suspension, we want to be able to back - * up to the start of the current MCU. To do this, we copy state variables - * into local working storage, and update them back to the permanent - * storage only upon successful completion of an MCU. - */ - -#define JPEG_INTERNALS -#include "jinclude.h" -#include "radiant_jpeglib.h" -#include "jdhuff.h" /* Declarations shared with jdphuff.c */ - - -/* - * Expanded entropy decoder object for Huffman decoding. - * - * The savable_state subrecord contains fields that change within an MCU, - * but must not be updated permanently until we complete the MCU. - */ - -typedef struct { - int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */ -} savable_state; - -/* This macro is to work around compilers with missing or broken - * structure assignment. You'll need to fix this code if you have - * such a compiler and you change MAX_COMPS_IN_SCAN. - */ - -#ifndef NO_STRUCT_ASSIGN -#define ASSIGN_STATE( dest,src ) ( ( dest ) = ( src ) ) -#else -#if MAX_COMPS_IN_SCAN == 4 -#define ASSIGN_STATE( dest,src ) \ - ( ( dest ).last_dc_val[0] = ( src ).last_dc_val[0], \ - ( dest ).last_dc_val[1] = ( src ).last_dc_val[1], \ - ( dest ).last_dc_val[2] = ( src ).last_dc_val[2], \ - ( dest ).last_dc_val[3] = ( src ).last_dc_val[3] ) -#endif -#endif - - -typedef struct { - struct jpeg_entropy_decoder pub; /* public fields */ - - /* These fields are loaded into local variables at start of each MCU. - * In case of suspension, we exit WITHOUT updating them. - */ - bitread_perm_state bitstate; /* Bit buffer at start of MCU */ - savable_state saved; /* Other state at start of MCU */ - - /* These fields are NOT loaded into local working state. */ - unsigned int restarts_to_go; /* MCUs left in this restart interval */ - - /* Pointers to derived tables (these workspaces have image lifespan) */ - d_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS]; - d_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS]; -} huff_entropy_decoder; - -typedef huff_entropy_decoder * huff_entropy_ptr; - - -/* - * Initialize for a Huffman-compressed scan. - */ - -METHODDEF void -start_pass_huff_decoder( j_decompress_ptr cinfo ){ - huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy; - int ci, dctbl, actbl; - jpeg_component_info * compptr; - - /* Check that the scan parameters Ss, Se, Ah/Al are OK for sequential JPEG. - * This ought to be an error condition, but we make it a warning because - * there are some baseline files out there with all zeroes in these bytes. - */ - if ( cinfo->Ss != 0 || cinfo->Se != DCTSIZE2 - 1 || - cinfo->Ah != 0 || cinfo->Al != 0 ) { - WARNMS( cinfo, JWRN_NOT_SEQUENTIAL ); - } - - for ( ci = 0; ci < cinfo->comps_in_scan; ci++ ) { - compptr = cinfo->cur_comp_info[ci]; - dctbl = compptr->dc_tbl_no; - actbl = compptr->ac_tbl_no; - /* Make sure requested tables are present */ - if ( dctbl < 0 || dctbl >= NUM_HUFF_TBLS || - cinfo->dc_huff_tbl_ptrs[dctbl] == NULL ) { - ERREXIT1( cinfo, JERR_NO_HUFF_TABLE, dctbl ); - } - if ( actbl < 0 || actbl >= NUM_HUFF_TBLS || - cinfo->ac_huff_tbl_ptrs[actbl] == NULL ) { - ERREXIT1( cinfo, JERR_NO_HUFF_TABLE, actbl ); - } - /* Compute derived values for Huffman tables */ - /* We may do this more than once for a table, but it's not expensive */ - jpeg_make_d_derived_tbl( cinfo, cinfo->dc_huff_tbl_ptrs[dctbl], - &entropy->dc_derived_tbls[dctbl] ); - jpeg_make_d_derived_tbl( cinfo, cinfo->ac_huff_tbl_ptrs[actbl], - &entropy->ac_derived_tbls[actbl] ); - /* Initialize DC predictions to 0 */ - entropy->saved.last_dc_val[ci] = 0; - } - - /* Initialize bitread state variables */ - entropy->bitstate.bits_left = 0; - entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */ - entropy->bitstate.printed_eod = FALSE; - - /* Initialize restart counter */ - entropy->restarts_to_go = cinfo->restart_interval; -} - - -/* - * Compute the derived values for a Huffman table. - * Note this is also used by jdphuff.c. - */ - -GLOBAL void -jpeg_make_d_derived_tbl( j_decompress_ptr cinfo, JHUFF_TBL * htbl, - d_derived_tbl ** pdtbl ){ - d_derived_tbl *dtbl; - int p, i, l, si; - int lookbits, ctr; - char huffsize[257]; - unsigned int huffcode[257]; - unsigned int code; - - /* Allocate a workspace if we haven't already done so. */ - if ( *pdtbl == NULL ) { - *pdtbl = (d_derived_tbl *) - ( *cinfo->mem->alloc_small )( (j_common_ptr) cinfo, JPOOL_IMAGE, - SIZEOF( d_derived_tbl ) ); - } - dtbl = *pdtbl; - dtbl->pub = htbl; /* fill in back link */ - - /* Figure C.1: make table of Huffman code length for each symbol */ - /* Note that this is in code-length order. */ - - p = 0; - for ( l = 1; l <= 16; l++ ) { - for ( i = 1; i <= (int) htbl->bits[l]; i++ ) - huffsize[p++] = (char) l; - } - huffsize[p] = 0; - - /* Figure C.2: generate the codes themselves */ - /* Note that this is in code-length order. */ - - code = 0; - si = huffsize[0]; - p = 0; - while ( huffsize[p] ) { - while ( ( (int) huffsize[p] ) == si ) { - huffcode[p++] = code; - code++; - } - code <<= 1; - si++; - } - - /* Figure F.15: generate decoding tables for bit-sequential decoding */ - - p = 0; - for ( l = 1; l <= 16; l++ ) { - if ( htbl->bits[l] ) { - dtbl->valptr[l] = p; /* huffval[] index of 1st symbol of code length l */ - dtbl->mincode[l] = huffcode[p]; /* minimum code of length l */ - p += htbl->bits[l]; - dtbl->maxcode[l] = huffcode[p - 1]; /* maximum code of length l */ - } - else { - dtbl->maxcode[l] = -1; /* -1 if no codes of this length */ - } - } - dtbl->maxcode[17] = 0xFFFFFL; /* ensures jpeg_huff_decode terminates */ - - /* Compute lookahead tables to speed up decoding. - * First we set all the table entries to 0, indicating "too long"; - * then we iterate through the Huffman codes that are short enough and - * fill in all the entries that correspond to bit sequences starting - * with that code. - */ - - MEMZERO( dtbl->look_nbits, SIZEOF( dtbl->look_nbits ) ); - - p = 0; - for ( l = 1; l <= HUFF_LOOKAHEAD; l++ ) { - for ( i = 1; i <= (int) htbl->bits[l]; i++, p++ ) { - /* l = current code's length, p = its index in huffcode[] & huffval[]. */ - /* Generate left-justified code followed by all possible bit sequences */ - lookbits = huffcode[p] << ( HUFF_LOOKAHEAD - l ); - for ( ctr = 1 << ( HUFF_LOOKAHEAD - l ); ctr > 0; ctr-- ) { - dtbl->look_nbits[lookbits] = l; - dtbl->look_sym[lookbits] = htbl->huffval[p]; - lookbits++; - } - } - } -} - - -/* - * Out-of-line code for bit fetching (shared with jdphuff.c). - * See jdhuff.h for info about usage. - * Note: current values of get_buffer and bits_left are passed as parameters, - * but are returned in the corresponding fields of the state struct. - * - * On most machines MIN_GET_BITS should be 25 to allow the full 32-bit width - * of get_buffer to be used. (On machines with wider words, an even larger - * buffer could be used.) However, on some machines 32-bit shifts are - * quite slow and take time proportional to the number of places shifted. - * (This is true with most PC compilers, for instance.) In this case it may - * be a win to set MIN_GET_BITS to the minimum value of 15. This reduces the - * average shift distance at the cost of more calls to jpeg_fill_bit_buffer. - */ - -#ifdef SLOW_SHIFT_32 -#define MIN_GET_BITS 15 /* minimum allowable value */ -#else -#define MIN_GET_BITS ( BIT_BUF_SIZE - 7 ) -#endif - - -GLOBAL boolean -jpeg_fill_bit_buffer( bitread_working_state * state, - register bit_buf_type get_buffer, register int bits_left, - int nbits ){ -/* Load up the bit buffer to a depth of at least nbits */ - /* Copy heavily used state fields into locals (hopefully registers) */ - register const JOCTET * next_input_byte = state->next_input_byte; - register size_t bytes_in_buffer = state->bytes_in_buffer; - register int c; - - /* Attempt to load at least MIN_GET_BITS bits into get_buffer. */ - /* (It is assumed that no request will be for more than that many bits.) */ - - while ( bits_left < MIN_GET_BITS ) { - /* Attempt to read a byte */ - if ( state->unread_marker != 0 ) { - goto no_more_data; /* can't advance past a marker */ - - } - if ( bytes_in_buffer == 0 ) { - if ( !( *state->cinfo->src->fill_input_buffer )( state->cinfo ) ) { - return FALSE; - } - next_input_byte = state->cinfo->src->next_input_byte; - bytes_in_buffer = state->cinfo->src->bytes_in_buffer; - } - bytes_in_buffer--; - c = GETJOCTET( *next_input_byte++ ); - - /* If it's 0xFF, check and discard stuffed zero byte */ - if ( c == 0xFF ) { - do { - if ( bytes_in_buffer == 0 ) { - if ( !( *state->cinfo->src->fill_input_buffer )( state->cinfo ) ) { - return FALSE; - } - next_input_byte = state->cinfo->src->next_input_byte; - bytes_in_buffer = state->cinfo->src->bytes_in_buffer; - } - bytes_in_buffer--; - c = GETJOCTET( *next_input_byte++ ); - } while ( c == 0xFF ); - - if ( c == 0 ) { - /* Found FF/00, which represents an FF data byte */ - c = 0xFF; - } - else { - /* Oops, it's actually a marker indicating end of compressed data. */ - /* Better put it back for use later */ - state->unread_marker = c; - -no_more_data: - /* There should be enough bits still left in the data segment; */ - /* if so, just break out of the outer while loop. */ - if ( bits_left >= nbits ) { - break; - } - /* Uh-oh. Report corrupted data to user and stuff zeroes into - * the data stream, so that we can produce some kind of image. - * Note that this code will be repeated for each byte demanded - * for the rest of the segment. We use a nonvolatile flag to ensure - * that only one warning message appears. - */ - if ( !*( state->printed_eod_ptr ) ) { - WARNMS( state->cinfo, JWRN_HIT_MARKER ); - *( state->printed_eod_ptr ) = TRUE; - } - c = 0; /* insert a zero byte into bit buffer */ - } - } - - /* OK, load c into get_buffer */ - get_buffer = ( get_buffer << 8 ) | c; - bits_left += 8; - } - - /* Unload the local registers */ - state->next_input_byte = next_input_byte; - state->bytes_in_buffer = bytes_in_buffer; - state->get_buffer = get_buffer; - state->bits_left = bits_left; - - return TRUE; -} - - -/* - * Out-of-line code for Huffman code decoding. - * See jdhuff.h for info about usage. - */ - -GLOBAL int -jpeg_huff_decode( bitread_working_state * state, - register bit_buf_type get_buffer, register int bits_left, - d_derived_tbl * htbl, int min_bits ){ - register int l = min_bits; - register INT32 code; - - /* HUFF_DECODE has determined that the code is at least min_bits */ - /* bits long, so fetch that many bits in one swoop. */ - - CHECK_BIT_BUFFER( *state, l, return -1 ); - code = GET_BITS( l ); - - /* Collect the rest of the Huffman code one bit at a time. */ - /* This is per Figure F.16 in the JPEG spec. */ - - while ( code > htbl->maxcode[l] ) { - code <<= 1; - CHECK_BIT_BUFFER( *state, 1, return -1 ); - code |= GET_BITS( 1 ); - l++; - } - - /* Unload the local registers */ - state->get_buffer = get_buffer; - state->bits_left = bits_left; - - /* With garbage input we may reach the sentinel value l = 17. */ - - if ( l > 16 ) { - WARNMS( state->cinfo, JWRN_HUFF_BAD_CODE ); - return 0; /* fake a zero as the safest result */ - } - - return htbl->pub->huffval[ htbl->valptr[l] + - ( (int) ( code - htbl->mincode[l] ) ) ]; -} - - -/* - * Figure F.12: extend sign bit. - * On some machines, a shift and add will be faster than a table lookup. - */ - -#ifdef AVOID_TABLES - -#define HUFF_EXTEND( x,s ) ( ( x ) < ( 1 << ( ( s ) - 1 ) ) ? ( x ) + ( ( ( -1 ) << ( s ) ) + 1 ) : ( x ) ) - -#else - -#define HUFF_EXTEND( x,s ) ( ( x ) < extend_test[s] ? ( x ) + extend_offset[s] : ( x ) ) - -static const int extend_test[16] = /* entry n is 2**(n-1) */ -{ 0, 0x0001, 0x0002, 0x0004, 0x0008, 0x0010, 0x0020, 0x0040, 0x0080, - 0x0100, 0x0200, 0x0400, 0x0800, 0x1000, 0x2000, 0x4000 }; - -static const int extend_offset[16] = /* entry n is (-1 << n) + 1 */ -{ 0, ( ( -1 ) << 1 ) + 1, ( ( -1 ) << 2 ) + 1, ( ( -1 ) << 3 ) + 1, ( ( -1 ) << 4 ) + 1, - ( ( -1 ) << 5 ) + 1, ( ( -1 ) << 6 ) + 1, ( ( -1 ) << 7 ) + 1, ( ( -1 ) << 8 ) + 1, - ( ( -1 ) << 9 ) + 1, ( ( -1 ) << 10 ) + 1, ( ( -1 ) << 11 ) + 1, ( ( -1 ) << 12 ) + 1, - ( ( -1 ) << 13 ) + 1, ( ( -1 ) << 14 ) + 1, ( ( -1 ) << 15 ) + 1 }; - -#endif /* AVOID_TABLES */ - - -/* - * Check for a restart marker & resynchronize decoder. - * Returns FALSE if must suspend. - */ - -LOCAL boolean -process_restart( j_decompress_ptr cinfo ){ - huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy; - int ci; - - /* Throw away any unused bits remaining in bit buffer; */ - /* include any full bytes in next_marker's count of discarded bytes */ - cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8; - entropy->bitstate.bits_left = 0; - - /* Advance past the RSTn marker */ - if ( !( *cinfo->marker->read_restart_marker )( cinfo ) ) { - return FALSE; - } - - /* Re-initialize DC predictions to 0 */ - for ( ci = 0; ci < cinfo->comps_in_scan; ci++ ) - entropy->saved.last_dc_val[ci] = 0; - - /* Reset restart counter */ - entropy->restarts_to_go = cinfo->restart_interval; - - /* Next segment can get another out-of-data warning */ - entropy->bitstate.printed_eod = FALSE; - - return TRUE; -} - - -/* - * Decode and return one MCU's worth of Huffman-compressed coefficients. - * The coefficients are reordered from zigzag order into natural array order, - * but are not dequantized. - * - * The i'th block of the MCU is stored into the block pointed to by - * MCU_data[i]. WE ASSUME THIS AREA HAS BEEN ZEROED BY THE CALLER. - * (Wholesale zeroing is usually a little faster than retail...) - * - * Returns FALSE if data source requested suspension. In that case no - * changes have been made to permanent state. (Exception: some output - * coefficients may already have been assigned. This is harmless for - * this module, since we'll just re-assign them on the next call.) - */ - -METHODDEF boolean -decode_mcu( j_decompress_ptr cinfo, JBLOCKROW *MCU_data ){ - huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy; - register int s, k, r; - int blkn, ci; - JBLOCKROW block; - BITREAD_STATE_VARS; - savable_state state; - d_derived_tbl * dctbl; - d_derived_tbl * actbl; - jpeg_component_info * compptr; - - /* Process restart marker if needed; may have to suspend */ - if ( cinfo->restart_interval ) { - if ( entropy->restarts_to_go == 0 ) { - if ( !process_restart( cinfo ) ) { - return FALSE; - } - } - } - - /* Load up working state */ - BITREAD_LOAD_STATE( cinfo,entropy->bitstate ); - ASSIGN_STATE( state, entropy->saved ); - - /* Outer loop handles each block in the MCU */ - - for ( blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++ ) { - block = MCU_data[blkn]; - ci = cinfo->MCU_membership[blkn]; - compptr = cinfo->cur_comp_info[ci]; - dctbl = entropy->dc_derived_tbls[compptr->dc_tbl_no]; - actbl = entropy->ac_derived_tbls[compptr->ac_tbl_no]; - - /* Decode a single block's worth of coefficients */ - - /* Section F.2.2.1: decode the DC coefficient difference */ - HUFF_DECODE( s, br_state, dctbl, return FALSE, label1 ); - if ( s ) { - CHECK_BIT_BUFFER( br_state, s, return FALSE ); - r = GET_BITS( s ); - s = HUFF_EXTEND( r, s ); - } - - /* Shortcut if component's values are not interesting */ - if ( !compptr->component_needed ) { - goto skip_ACs; - } - - /* Convert DC difference to actual value, update last_dc_val */ - s += state.last_dc_val[ci]; - state.last_dc_val[ci] = s; - /* Output the DC coefficient (assumes jpeg_natural_order[0] = 0) */ - ( *block )[0] = (JCOEF) s; - - /* Do we need to decode the AC coefficients for this component? */ - if ( compptr->DCT_scaled_size > 1 ) { - - /* Section F.2.2.2: decode the AC coefficients */ - /* Since zeroes are skipped, output area must be cleared beforehand */ - for ( k = 1; k < DCTSIZE2; k++ ) { - HUFF_DECODE( s, br_state, actbl, return FALSE, label2 ); - - r = s >> 4; - s &= 15; - - if ( s ) { - k += r; - CHECK_BIT_BUFFER( br_state, s, return FALSE ); - r = GET_BITS( s ); - s = HUFF_EXTEND( r, s ); - /* Output coefficient in natural (dezigzagged) order. - * Note: the extra entries in jpeg_natural_order[] will save us - * if k >= DCTSIZE2, which could happen if the data is corrupted. - */ - ( *block )[jpeg_natural_order[k]] = (JCOEF) s; - } - else { - if ( r != 15 ) { - break; - } - k += 15; - } - } - - } - else { -skip_ACs: - - /* Section F.2.2.2: decode the AC coefficients */ - /* In this path we just discard the values */ - for ( k = 1; k < DCTSIZE2; k++ ) { - HUFF_DECODE( s, br_state, actbl, return FALSE, label3 ); - - r = s >> 4; - s &= 15; - - if ( s ) { - k += r; - CHECK_BIT_BUFFER( br_state, s, return FALSE ); - DROP_BITS( s ); - } - else { - if ( r != 15 ) { - break; - } - k += 15; - } - } - - } - } - - /* Completed MCU, so update state */ - BITREAD_SAVE_STATE( cinfo,entropy->bitstate ); - ASSIGN_STATE( entropy->saved, state ); - - /* Account for restart interval (no-op if not using restarts) */ - entropy->restarts_to_go--; - - return TRUE; -} - - -/* - * Module initialization routine for Huffman entropy decoding. - */ - -GLOBAL void -jinit_huff_decoder( j_decompress_ptr cinfo ){ - huff_entropy_ptr entropy; - int i; - - entropy = (huff_entropy_ptr) - ( *cinfo->mem->alloc_small )( (j_common_ptr) cinfo, JPOOL_IMAGE, - SIZEOF( huff_entropy_decoder ) ); - cinfo->entropy = (struct jpeg_entropy_decoder *) entropy; - entropy->pub.start_pass = start_pass_huff_decoder; - entropy->pub.decode_mcu = decode_mcu; - - /* Mark tables unallocated */ - for ( i = 0; i < NUM_HUFF_TBLS; i++ ) { - entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL; - } -} diff --git a/tools/urt/libs/jpeg6/jdhuff.h b/tools/urt/libs/jpeg6/jdhuff.h deleted file mode 100644 index 449b527..0000000 --- a/tools/urt/libs/jpeg6/jdhuff.h +++ /dev/null @@ -1,202 +0,0 @@ -/* - * jdhuff.h - * - * Copyright (C) 1991-1995, Thomas G. Lane. - * This file is part of the Independent JPEG Group's software. - * For conditions of distribution and use, see the accompanying README file. - * - * This file contains declarations for Huffman entropy decoding routines - * that are shared between the sequential decoder (jdhuff.c) and the - * progressive decoder (jdphuff.c). No other modules need to see these. - */ - -/* Short forms of external names for systems with brain-damaged linkers. */ - -#ifdef NEED_SHORT_EXTERNAL_NAMES -#define jpeg_make_d_derived_tbl jMkDDerived -#define jpeg_fill_bit_buffer jFilBitBuf -#define jpeg_huff_decode jHufDecode -#endif /* NEED_SHORT_EXTERNAL_NAMES */ - - -/* Derived data constructed for each Huffman table */ - -#define HUFF_LOOKAHEAD 8 /* # of bits of lookahead */ - -typedef struct { - /* Basic tables: (element [0] of each array is unused) */ - INT32 mincode[17]; /* smallest code of length k */ - INT32 maxcode[18]; /* largest code of length k (-1 if none) */ - /* (maxcode[17] is a sentinel to ensure jpeg_huff_decode terminates) */ - int valptr[17]; /* huffval[] index of 1st symbol of length k */ - - /* Link to public Huffman table (needed only in jpeg_huff_decode) */ - JHUFF_TBL *pub; - - /* Lookahead tables: indexed by the next HUFF_LOOKAHEAD bits of - * the input data stream. If the next Huffman code is no more - * than HUFF_LOOKAHEAD bits long, we can obtain its length and - * the corresponding symbol directly from these tables. - */ - int look_nbits[1 << HUFF_LOOKAHEAD]; /* # bits, or 0 if too long */ - UINT8 look_sym[1 << HUFF_LOOKAHEAD]; /* symbol, or unused */ -} d_derived_tbl; - -/* Expand a Huffman table definition into the derived format */ -EXTERN void jpeg_make_d_derived_tbl JPP( ( j_decompress_ptr cinfo, - JHUFF_TBL * htbl, d_derived_tbl * *pdtbl ) ); - - -/* - * Fetching the next N bits from the input stream is a time-critical operation - * for the Huffman decoders. We implement it with a combination of inline - * macros and out-of-line subroutines. Note that N (the number of bits - * demanded at one time) never exceeds 15 for JPEG use. - * - * We read source bytes into get_buffer and dole out bits as needed. - * If get_buffer already contains enough bits, they are fetched in-line - * by the macros CHECK_BIT_BUFFER and GET_BITS. When there aren't enough - * bits, jpeg_fill_bit_buffer is called; it will attempt to fill get_buffer - * as full as possible (not just to the number of bits needed; this - * prefetching reduces the overhead cost of calling jpeg_fill_bit_buffer). - * Note that jpeg_fill_bit_buffer may return FALSE to indicate suspension. - * On TRUE return, jpeg_fill_bit_buffer guarantees that get_buffer contains - * at least the requested number of bits --- dummy zeroes are inserted if - * necessary. - */ - -typedef INT32 bit_buf_type; /* type of bit-extraction buffer */ -#define BIT_BUF_SIZE 32 /* size of buffer in bits */ - -/* If long is > 32 bits on your machine, and shifting/masking longs is - * reasonably fast, making bit_buf_type be long and setting BIT_BUF_SIZE - * appropriately should be a win. Unfortunately we can't do this with - * something like #define BIT_BUF_SIZE (sizeof(bit_buf_type)*8) - * because not all machines measure sizeof in 8-bit bytes. - */ - -typedef struct { /* Bitreading state saved across MCUs */ - bit_buf_type get_buffer; /* current bit-extraction buffer */ - int bits_left; /* # of unused bits in it */ - boolean printed_eod; /* flag to suppress multiple warning msgs */ -} bitread_perm_state; - -typedef struct { /* Bitreading working state within an MCU */ - /* current data source state */ - const JOCTET * next_input_byte; /* => next byte to read from source */ - size_t bytes_in_buffer; /* # of bytes remaining in source buffer */ - int unread_marker; /* nonzero if we have hit a marker */ - /* bit input buffer --- note these values are kept in register variables, - * not in this struct, inside the inner loops. - */ - bit_buf_type get_buffer; /* current bit-extraction buffer */ - int bits_left; /* # of unused bits in it */ - /* pointers needed by jpeg_fill_bit_buffer */ - j_decompress_ptr cinfo; /* back link to decompress master record */ - boolean * printed_eod_ptr; /* => flag in permanent state */ -} bitread_working_state; - -/* Macros to declare and load/save bitread local variables. */ -#define BITREAD_STATE_VARS \ - register bit_buf_type get_buffer; \ - register int bits_left; \ - bitread_working_state br_state - -#define BITREAD_LOAD_STATE( cinfop,permstate ) \ - br_state.cinfo = cinfop; \ - br_state.next_input_byte = cinfop->src->next_input_byte; \ - br_state.bytes_in_buffer = cinfop->src->bytes_in_buffer; \ - br_state.unread_marker = cinfop->unread_marker; \ - get_buffer = permstate.get_buffer; \ - bits_left = permstate.bits_left; \ - br_state.printed_eod_ptr = &permstate.printed_eod - -#define BITREAD_SAVE_STATE( cinfop,permstate ) \ - cinfop->src->next_input_byte = br_state.next_input_byte; \ - cinfop->src->bytes_in_buffer = br_state.bytes_in_buffer; \ - cinfop->unread_marker = br_state.unread_marker; \ - permstate.get_buffer = get_buffer; \ - permstate.bits_left = bits_left - -/* - * These macros provide the in-line portion of bit fetching. - * Use CHECK_BIT_BUFFER to ensure there are N bits in get_buffer - * before using GET_BITS, PEEK_BITS, or DROP_BITS. - * The variables get_buffer and bits_left are assumed to be locals, - * but the state struct might not be (jpeg_huff_decode needs this). - * CHECK_BIT_BUFFER(state,n,action); - * Ensure there are N bits in get_buffer; if suspend, take action. - * val = GET_BITS(n); - * Fetch next N bits. - * val = PEEK_BITS(n); - * Fetch next N bits without removing them from the buffer. - * DROP_BITS(n); - * Discard next N bits. - * The value N should be a simple variable, not an expression, because it - * is evaluated multiple times. - */ - -#define CHECK_BIT_BUFFER( state,nbits,action ) \ - { if ( bits_left < ( nbits ) ) { \ - if ( !jpeg_fill_bit_buffer( &( state ),get_buffer,bits_left,nbits ) ) \ - { action; } \ - get_buffer = ( state ).get_buffer; bits_left = ( state ).bits_left; } } - -#define GET_BITS( nbits ) \ - ( ( (int) ( get_buffer >> ( bits_left -= ( nbits ) ) ) ) & ( ( 1 << ( nbits ) ) - 1 ) ) - -#define PEEK_BITS( nbits ) \ - ( ( (int) ( get_buffer >> ( bits_left - ( nbits ) ) ) ) & ( ( 1 << ( nbits ) ) - 1 ) ) - -#define DROP_BITS( nbits ) \ - ( bits_left -= ( nbits ) ) - -/* Load up the bit buffer to a depth of at least nbits */ -EXTERN boolean jpeg_fill_bit_buffer JPP( ( bitread_working_state * state, - register bit_buf_type get_buffer, register int bits_left, - int nbits ) ); - - -/* - * Code for extracting next Huffman-coded symbol from input bit stream. - * Again, this is time-critical and we make the main paths be macros. - * - * We use a lookahead table to process codes of up to HUFF_LOOKAHEAD bits - * without looping. Usually, more than 95% of the Huffman codes will be 8 - * or fewer bits long. The few overlength codes are handled with a loop, - * which need not be inline code. - * - * Notes about the HUFF_DECODE macro: - * 1. Near the end of the data segment, we may fail to get enough bits - * for a lookahead. In that case, we do it the hard way. - * 2. If the lookahead table contains no entry, the next code must be - * more than HUFF_LOOKAHEAD bits long. - * 3. jpeg_huff_decode returns -1 if forced to suspend. - */ - -#define HUFF_DECODE( result,state,htbl,failaction,slowlabel ) \ - { register int nb, look; \ - if ( bits_left < HUFF_LOOKAHEAD ) { \ - if ( !jpeg_fill_bit_buffer( &state,get_buffer,bits_left, 0 ) ) {failaction; } \ - get_buffer = state.get_buffer; bits_left = state.bits_left; \ - if ( bits_left < HUFF_LOOKAHEAD ) { \ - nb = 1; goto slowlabel; \ - } \ - } \ - look = PEEK_BITS( HUFF_LOOKAHEAD ); \ - if ( ( nb = htbl->look_nbits[look] ) != 0 ) { \ - DROP_BITS( nb ); \ - result = htbl->look_sym[look]; \ - } else { \ - nb = HUFF_LOOKAHEAD + 1; \ -slowlabel: \ - if ( ( result = jpeg_huff_decode( &state,get_buffer,bits_left,htbl,nb ) ) < 0 ) \ - { failaction; } \ - get_buffer = state.get_buffer; bits_left = state.bits_left; \ - } \ - } - -/* Out-of-line case for Huffman code fetching */ -EXTERN int jpeg_huff_decode JPP( ( bitread_working_state * state, - register bit_buf_type get_buffer, register int bits_left, - d_derived_tbl * htbl, int min_bits ) ); diff --git a/tools/urt/libs/jpeg6/jdinput.cpp b/tools/urt/libs/jpeg6/jdinput.cpp deleted file mode 100644 index d5ea18a..0000000 --- a/tools/urt/libs/jpeg6/jdinput.cpp +++ /dev/null @@ -1,765 +0,0 @@ -/* - - * jdinput.c - - * - - * Copyright (C) 1991-1995, Thomas G. Lane. - - * This file is part of the Independent JPEG Group's software. - - * For conditions of distribution and use, see the accompanying README file. - - * - - * This file contains input control logic for the JPEG decompressor. - - * These routines are concerned with controlling the decompressor's input - - * processing (marker reading and coefficient decoding). The actual input - - * reading is done in jdmarker.c, jdhuff.c, and jdphuff.c. - - */ - - - -#define JPEG_INTERNALS - -#include "jinclude.h" - -#include "radiant_jpeglib.h" - - - - - -/* Private state */ - - - -typedef struct { - - struct jpeg_input_controller pub; /* public fields */ - - - - boolean inheaders; /* TRUE until first SOS is reached */ - -} my_input_controller; - - - -typedef my_input_controller * my_inputctl_ptr; - - - - - -/* Forward declarations */ - -METHODDEF int consume_markers JPP( (j_decompress_ptr cinfo) ); - - - - - -/* - - * Routines to calculate various quantities related to the size of the image. - - */ - - - -LOCAL void - -initial_setup( j_decompress_ptr cinfo ){ -/* Called once, when first SOS marker is reached */ - - int ci; - - jpeg_component_info *compptr; - - - - /* Make sure image isn't bigger than I can handle */ - - if ( (long) cinfo->image_height > (long) JPEG_MAX_DIMENSION || - - (long) cinfo->image_width > (long) JPEG_MAX_DIMENSION ) { - - ERREXIT1( cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) JPEG_MAX_DIMENSION ); - } - - - - /* For now, precision must match compiled-in value... */ - - if ( cinfo->data_precision != BITS_IN_JSAMPLE ) { - - ERREXIT1( cinfo, JERR_BAD_PRECISION, cinfo->data_precision ); - } - - - - /* Check that number of components won't exceed internal array sizes */ - - if ( cinfo->num_components > MAX_COMPONENTS ) { - - ERREXIT2( cinfo, JERR_COMPONENT_COUNT, cinfo->num_components, - - MAX_COMPONENTS ); - } - - - - /* Compute maximum sampling factors; check factor validity */ - - cinfo->max_h_samp_factor = 1; - - cinfo->max_v_samp_factor = 1; - - for ( ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components; - - ci++, compptr++ ) { - - if ( compptr->h_samp_factor <= 0 || compptr->h_samp_factor > MAX_SAMP_FACTOR || - - compptr->v_samp_factor <= 0 || compptr->v_samp_factor > MAX_SAMP_FACTOR ) { - - ERREXIT( cinfo, JERR_BAD_SAMPLING ); - } - - cinfo->max_h_samp_factor = MAX( cinfo->max_h_samp_factor, - - compptr->h_samp_factor ); - - cinfo->max_v_samp_factor = MAX( cinfo->max_v_samp_factor, - - compptr->v_samp_factor ); - - } - - - - /* We initialize DCT_scaled_size and min_DCT_scaled_size to DCTSIZE. - - * In the full decompressor, this will be overridden by jdmaster.c; - - * but in the transcoder, jdmaster.c is not used, so we must do it here. - - */ - - cinfo->min_DCT_scaled_size = DCTSIZE; - - - - /* Compute dimensions of components */ - - for ( ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components; - - ci++, compptr++ ) { - - compptr->DCT_scaled_size = DCTSIZE; - - /* Size in DCT blocks */ - - compptr->width_in_blocks = (JDIMENSION) - - jdiv_round_up( (long) cinfo->image_width * (long) compptr->h_samp_factor, - - (long) ( cinfo->max_h_samp_factor * DCTSIZE ) ); - - compptr->height_in_blocks = (JDIMENSION) - - jdiv_round_up( (long) cinfo->image_height * (long) compptr->v_samp_factor, - - (long) ( cinfo->max_v_samp_factor * DCTSIZE ) ); - - /* downsampled_width and downsampled_height will also be overridden by - - * jdmaster.c if we are doing full decompression. The transcoder library - - * doesn't use these values, but the calling application might. - - */ - - /* Size in samples */ - - compptr->downsampled_width = (JDIMENSION) - - jdiv_round_up( (long) cinfo->image_width * (long) compptr->h_samp_factor, - - (long) cinfo->max_h_samp_factor ); - - compptr->downsampled_height = (JDIMENSION) - - jdiv_round_up( (long) cinfo->image_height * (long) compptr->v_samp_factor, - - (long) cinfo->max_v_samp_factor ); - - /* Mark component needed, until color conversion says otherwise */ - - compptr->component_needed = TRUE; - - /* Mark no quantization table yet saved for component */ - - compptr->quant_table = NULL; - - } - - - - /* Compute number of fully interleaved MCU rows. */ - - cinfo->total_iMCU_rows = (JDIMENSION) - - jdiv_round_up( (long) cinfo->image_height, - - (long) ( cinfo->max_v_samp_factor * DCTSIZE ) ); - - - - /* Decide whether file contains multiple scans */ - - if ( cinfo->comps_in_scan < cinfo->num_components || cinfo->progressive_mode ) { - - cinfo->inputctl->has_multiple_scans = TRUE; - } - - else{ - - cinfo->inputctl->has_multiple_scans = FALSE; - } - -} - - - - - -LOCAL void - -per_scan_setup( j_decompress_ptr cinfo ){ -/* Do computations that are needed before processing a JPEG scan */ -/* cinfo->comps_in_scan and cinfo->cur_comp_info[] were set from SOS marker */ - - int ci, mcublks, tmp; - - jpeg_component_info *compptr; - - - - if ( cinfo->comps_in_scan == 1 ) { - - - - /* Noninterleaved (single-component) scan */ - - compptr = cinfo->cur_comp_info[0]; - - - - /* Overall image size in MCUs */ - - cinfo->MCUs_per_row = compptr->width_in_blocks; - - cinfo->MCU_rows_in_scan = compptr->height_in_blocks; - - - - /* For noninterleaved scan, always one block per MCU */ - - compptr->MCU_width = 1; - - compptr->MCU_height = 1; - - compptr->MCU_blocks = 1; - - compptr->MCU_sample_width = compptr->DCT_scaled_size; - - compptr->last_col_width = 1; - - /* For noninterleaved scans, it is convenient to define last_row_height - - * as the number of block rows present in the last iMCU row. - - */ - - tmp = (int) ( compptr->height_in_blocks % compptr->v_samp_factor ); - - if ( tmp == 0 ) { - tmp = compptr->v_samp_factor; - } - - compptr->last_row_height = tmp; - - - - /* Prepare array describing MCU composition */ - - cinfo->blocks_in_MCU = 1; - - cinfo->MCU_membership[0] = 0; - - - - } - else { - - - - /* Interleaved (multi-component) scan */ - - if ( cinfo->comps_in_scan <= 0 || cinfo->comps_in_scan > MAX_COMPS_IN_SCAN ) { - - ERREXIT2( cinfo, JERR_COMPONENT_COUNT, cinfo->comps_in_scan, - - MAX_COMPS_IN_SCAN ); - } - - - - /* Overall image size in MCUs */ - - cinfo->MCUs_per_row = (JDIMENSION) - - jdiv_round_up( (long) cinfo->image_width, - - (long) ( cinfo->max_h_samp_factor * DCTSIZE ) ); - - cinfo->MCU_rows_in_scan = (JDIMENSION) - - jdiv_round_up( (long) cinfo->image_height, - - (long) ( cinfo->max_v_samp_factor * DCTSIZE ) ); - - - - cinfo->blocks_in_MCU = 0; - - - - for ( ci = 0; ci < cinfo->comps_in_scan; ci++ ) { - - compptr = cinfo->cur_comp_info[ci]; - - /* Sampling factors give # of blocks of component in each MCU */ - - compptr->MCU_width = compptr->h_samp_factor; - - compptr->MCU_height = compptr->v_samp_factor; - - compptr->MCU_blocks = compptr->MCU_width * compptr->MCU_height; - - compptr->MCU_sample_width = compptr->MCU_width * compptr->DCT_scaled_size; - - /* Figure number of non-dummy blocks in last MCU column & row */ - - tmp = (int) ( compptr->width_in_blocks % compptr->MCU_width ); - - if ( tmp == 0 ) { - tmp = compptr->MCU_width; - } - - compptr->last_col_width = tmp; - - tmp = (int) ( compptr->height_in_blocks % compptr->MCU_height ); - - if ( tmp == 0 ) { - tmp = compptr->MCU_height; - } - - compptr->last_row_height = tmp; - - /* Prepare array describing MCU composition */ - - mcublks = compptr->MCU_blocks; - - if ( cinfo->blocks_in_MCU + mcublks > D_MAX_BLOCKS_IN_MCU ) { - - ERREXIT( cinfo, JERR_BAD_MCU_SIZE ); - } - - while ( mcublks-- > 0 ) { - - cinfo->MCU_membership[cinfo->blocks_in_MCU++] = ci; - - } - - } - - - - } - -} - - - - - -/* - - * Save away a copy of the Q-table referenced by each component present - - * in the current scan, unless already saved during a prior scan. - - * - - * In a multiple-scan JPEG file, the encoder could assign different components - - * the same Q-table slot number, but change table definitions between scans - - * so that each component uses a different Q-table. (The IJG encoder is not - - * currently capable of doing this, but other encoders might.) Since we want - - * to be able to dequantize all the components at the end of the file, this - - * means that we have to save away the table actually used for each component. - - * We do this by copying the table at the start of the first scan containing - - * the component. - - * The JPEG spec prohibits the encoder from changing the contents of a Q-table - - * slot between scans of a component using that slot. If the encoder does so - - * anyway, this decoder will simply use the Q-table values that were current - - * at the start of the first scan for the component. - - * - - * The decompressor output side looks only at the saved quant tables, - - * not at the current Q-table slots. - - */ - - - -LOCAL void - -latch_quant_tables( j_decompress_ptr cinfo ){ - - int ci, qtblno; - - jpeg_component_info *compptr; - - JQUANT_TBL * qtbl; - - - - for ( ci = 0; ci < cinfo->comps_in_scan; ci++ ) { - - compptr = cinfo->cur_comp_info[ci]; - - /* No work if we already saved Q-table for this component */ - - if ( compptr->quant_table != NULL ) { - - continue; - } - - /* Make sure specified quantization table is present */ - - qtblno = compptr->quant_tbl_no; - - if ( qtblno < 0 || qtblno >= NUM_QUANT_TBLS || - - cinfo->quant_tbl_ptrs[qtblno] == NULL ) { - - ERREXIT1( cinfo, JERR_NO_QUANT_TABLE, qtblno ); - } - - /* OK, save away the quantization table */ - - qtbl = (JQUANT_TBL *) - - ( *cinfo->mem->alloc_small )( (j_common_ptr) cinfo, JPOOL_IMAGE, - - SIZEOF( JQUANT_TBL ) ); - - MEMCOPY( qtbl, cinfo->quant_tbl_ptrs[qtblno], SIZEOF( JQUANT_TBL ) ); - - compptr->quant_table = qtbl; - - } - -} - - - - - -/* - - * Initialize the input modules to read a scan of compressed data. - - * The first call to this is done by jdmaster.c after initializing - - * the entire decompressor (during jpeg_start_decompress). - - * Subsequent calls come from consume_markers, below. - - */ - - - -METHODDEF void - -start_input_pass( j_decompress_ptr cinfo ){ - - per_scan_setup( cinfo ); - - latch_quant_tables( cinfo ); - - ( *cinfo->entropy->start_pass )( cinfo ); - - ( *cinfo->coef->start_input_pass )( cinfo ); - - cinfo->inputctl->consume_input = cinfo->coef->consume_data; - -} - - - - - -/* - - * Finish up after inputting a compressed-data scan. - - * This is called by the coefficient controller after it's read all - - * the expected data of the scan. - - */ - - - -METHODDEF void - -finish_input_pass( j_decompress_ptr cinfo ){ - - cinfo->inputctl->consume_input = consume_markers; - -} - - - - - -/* - - * Read JPEG markers before, between, or after compressed-data scans. - - * Change state as necessary when a new scan is reached. - - * Return value is JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI. - - * - - * The consume_input method pointer points either here or to the - - * coefficient controller's consume_data routine, depending on whether - - * we are reading a compressed data segment or inter-segment markers. - - */ - - - -METHODDEF int - -consume_markers( j_decompress_ptr cinfo ){ - - my_inputctl_ptr inputctl = (my_inputctl_ptr) cinfo->inputctl; - - int val; - - - - if ( inputctl->pub.eoi_reached ) { /* After hitting EOI, read no further */ - - return JPEG_REACHED_EOI; - } - - - - val = ( *cinfo->marker->read_markers )( cinfo ); - - - - switch ( val ) { - - case JPEG_REACHED_SOS: /* Found SOS */ - - if ( inputctl->inheaders ) { /* 1st SOS */ - - initial_setup( cinfo ); - - inputctl->inheaders = FALSE; - - /* Note: start_input_pass must be called by jdmaster.c - - * before any more input can be consumed. jdapi.c is - - * responsible for enforcing this sequencing. - - */ - - } - else { /* 2nd or later SOS marker */ - - if ( !inputctl->pub.has_multiple_scans ) { - - ERREXIT( cinfo, JERR_EOI_EXPECTED ); /* Oops, I wasn't expecting this! */ - - } - start_input_pass( cinfo ); - - } - - break; - - case JPEG_REACHED_EOI: /* Found EOI */ - - inputctl->pub.eoi_reached = TRUE; - - if ( inputctl->inheaders ) { /* Tables-only datastream, apparently */ - - if ( cinfo->marker->saw_SOF ) { - - ERREXIT( cinfo, JERR_SOF_NO_SOS ); - } - - } - else { - - /* Prevent infinite loop in coef ctlr's decompress_data routine - - * if user set output_scan_number larger than number of scans. - - */ - - if ( cinfo->output_scan_number > cinfo->input_scan_number ) { - - cinfo->output_scan_number = cinfo->input_scan_number; - } - - } - - break; - - case JPEG_SUSPENDED: - - break; - - } - - - - return val; - -} - - - - - -/* - - * Reset state to begin a fresh datastream. - - */ - - - -METHODDEF void - -reset_input_controller( j_decompress_ptr cinfo ){ - - my_inputctl_ptr inputctl = (my_inputctl_ptr) cinfo->inputctl; - - - - inputctl->pub.consume_input = consume_markers; - - inputctl->pub.has_multiple_scans = FALSE; /* "unknown" would be better */ - - inputctl->pub.eoi_reached = FALSE; - - inputctl->inheaders = TRUE; - - /* Reset other modules */ - - ( *cinfo->err->reset_error_mgr )( (j_common_ptr) cinfo ); - - ( *cinfo->marker->reset_marker_reader )( cinfo ); - - /* Reset progression state -- would be cleaner if entropy decoder did this */ - - cinfo->coef_bits = NULL; - -} - - - - - -/* - - * Initialize the input controller module. - - * This is called only once, when the decompression object is created. - - */ - - - -GLOBAL void - -jinit_input_controller( j_decompress_ptr cinfo ){ - - my_inputctl_ptr inputctl; - - - - /* Create subobject in permanent pool */ - - inputctl = (my_inputctl_ptr) - - ( *cinfo->mem->alloc_small )( (j_common_ptr) cinfo, JPOOL_PERMANENT, - - SIZEOF( my_input_controller ) ); - - cinfo->inputctl = (struct jpeg_input_controller *) inputctl; - - /* Initialize method pointers */ - - inputctl->pub.consume_input = consume_markers; - - inputctl->pub.reset_input_controller = reset_input_controller; - - inputctl->pub.start_input_pass = start_input_pass; - - inputctl->pub.finish_input_pass = finish_input_pass; - - /* Initialize state: can't use reset_input_controller since we don't - - * want to try to reset other modules yet. - - */ - - inputctl->pub.has_multiple_scans = FALSE; /* "unknown" would be better */ - - inputctl->pub.eoi_reached = FALSE; - - inputctl->inheaders = TRUE; - -} diff --git a/tools/urt/libs/jpeg6/jdmainct.cpp b/tools/urt/libs/jpeg6/jdmainct.cpp deleted file mode 100644 index ab75325..0000000 --- a/tools/urt/libs/jpeg6/jdmainct.cpp +++ /dev/null @@ -1,1014 +0,0 @@ -/* - - * jdmainct.c - - * - - * Copyright (C) 1994-1995, Thomas G. Lane. - - * This file is part of the Independent JPEG Group's software. - - * For conditions of distribution and use, see the accompanying README file. - - * - - * This file contains the main buffer controller for decompression. - - * The main buffer lies between the JPEG decompressor proper and the - - * post-processor; it holds downsampled data in the JPEG colorspace. - - * - - * Note that this code is bypassed in raw-data mode, since the application - - * supplies the equivalent of the main buffer in that case. - - */ - - - -#define JPEG_INTERNALS - -#include "jinclude.h" - -#include "radiant_jpeglib.h" - - - - - -/* - - * In the current system design, the main buffer need never be a full-image - - * buffer; any full-height buffers will be found inside the coefficient or - - * postprocessing controllers. Nonetheless, the main controller is not - - * trivial. Its responsibility is to provide context rows for upsampling/ - - * rescaling, and doing this in an efficient fashion is a bit tricky. - - * - - * Postprocessor input data is counted in "row groups". A row group - - * is defined to be (v_samp_factor * DCT_scaled_size / min_DCT_scaled_size) - - * sample rows of each component. (We require DCT_scaled_size values to be - - * chosen such that these numbers are integers. In practice DCT_scaled_size - - * values will likely be powers of two, so we actually have the stronger - - * condition that DCT_scaled_size / min_DCT_scaled_size is an integer.) - - * Upsampling will typically produce max_v_samp_factor pixel rows from each - - * row group (times any additional scale factor that the upsampler is - - * applying). - - * - - * The coefficient controller will deliver data to us one iMCU row at a time; - - * each iMCU row contains v_samp_factor * DCT_scaled_size sample rows, or - - * exactly min_DCT_scaled_size row groups. (This amount of data corresponds - - * to one row of MCUs when the image is fully interleaved.) Note that the - - * number of sample rows varies across components, but the number of row - - * groups does not. Some garbage sample rows may be included in the last iMCU - - * row at the bottom of the image. - - * - - * Depending on the vertical scaling algorithm used, the upsampler may need - - * access to the sample row(s) above and below its current input row group. - - * The upsampler is required to set need_context_rows TRUE at global selection - - * time if so. When need_context_rows is FALSE, this controller can simply - - * obtain one iMCU row at a time from the coefficient controller and dole it - - * out as row groups to the postprocessor. - - * - - * When need_context_rows is TRUE, this controller guarantees that the buffer - - * passed to postprocessing contains at least one row group's worth of samples - - * above and below the row group(s) being processed. Note that the context - - * rows "above" the first passed row group appear at negative row offsets in - - * the passed buffer. At the top and bottom of the image, the required - - * context rows are manufactured by duplicating the first or last real sample - - * row; this avoids having special cases in the upsampling inner loops. - - * - - * The amount of context is fixed at one row group just because that's a - - * convenient number for this controller to work with. The existing - - * upsamplers really only need one sample row of context. An upsampler - - * supporting arbitrary output rescaling might wish for more than one row - - * group of context when shrinking the image; tough, we don't handle that. - - * (This is justified by the assumption that downsizing will be handled mostly - - * by adjusting the DCT_scaled_size values, so that the actual scale factor at - - * the upsample step needn't be much less than one.) - - * - - * To provide the desired context, we have to retain the last two row groups - - * of one iMCU row while reading in the next iMCU row. (The last row group - - * can't be processed until we have another row group for its below-context, - - * and so we have to save the next-to-last group too for its above-context.) - - * We could do this most simply by copying data around in our buffer, but - - * that'd be very slow. We can avoid copying any data by creating a rather - - * strange pointer structure. Here's how it works. We allocate a workspace - - * consisting of M+2 row groups (where M = min_DCT_scaled_size is the number - - * of row groups per iMCU row). We create two sets of redundant pointers to - - * the workspace. Labeling the physical row groups 0 to M+1, the synthesized - - * pointer lists look like this: - - * M+1 M-1 - - * master pointer --> 0 master pointer --> 0 - - * 1 1 - - * ... ... - - * M-3 M-3 - - * M-2 M - - * M-1 M+1 - - * M M-2 - - * M+1 M-1 - - * 0 0 - - * We read alternate iMCU rows using each master pointer; thus the last two - - * row groups of the previous iMCU row remain un-overwritten in the workspace. - - * The pointer lists are set up so that the required context rows appear to - - * be adjacent to the proper places when we pass the pointer lists to the - - * upsampler. - - * - - * The above pictures describe the normal state of the pointer lists. - - * At top and bottom of the image, we diddle the pointer lists to duplicate - - * the first or last sample row as necessary (this is cheaper than copying - - * sample rows around). - - * - - * This scheme breaks down if M < 2, ie, min_DCT_scaled_size is 1. In that - - * situation each iMCU row provides only one row group so the buffering logic - - * must be different (eg, we must read two iMCU rows before we can emit the - - * first row group). For now, we simply do not support providing context - - * rows when min_DCT_scaled_size is 1. That combination seems unlikely to - - * be worth providing --- if someone wants a 1/8th-size preview, they probably - - * want it quick and dirty, so a context-free upsampler is sufficient. - - */ - - - - - -/* Private buffer controller object */ - - - -typedef struct { - - struct jpeg_d_main_controller pub; /* public fields */ - - - - /* Pointer to allocated workspace (M or M+2 row groups). */ - - JSAMPARRAY buffer[MAX_COMPONENTS]; - - - - boolean buffer_full; /* Have we gotten an iMCU row from decoder? */ - - JDIMENSION rowgroup_ctr; /* counts row groups output to postprocessor */ - - - - /* Remaining fields are only used in the context case. */ - - - - /* These are the master pointers to the funny-order pointer lists. */ - - JSAMPIMAGE xbuffer[2]; /* pointers to weird pointer lists */ - - - - int whichptr; /* indicates which pointer set is now in use */ - - int context_state; /* process_data state machine status */ - - JDIMENSION rowgroups_avail; /* row groups available to postprocessor */ - - JDIMENSION iMCU_row_ctr; /* counts iMCU rows to detect image top/bot */ - -} my_main_controller; - - - -typedef my_main_controller * my_main_ptr; - - - -/* context_state values: */ - -#define CTX_PREPARE_FOR_IMCU 0 /* need to prepare for MCU row */ - -#define CTX_PROCESS_IMCU 1 /* feeding iMCU to postprocessor */ - -#define CTX_POSTPONED_ROW 2 /* feeding postponed row group */ - - - - - -/* Forward declarations */ - -METHODDEF void process_data_simple_main - -JPP( ( j_decompress_ptr cinfo, JSAMPARRAY output_buf, - - JDIMENSION * out_row_ctr, JDIMENSION out_rows_avail ) ); - -METHODDEF void process_data_context_main - -JPP( ( j_decompress_ptr cinfo, JSAMPARRAY output_buf, - - JDIMENSION * out_row_ctr, JDIMENSION out_rows_avail ) ); - -#ifdef QUANT_2PASS_SUPPORTED - -METHODDEF void process_data_crank_post - -JPP( ( j_decompress_ptr cinfo, JSAMPARRAY output_buf, - - JDIMENSION * out_row_ctr, JDIMENSION out_rows_avail ) ); - -#endif - - - - - -LOCAL void - -alloc_funny_pointers( j_decompress_ptr cinfo ){ -/* Allocate space for the funny pointer lists. - - * This is done only once, not once per pass. - - */ - - my_main_ptr main = (my_main_ptr) cinfo->main; - - int ci, rgroup; - - int M = cinfo->min_DCT_scaled_size; - - jpeg_component_info *compptr; - - JSAMPARRAY xbuf; - - - - /* Get top-level space for component array pointers. - - * We alloc both arrays with one call to save a few cycles. - - */ - - main->xbuffer[0] = (JSAMPIMAGE) - - ( *cinfo->mem->alloc_small )( (j_common_ptr) cinfo, JPOOL_IMAGE, - - cinfo->num_components * 2 * SIZEOF( JSAMPARRAY ) ); - - main->xbuffer[1] = main->xbuffer[0] + cinfo->num_components; - - - - for ( ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components; - - ci++, compptr++ ) { - - rgroup = ( compptr->v_samp_factor * compptr->DCT_scaled_size ) / - - cinfo->min_DCT_scaled_size; /* height of a row group of component */ - - /* Get space for pointer lists --- M+4 row groups in each list. - - * We alloc both pointer lists with one call to save a few cycles. - - */ - - xbuf = (JSAMPARRAY) - - ( *cinfo->mem->alloc_small )( (j_common_ptr) cinfo, JPOOL_IMAGE, - - 2 * ( rgroup * ( M + 4 ) ) * SIZEOF( JSAMPROW ) ); - - xbuf += rgroup; /* want one row group at negative offsets */ - - main->xbuffer[0][ci] = xbuf; - - xbuf += rgroup * ( M + 4 ); - - main->xbuffer[1][ci] = xbuf; - - } - -} - - - - - -LOCAL void - -make_funny_pointers( j_decompress_ptr cinfo ){ -/* Create the funny pointer lists discussed in the comments above. - - * The actual workspace is already allocated (in main->buffer), - - * and the space for the pointer lists is allocated too. - - * This routine just fills in the curiously ordered lists. - - * This will be repeated at the beginning of each pass. - - */ - - my_main_ptr main = (my_main_ptr) cinfo->main; - - int ci, i, rgroup; - - int M = cinfo->min_DCT_scaled_size; - - jpeg_component_info *compptr; - - JSAMPARRAY buf, xbuf0, xbuf1; - - - - for ( ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components; - - ci++, compptr++ ) { - - rgroup = ( compptr->v_samp_factor * compptr->DCT_scaled_size ) / - - cinfo->min_DCT_scaled_size; /* height of a row group of component */ - - xbuf0 = main->xbuffer[0][ci]; - - xbuf1 = main->xbuffer[1][ci]; - - /* First copy the workspace pointers as-is */ - - buf = main->buffer[ci]; - - for ( i = 0; i < rgroup * ( M + 2 ); i++ ) { - - xbuf0[i] = xbuf1[i] = buf[i]; - - } - - /* In the second list, put the last four row groups in swapped order */ - - for ( i = 0; i < rgroup * 2; i++ ) { - - xbuf1[rgroup * ( M - 2 ) + i] = buf[rgroup * M + i]; - - xbuf1[rgroup * M + i] = buf[rgroup * ( M - 2 ) + i]; - - } - - /* The wraparound pointers at top and bottom will be filled later - - * (see set_wraparound_pointers, below). Initially we want the "above" - - * pointers to duplicate the first actual data line. This only needs - - * to happen in xbuffer[0]. - - */ - - for ( i = 0; i < rgroup; i++ ) { - - xbuf0[i - rgroup] = xbuf0[0]; - - } - - } - -} - - - - - -LOCAL void - -set_wraparound_pointers( j_decompress_ptr cinfo ){ -/* Set up the "wraparound" pointers at top and bottom of the pointer lists. - - * This changes the pointer list state from top-of-image to the normal state. - - */ - - my_main_ptr main = (my_main_ptr) cinfo->main; - - int ci, i, rgroup; - - int M = cinfo->min_DCT_scaled_size; - - jpeg_component_info *compptr; - - JSAMPARRAY xbuf0, xbuf1; - - - - for ( ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components; - - ci++, compptr++ ) { - - rgroup = ( compptr->v_samp_factor * compptr->DCT_scaled_size ) / - - cinfo->min_DCT_scaled_size; /* height of a row group of component */ - - xbuf0 = main->xbuffer[0][ci]; - - xbuf1 = main->xbuffer[1][ci]; - - for ( i = 0; i < rgroup; i++ ) { - - xbuf0[i - rgroup] = xbuf0[rgroup * ( M + 1 ) + i]; - - xbuf1[i - rgroup] = xbuf1[rgroup * ( M + 1 ) + i]; - - xbuf0[rgroup * ( M + 2 ) + i] = xbuf0[i]; - - xbuf1[rgroup * ( M + 2 ) + i] = xbuf1[i]; - - } - - } - -} - - - - - -LOCAL void - -set_bottom_pointers( j_decompress_ptr cinfo ){ -/* Change the pointer lists to duplicate the last sample row at the bottom - - * of the image. whichptr indicates which xbuffer holds the final iMCU row. - - * Also sets rowgroups_avail to indicate number of nondummy row groups in row. - - */ - - my_main_ptr main = (my_main_ptr) cinfo->main; - - int ci, i, rgroup, iMCUheight, rows_left; - - jpeg_component_info *compptr; - - JSAMPARRAY xbuf; - - - - for ( ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components; - - ci++, compptr++ ) { - - /* Count sample rows in one iMCU row and in one row group */ - - iMCUheight = compptr->v_samp_factor * compptr->DCT_scaled_size; - - rgroup = iMCUheight / cinfo->min_DCT_scaled_size; - - /* Count nondummy sample rows remaining for this component */ - - rows_left = (int) ( compptr->downsampled_height % (JDIMENSION) iMCUheight ); - - if ( rows_left == 0 ) { - rows_left = iMCUheight; - } - - /* Count nondummy row groups. Should get same answer for each component, - - * so we need only do it once. - - */ - - if ( ci == 0 ) { - - main->rowgroups_avail = (JDIMENSION) ( ( rows_left - 1 ) / rgroup + 1 ); - - } - - /* Duplicate the last real sample row rgroup*2 times; this pads out the - - * last partial rowgroup and ensures at least one full rowgroup of context. - - */ - - xbuf = main->xbuffer[main->whichptr][ci]; - - for ( i = 0; i < rgroup * 2; i++ ) { - - xbuf[rows_left + i] = xbuf[rows_left - 1]; - - } - - } - -} - - - - - -/* - - * Initialize for a processing pass. - - */ - - - -METHODDEF void - -start_pass_main( j_decompress_ptr cinfo, J_BUF_MODE pass_mode ){ - - my_main_ptr main = (my_main_ptr) cinfo->main; - - - - switch ( pass_mode ) { - - case JBUF_PASS_THRU: - - if ( cinfo->upsample->need_context_rows ) { - - main->pub.process_data = process_data_context_main; - - make_funny_pointers( cinfo ); /* Create the xbuffer[] lists */ - - main->whichptr = 0; /* Read first iMCU row into xbuffer[0] */ - - main->context_state = CTX_PREPARE_FOR_IMCU; - - main->iMCU_row_ctr = 0; - - } - else { - - /* Simple case with no context needed */ - - main->pub.process_data = process_data_simple_main; - - } - - main->buffer_full = FALSE; /* Mark buffer empty */ - - main->rowgroup_ctr = 0; - - break; - -#ifdef QUANT_2PASS_SUPPORTED - - case JBUF_CRANK_DEST: - - /* For last pass of 2-pass quantization, just crank the postprocessor */ - - main->pub.process_data = process_data_crank_post; - - break; - -#endif - - default: - - ERREXIT( cinfo, JERR_BAD_BUFFER_MODE ); - - break; - - } - -} - - - - - -/* - - * Process some data. - - * This handles the simple case where no context is required. - - */ - - - -METHODDEF void - -process_data_simple_main( j_decompress_ptr cinfo, - - JSAMPARRAY output_buf, JDIMENSION *out_row_ctr, - - JDIMENSION out_rows_avail ){ - - my_main_ptr main = (my_main_ptr) cinfo->main; - - JDIMENSION rowgroups_avail; - - - - /* Read input data if we haven't filled the main buffer yet */ - - if ( !main->buffer_full ) { - - if ( !( *cinfo->coef->decompress_data )( cinfo, main->buffer ) ) { - - return; /* suspension forced, can do nothing more */ - - } - main->buffer_full = TRUE; /* OK, we have an iMCU row to work with */ - - } - - - - /* There are always min_DCT_scaled_size row groups in an iMCU row. */ - - rowgroups_avail = (JDIMENSION) cinfo->min_DCT_scaled_size; - - /* Note: at the bottom of the image, we may pass extra garbage row groups - - * to the postprocessor. The postprocessor has to check for bottom - - * of image anyway (at row resolution), so no point in us doing it too. - - */ - - - - /* Feed the postprocessor */ - - ( *cinfo->post->post_process_data )( cinfo, main->buffer, - - &main->rowgroup_ctr, rowgroups_avail, - - output_buf, out_row_ctr, out_rows_avail ); - - - - /* Has postprocessor consumed all the data yet? If so, mark buffer empty */ - - if ( main->rowgroup_ctr >= rowgroups_avail ) { - - main->buffer_full = FALSE; - - main->rowgroup_ctr = 0; - - } - -} - - - - - -/* - - * Process some data. - - * This handles the case where context rows must be provided. - - */ - - - -METHODDEF void - -process_data_context_main( j_decompress_ptr cinfo, - - JSAMPARRAY output_buf, JDIMENSION *out_row_ctr, - - JDIMENSION out_rows_avail ){ - - my_main_ptr main = (my_main_ptr) cinfo->main; - - - - /* Read input data if we haven't filled the main buffer yet */ - - if ( !main->buffer_full ) { - - if ( !( *cinfo->coef->decompress_data )( cinfo, - - main->xbuffer[main->whichptr] ) ) { - - return; /* suspension forced, can do nothing more */ - - } - main->buffer_full = TRUE; /* OK, we have an iMCU row to work with */ - - main->iMCU_row_ctr++; /* count rows received */ - - } - - - - /* Postprocessor typically will not swallow all the input data it is handed - - * in one call (due to filling the output buffer first). Must be prepared - - * to exit and restart. This switch lets us keep track of how far we got. - - * Note that each case falls through to the next on successful completion. - - */ - - switch ( main->context_state ) { - - case CTX_POSTPONED_ROW: - - /* Call postprocessor using previously set pointers for postponed row */ - - ( *cinfo->post->post_process_data )( cinfo, main->xbuffer[main->whichptr], - - &main->rowgroup_ctr, main->rowgroups_avail, - - output_buf, out_row_ctr, out_rows_avail ); - - if ( main->rowgroup_ctr < main->rowgroups_avail ) { - - return; /* Need to suspend */ - - } - main->context_state = CTX_PREPARE_FOR_IMCU; - - if ( *out_row_ctr >= out_rows_avail ) { - - return; /* Postprocessor exactly filled output buf */ - - } - /*FALLTHROUGH*/ - - case CTX_PREPARE_FOR_IMCU: - - /* Prepare to process first M-1 row groups of this iMCU row */ - - main->rowgroup_ctr = 0; - - main->rowgroups_avail = (JDIMENSION) ( cinfo->min_DCT_scaled_size - 1 ); - - /* Check for bottom of image: if so, tweak pointers to "duplicate" - - * the last sample row, and adjust rowgroups_avail to ignore padding rows. - - */ - - if ( main->iMCU_row_ctr == cinfo->total_iMCU_rows ) { - - set_bottom_pointers( cinfo ); - } - - main->context_state = CTX_PROCESS_IMCU; - - /*FALLTHROUGH*/ - - case CTX_PROCESS_IMCU: - - /* Call postprocessor using previously set pointers */ - - ( *cinfo->post->post_process_data )( cinfo, main->xbuffer[main->whichptr], - - &main->rowgroup_ctr, main->rowgroups_avail, - - output_buf, out_row_ctr, out_rows_avail ); - - if ( main->rowgroup_ctr < main->rowgroups_avail ) { - - return; /* Need to suspend */ - - } - /* After the first iMCU, change wraparound pointers to normal state */ - - if ( main->iMCU_row_ctr == 1 ) { - - set_wraparound_pointers( cinfo ); - } - - /* Prepare to load new iMCU row using other xbuffer list */ - - main->whichptr ^= 1; /* 0=>1 or 1=>0 */ - - main->buffer_full = FALSE; - - /* Still need to process last row group of this iMCU row, */ - - /* which is saved at index M+1 of the other xbuffer */ - - main->rowgroup_ctr = (JDIMENSION) ( cinfo->min_DCT_scaled_size + 1 ); - - main->rowgroups_avail = (JDIMENSION) ( cinfo->min_DCT_scaled_size + 2 ); - - main->context_state = CTX_POSTPONED_ROW; - - } - -} - - - - - -/* - - * Process some data. - - * Final pass of two-pass quantization: just call the postprocessor. - - * Source data will be the postprocessor controller's internal buffer. - - */ - - - -#ifdef QUANT_2PASS_SUPPORTED - - - -METHODDEF void - -process_data_crank_post( j_decompress_ptr cinfo, - - JSAMPARRAY output_buf, JDIMENSION *out_row_ctr, - - JDIMENSION out_rows_avail ){ - - ( *cinfo->post->post_process_data )( cinfo, (JSAMPIMAGE) NULL, - - (JDIMENSION *) NULL, (JDIMENSION) 0, - - output_buf, out_row_ctr, out_rows_avail ); - -} - - - -#endif /* QUANT_2PASS_SUPPORTED */ - - - - - -/* - - * Initialize main buffer controller. - - */ - - - -GLOBAL void - -jinit_d_main_controller( j_decompress_ptr cinfo, boolean need_full_buffer ){ - - my_main_ptr main; - - int ci, rgroup, ngroups; - - jpeg_component_info *compptr; - - - - main = (my_main_ptr) - - ( *cinfo->mem->alloc_small )( (j_common_ptr) cinfo, JPOOL_IMAGE, - - SIZEOF( my_main_controller ) ); - - cinfo->main = (struct jpeg_d_main_controller *) main; - - main->pub.start_pass = start_pass_main; - - - - if ( need_full_buffer ) { /* shouldn't happen */ - - ERREXIT( cinfo, JERR_BAD_BUFFER_MODE ); - } - - - - /* Allocate the workspace. - - * ngroups is the number of row groups we need. - - */ - - if ( cinfo->upsample->need_context_rows ) { - - if ( cinfo->min_DCT_scaled_size < 2 ) { /* unsupported, see comments above */ - - ERREXIT( cinfo, JERR_NOTIMPL ); - } - - alloc_funny_pointers( cinfo ); /* Alloc space for xbuffer[] lists */ - - ngroups = cinfo->min_DCT_scaled_size + 2; - - } - else { - - ngroups = cinfo->min_DCT_scaled_size; - - } - - - - for ( ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components; - - ci++, compptr++ ) { - - rgroup = ( compptr->v_samp_factor * compptr->DCT_scaled_size ) / - - cinfo->min_DCT_scaled_size; /* height of a row group of component */ - - main->buffer[ci] = ( *cinfo->mem->alloc_sarray ) - - ( (j_common_ptr) cinfo, JPOOL_IMAGE, - - compptr->width_in_blocks * compptr->DCT_scaled_size, - - (JDIMENSION) ( rgroup * ngroups ) ); - - } - -} diff --git a/tools/urt/libs/jpeg6/jdmarker.cpp b/tools/urt/libs/jpeg6/jdmarker.cpp deleted file mode 100644 index 8d5bb88..0000000 --- a/tools/urt/libs/jpeg6/jdmarker.cpp +++ /dev/null @@ -1,1094 +0,0 @@ -/* - * jdmarker.c - * - * Copyright (C) 1991-1995, Thomas G. Lane. - * This file is part of the Independent JPEG Group's software. - * For conditions of distribution and use, see the accompanying README file. - * - * This file contains routines to decode JPEG datastream markers. - * Most of the complexity arises from our desire to support input - * suspension: if not all of the data for a marker is available, - * we must exit back to the application. On resumption, we reprocess - * the marker. - */ - -#define JPEG_INTERNALS -#include "jinclude.h" -#include "radiant_jpeglib.h" - - -typedef enum { /* JPEG marker codes */ - M_SOF0 = 0xc0, - M_SOF1 = 0xc1, - M_SOF2 = 0xc2, - M_SOF3 = 0xc3, - - M_SOF5 = 0xc5, - M_SOF6 = 0xc6, - M_SOF7 = 0xc7, - - M_JPG = 0xc8, - M_SOF9 = 0xc9, - M_SOF10 = 0xca, - M_SOF11 = 0xcb, - - M_SOF13 = 0xcd, - M_SOF14 = 0xce, - M_SOF15 = 0xcf, - - M_DHT = 0xc4, - - M_DAC = 0xcc, - - M_RST0 = 0xd0, - M_RST1 = 0xd1, - M_RST2 = 0xd2, - M_RST3 = 0xd3, - M_RST4 = 0xd4, - M_RST5 = 0xd5, - M_RST6 = 0xd6, - M_RST7 = 0xd7, - - M_SOI = 0xd8, - M_EOI = 0xd9, - M_SOS = 0xda, - M_DQT = 0xdb, - M_DNL = 0xdc, - M_DRI = 0xdd, - M_DHP = 0xde, - M_EXP = 0xdf, - - M_APP0 = 0xe0, - M_APP1 = 0xe1, - M_APP2 = 0xe2, - M_APP3 = 0xe3, - M_APP4 = 0xe4, - M_APP5 = 0xe5, - M_APP6 = 0xe6, - M_APP7 = 0xe7, - M_APP8 = 0xe8, - M_APP9 = 0xe9, - M_APP10 = 0xea, - M_APP11 = 0xeb, - M_APP12 = 0xec, - M_APP13 = 0xed, - M_APP14 = 0xee, - M_APP15 = 0xef, - - M_JPG0 = 0xf0, - M_JPG13 = 0xfd, - M_COM = 0xfe, - - M_TEM = 0x01, - - M_ERROR = 0x100 -} JPEG_MARKER; - - -/* - * Macros for fetching data from the data source module. - * - * At all times, cinfo->src->next_input_byte and ->bytes_in_buffer reflect - * the current restart point; we update them only when we have reached a - * suitable place to restart if a suspension occurs. - */ - -/* Declare and initialize local copies of input pointer/count */ -#define INPUT_VARS( cinfo ) \ - struct jpeg_source_mgr * datasrc = ( cinfo )->src; \ - const JOCTET * next_input_byte = datasrc->next_input_byte; \ - size_t bytes_in_buffer = datasrc->bytes_in_buffer - -/* Unload the local copies --- do this only at a restart boundary */ -#define INPUT_SYNC( cinfo ) \ - ( datasrc->next_input_byte = next_input_byte, \ - datasrc->bytes_in_buffer = bytes_in_buffer ) - -/* Reload the local copies --- seldom used except in MAKE_BYTE_AVAIL */ -#define INPUT_RELOAD( cinfo ) \ - ( next_input_byte = datasrc->next_input_byte, \ - bytes_in_buffer = datasrc->bytes_in_buffer ) - -/* Internal macro for INPUT_BYTE and INPUT_2BYTES: make a byte available. - * Note we do *not* do INPUT_SYNC before calling fill_input_buffer, - * but we must reload the local copies after a successful fill. - */ -#define MAKE_BYTE_AVAIL( cinfo,action ) \ - if ( bytes_in_buffer == 0 ) { \ - if ( !( *datasrc->fill_input_buffer )( cinfo ) ) \ - { action; } \ - INPUT_RELOAD( cinfo ); \ - } \ - bytes_in_buffer-- - -/* Read a byte into variable V. - * If must suspend, take the specified action (typically "return FALSE"). - */ -#define INPUT_BYTE( cinfo,V,action ) \ - MAKESTMT( MAKE_BYTE_AVAIL( cinfo,action ); \ - V = GETJOCTET( *next_input_byte++ ); ) - -/* As above, but read two bytes interpreted as an unsigned 16-bit integer. - * V should be declared unsigned int or perhaps INT32. - */ -#define INPUT_2BYTES( cinfo,V,action ) \ - MAKESTMT( MAKE_BYTE_AVAIL( cinfo,action ); \ - V = ( (unsigned int) GETJOCTET( *next_input_byte++ ) ) << 8; \ - MAKE_BYTE_AVAIL( cinfo,action ); \ - V += GETJOCTET( *next_input_byte++ ); ) - - -/* - * Routines to process JPEG markers. - * - * Entry condition: JPEG marker itself has been read and its code saved - * in cinfo->unread_marker; input restart point is just after the marker. - * - * Exit: if return TRUE, have read and processed any parameters, and have - * updated the restart point to point after the parameters. - * If return FALSE, was forced to suspend before reaching end of - * marker parameters; restart point has not been moved. Same routine - * will be called again after application supplies more input data. - * - * This approach to suspension assumes that all of a marker's parameters can - * fit into a single input bufferload. This should hold for "normal" - * markers. Some COM/APPn markers might have large parameter segments, - * but we use skip_input_data to get past those, and thereby put the problem - * on the source manager's shoulders. - * - * Note that we don't bother to avoid duplicate trace messages if a - * suspension occurs within marker parameters. Other side effects - * require more care. - */ - - -LOCAL boolean -get_soi( j_decompress_ptr cinfo ){ -/* Process an SOI marker */ - int i; - - TRACEMS( cinfo, 1, JTRC_SOI ); - - if ( cinfo->marker->saw_SOI ) { - ERREXIT( cinfo, JERR_SOI_DUPLICATE ); - } - - /* Reset all parameters that are defined to be reset by SOI */ - - for ( i = 0; i < NUM_ARITH_TBLS; i++ ) { - cinfo->arith_dc_L[i] = 0; - cinfo->arith_dc_U[i] = 1; - cinfo->arith_ac_K[i] = 5; - } - cinfo->restart_interval = 0; - - /* Set initial assumptions for colorspace etc */ - - cinfo->jpeg_color_space = JCS_UNKNOWN; - cinfo->CCIR601_sampling = FALSE; /* Assume non-CCIR sampling??? */ - - cinfo->saw_JFIF_marker = FALSE; - cinfo->density_unit = 0; /* set default JFIF APP0 values */ - cinfo->X_density = 1; - cinfo->Y_density = 1; - cinfo->saw_Adobe_marker = FALSE; - cinfo->Adobe_transform = 0; - - cinfo->marker->saw_SOI = TRUE; - - return TRUE; -} - - -LOCAL boolean -get_sof( j_decompress_ptr cinfo, boolean is_prog, boolean is_arith ){ -/* Process a SOFn marker */ - INT32 length; - int c, ci; - jpeg_component_info * compptr; - INPUT_VARS( cinfo ); - - cinfo->progressive_mode = is_prog; - cinfo->arith_code = is_arith; - - INPUT_2BYTES( cinfo, length, return FALSE ); - - INPUT_BYTE( cinfo, cinfo->data_precision, return FALSE ); - INPUT_2BYTES( cinfo, cinfo->image_height, return FALSE ); - INPUT_2BYTES( cinfo, cinfo->image_width, return FALSE ); - INPUT_BYTE( cinfo, cinfo->num_components, return FALSE ); - - length -= 8; - - TRACEMS4( cinfo, 1, JTRC_SOF, cinfo->unread_marker, - (int) cinfo->image_width, (int) cinfo->image_height, - cinfo->num_components ); - - if ( cinfo->marker->saw_SOF ) { - ERREXIT( cinfo, JERR_SOF_DUPLICATE ); - } - - /* We don't support files in which the image height is initially specified */ - /* as 0 and is later redefined by DNL. As long as we have to check that, */ - /* might as well have a general sanity check. */ - if ( cinfo->image_height <= 0 || cinfo->image_width <= 0 - || cinfo->num_components <= 0 ) { - ERREXIT( cinfo, JERR_EMPTY_IMAGE ); - } - - if ( length != ( cinfo->num_components * 3 ) ) { - ERREXIT( cinfo, JERR_BAD_LENGTH ); - } - - if ( cinfo->comp_info == NULL ) { /* do only once, even if suspend */ - cinfo->comp_info = (jpeg_component_info *) ( *cinfo->mem->alloc_small ) - ( (j_common_ptr) cinfo, JPOOL_IMAGE, - cinfo->num_components * SIZEOF( jpeg_component_info ) ); - } - - for ( ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components; - ci++, compptr++ ) { - compptr->component_index = ci; - INPUT_BYTE( cinfo, compptr->component_id, return FALSE ); - INPUT_BYTE( cinfo, c, return FALSE ); - compptr->h_samp_factor = ( c >> 4 ) & 15; - compptr->v_samp_factor = ( c ) & 15; - INPUT_BYTE( cinfo, compptr->quant_tbl_no, return FALSE ); - - TRACEMS4( cinfo, 1, JTRC_SOF_COMPONENT, - compptr->component_id, compptr->h_samp_factor, - compptr->v_samp_factor, compptr->quant_tbl_no ); - } - - cinfo->marker->saw_SOF = TRUE; - - INPUT_SYNC( cinfo ); - return TRUE; -} - - -LOCAL boolean -get_sos( j_decompress_ptr cinfo ){ -/* Process a SOS marker */ - INT32 length; - int i, ci, n, c, cc; - jpeg_component_info * compptr; - INPUT_VARS( cinfo ); - - if ( !cinfo->marker->saw_SOF ) { - ERREXIT( cinfo, JERR_SOS_NO_SOF ); - } - - INPUT_2BYTES( cinfo, length, return FALSE ); - - INPUT_BYTE( cinfo, n, return FALSE ); /* Number of components */ - - if ( length != ( n * 2 + 6 ) || n < 1 || n > MAX_COMPS_IN_SCAN ) { - ERREXIT( cinfo, JERR_BAD_LENGTH ); - } - - TRACEMS1( cinfo, 1, JTRC_SOS, n ); - - cinfo->comps_in_scan = n; - - /* Collect the component-spec parameters */ - - for ( i = 0; i < n; i++ ) { - INPUT_BYTE( cinfo, cc, return FALSE ); - INPUT_BYTE( cinfo, c, return FALSE ); - - for ( ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components; - ci++, compptr++ ) { - if ( cc == compptr->component_id ) { - goto id_found; - } - } - - ERREXIT1( cinfo, JERR_BAD_COMPONENT_ID, cc ); - -id_found: - - cinfo->cur_comp_info[i] = compptr; - compptr->dc_tbl_no = ( c >> 4 ) & 15; - compptr->ac_tbl_no = ( c ) & 15; - - TRACEMS3( cinfo, 1, JTRC_SOS_COMPONENT, cc, - compptr->dc_tbl_no, compptr->ac_tbl_no ); - } - - /* Collect the additional scan parameters Ss, Se, Ah/Al. */ - INPUT_BYTE( cinfo, c, return FALSE ); - cinfo->Ss = c; - INPUT_BYTE( cinfo, c, return FALSE ); - cinfo->Se = c; - INPUT_BYTE( cinfo, c, return FALSE ); - cinfo->Ah = ( c >> 4 ) & 15; - cinfo->Al = ( c ) & 15; - - TRACEMS4( cinfo, 1, JTRC_SOS_PARAMS, cinfo->Ss, cinfo->Se, - cinfo->Ah, cinfo->Al ); - - /* Prepare to scan data & restart markers */ - cinfo->marker->next_restart_num = 0; - - /* Count another SOS marker */ - cinfo->input_scan_number++; - - INPUT_SYNC( cinfo ); - return TRUE; -} - - -METHODDEF boolean -get_app0( j_decompress_ptr cinfo ){ -/* Process an APP0 marker */ -#define JFIF_LEN 14 - INT32 length; - UINT8 b[JFIF_LEN]; - int buffp; - INPUT_VARS( cinfo ); - - INPUT_2BYTES( cinfo, length, return FALSE ); - length -= 2; - - /* See if a JFIF APP0 marker is present */ - - if ( length >= JFIF_LEN ) { - for ( buffp = 0; buffp < JFIF_LEN; buffp++ ) - INPUT_BYTE( cinfo, b[buffp], return FALSE ); - length -= JFIF_LEN; - - if ( b[0] == 0x4A && b[1] == 0x46 && b[2] == 0x49 && b[3] == 0x46 && b[4] == 0 ) { - /* Found JFIF APP0 marker: check version */ - /* Major version must be 1, anything else signals an incompatible change. - * We used to treat this as an error, but now it's a nonfatal warning, - * because some bozo at Hijaak couldn't read the spec. - * Minor version should be 0..2, but process anyway if newer. - */ - if ( b[5] != 1 ) { - WARNMS2( cinfo, JWRN_JFIF_MAJOR, b[5], b[6] ); - } - else if ( b[6] > 2 ) { - TRACEMS2( cinfo, 1, JTRC_JFIF_MINOR, b[5], b[6] ); - } - /* Save info */ - cinfo->saw_JFIF_marker = TRUE; - cinfo->density_unit = b[7]; - cinfo->X_density = ( b[8] << 8 ) + b[9]; - cinfo->Y_density = ( b[10] << 8 ) + b[11]; - TRACEMS3( cinfo, 1, JTRC_JFIF, - cinfo->X_density, cinfo->Y_density, cinfo->density_unit ); - if ( b[12] | b[13] ) { - TRACEMS2( cinfo, 1, JTRC_JFIF_THUMBNAIL, b[12], b[13] ); - } - if ( length != ( (INT32) b[12] * (INT32) b[13] * (INT32) 3 ) ) { - TRACEMS1( cinfo, 1, JTRC_JFIF_BADTHUMBNAILSIZE, (int) length ); - } - } - else { - /* Start of APP0 does not match "JFIF" */ - TRACEMS1( cinfo, 1, JTRC_APP0, (int) length + JFIF_LEN ); - } - } - else { - /* Too short to be JFIF marker */ - TRACEMS1( cinfo, 1, JTRC_APP0, (int) length ); - } - - INPUT_SYNC( cinfo ); - if ( length > 0 ) { /* skip any remaining data -- could be lots */ - ( *cinfo->src->skip_input_data )( cinfo, (long) length ); - } - - return TRUE; -} - - -METHODDEF boolean -get_app14( j_decompress_ptr cinfo ){ -/* Process an APP14 marker */ -#define ADOBE_LEN 12 - INT32 length; - UINT8 b[ADOBE_LEN]; - int buffp; - unsigned int version, flags0, flags1, transform; - INPUT_VARS( cinfo ); - - INPUT_2BYTES( cinfo, length, return FALSE ); - length -= 2; - - /* See if an Adobe APP14 marker is present */ - - if ( length >= ADOBE_LEN ) { - for ( buffp = 0; buffp < ADOBE_LEN; buffp++ ) - INPUT_BYTE( cinfo, b[buffp], return FALSE ); - length -= ADOBE_LEN; - - if ( b[0] == 0x41 && b[1] == 0x64 && b[2] == 0x6F && b[3] == 0x62 && b[4] == 0x65 ) { - /* Found Adobe APP14 marker */ - version = ( b[5] << 8 ) + b[6]; - flags0 = ( b[7] << 8 ) + b[8]; - flags1 = ( b[9] << 8 ) + b[10]; - transform = b[11]; - TRACEMS4( cinfo, 1, JTRC_ADOBE, version, flags0, flags1, transform ); - cinfo->saw_Adobe_marker = TRUE; - cinfo->Adobe_transform = (UINT8) transform; - } - else { - /* Start of APP14 does not match "Adobe" */ - TRACEMS1( cinfo, 1, JTRC_APP14, (int) length + ADOBE_LEN ); - } - } - else { - /* Too short to be Adobe marker */ - TRACEMS1( cinfo, 1, JTRC_APP14, (int) length ); - } - - INPUT_SYNC( cinfo ); - if ( length > 0 ) { /* skip any remaining data -- could be lots */ - ( *cinfo->src->skip_input_data )( cinfo, (long) length ); - } - - return TRUE; -} - - -LOCAL boolean -get_dac( j_decompress_ptr cinfo ){ -/* Process a DAC marker */ - INT32 length; - int index, val; - INPUT_VARS( cinfo ); - - INPUT_2BYTES( cinfo, length, return FALSE ); - length -= 2; - - while ( length > 0 ) { - INPUT_BYTE( cinfo, index, return FALSE ); - INPUT_BYTE( cinfo, val, return FALSE ); - - length -= 2; - - TRACEMS2( cinfo, 1, JTRC_DAC, index, val ); - - if ( index < 0 || index >= ( 2 * NUM_ARITH_TBLS ) ) { - ERREXIT1( cinfo, JERR_DAC_INDEX, index ); - } - - if ( index >= NUM_ARITH_TBLS ) { /* define AC table */ - cinfo->arith_ac_K[index - NUM_ARITH_TBLS] = (UINT8) val; - } - else { /* define DC table */ - cinfo->arith_dc_L[index] = (UINT8) ( val & 0x0F ); - cinfo->arith_dc_U[index] = (UINT8) ( val >> 4 ); - if ( cinfo->arith_dc_L[index] > cinfo->arith_dc_U[index] ) { - ERREXIT1( cinfo, JERR_DAC_VALUE, val ); - } - } - } - - INPUT_SYNC( cinfo ); - return TRUE; -} - - -LOCAL boolean -get_dht( j_decompress_ptr cinfo ){ -/* Process a DHT marker */ - INT32 length; - UINT8 bits[17]; - UINT8 huffval[256]; - int i, index, count; - JHUFF_TBL **htblptr; - INPUT_VARS( cinfo ); - - INPUT_2BYTES( cinfo, length, return FALSE ); - length -= 2; - - while ( length > 0 ) { - INPUT_BYTE( cinfo, index, return FALSE ); - - TRACEMS1( cinfo, 1, JTRC_DHT, index ); - - bits[0] = 0; - count = 0; - for ( i = 1; i <= 16; i++ ) { - INPUT_BYTE( cinfo, bits[i], return FALSE ); - count += bits[i]; - } - - length -= 1 + 16; - - TRACEMS8( cinfo, 2, JTRC_HUFFBITS, - bits[1], bits[2], bits[3], bits[4], - bits[5], bits[6], bits[7], bits[8] ); - TRACEMS8( cinfo, 2, JTRC_HUFFBITS, - bits[9], bits[10], bits[11], bits[12], - bits[13], bits[14], bits[15], bits[16] ); - - if ( count > 256 || ( (INT32) count ) > length ) { - ERREXIT( cinfo, JERR_DHT_COUNTS ); - } - - for ( i = 0; i < count; i++ ) - INPUT_BYTE( cinfo, huffval[i], return FALSE ); - - length -= count; - - if ( index & 0x10 ) { /* AC table definition */ - index -= 0x10; - htblptr = &cinfo->ac_huff_tbl_ptrs[index]; - } - else { /* DC table definition */ - htblptr = &cinfo->dc_huff_tbl_ptrs[index]; - } - - if ( index < 0 || index >= NUM_HUFF_TBLS ) { - ERREXIT1( cinfo, JERR_DHT_INDEX, index ); - } - - if ( *htblptr == NULL ) { - *htblptr = jpeg_alloc_huff_table( (j_common_ptr) cinfo ); - } - - MEMCOPY( ( *htblptr )->bits, bits, SIZEOF( ( *htblptr )->bits ) ); - MEMCOPY( ( *htblptr )->huffval, huffval, SIZEOF( ( *htblptr )->huffval ) ); - } - - INPUT_SYNC( cinfo ); - return TRUE; -} - - -LOCAL boolean -get_dqt( j_decompress_ptr cinfo ){ -/* Process a DQT marker */ - INT32 length; - int n, i, prec; - unsigned int tmp; - JQUANT_TBL *quant_ptr; - INPUT_VARS( cinfo ); - - INPUT_2BYTES( cinfo, length, return FALSE ); - length -= 2; - - while ( length > 0 ) { - INPUT_BYTE( cinfo, n, return FALSE ); - prec = n >> 4; - n &= 0x0F; - - TRACEMS2( cinfo, 1, JTRC_DQT, n, prec ); - - if ( n >= NUM_QUANT_TBLS ) { - ERREXIT1( cinfo, JERR_DQT_INDEX, n ); - } - - if ( cinfo->quant_tbl_ptrs[n] == NULL ) { - cinfo->quant_tbl_ptrs[n] = jpeg_alloc_quant_table( (j_common_ptr) cinfo ); - } - quant_ptr = cinfo->quant_tbl_ptrs[n]; - - for ( i = 0; i < DCTSIZE2; i++ ) { - if ( prec ) { - INPUT_2BYTES( cinfo, tmp, return FALSE ); - } - else{ - INPUT_BYTE( cinfo, tmp, return FALSE ); - } - quant_ptr->quantval[i] = (UINT16) tmp; - } - - for ( i = 0; i < DCTSIZE2; i += 8 ) { - TRACEMS8( cinfo, 2, JTRC_QUANTVALS, - quant_ptr->quantval[i ], quant_ptr->quantval[i + 1], - quant_ptr->quantval[i + 2], quant_ptr->quantval[i + 3], - quant_ptr->quantval[i + 4], quant_ptr->quantval[i + 5], - quant_ptr->quantval[i + 6], quant_ptr->quantval[i + 7] ); - } - - length -= DCTSIZE2 + 1; - if ( prec ) { - length -= DCTSIZE2; - } - } - - INPUT_SYNC( cinfo ); - return TRUE; -} - - -LOCAL boolean -get_dri( j_decompress_ptr cinfo ){ -/* Process a DRI marker */ - INT32 length; - unsigned int tmp; - INPUT_VARS( cinfo ); - - INPUT_2BYTES( cinfo, length, return FALSE ); - - if ( length != 4 ) { - ERREXIT( cinfo, JERR_BAD_LENGTH ); - } - - INPUT_2BYTES( cinfo, tmp, return FALSE ); - - TRACEMS1( cinfo, 1, JTRC_DRI, tmp ); - - cinfo->restart_interval = tmp; - - INPUT_SYNC( cinfo ); - return TRUE; -} - - -METHODDEF boolean -skip_variable( j_decompress_ptr cinfo ){ -/* Skip over an unknown or uninteresting variable-length marker */ - INT32 length; - INPUT_VARS( cinfo ); - - INPUT_2BYTES( cinfo, length, return FALSE ); - - TRACEMS2( cinfo, 1, JTRC_MISC_MARKER, cinfo->unread_marker, (int) length ); - - INPUT_SYNC( cinfo ); /* do before skip_input_data */ - ( *cinfo->src->skip_input_data )( cinfo, (long) length - 2L ); - - return TRUE; -} - - -/* - * Find the next JPEG marker, save it in cinfo->unread_marker. - * Returns FALSE if had to suspend before reaching a marker; - * in that case cinfo->unread_marker is unchanged. - * - * Note that the result might not be a valid marker code, - * but it will never be 0 or FF. - */ - -LOCAL boolean -next_marker( j_decompress_ptr cinfo ){ - int c; - INPUT_VARS( cinfo ); - - for (;; ) { - INPUT_BYTE( cinfo, c, return FALSE ); - /* Skip any non-FF bytes. - * This may look a bit inefficient, but it will not occur in a valid file. - * We sync after each discarded byte so that a suspending data source - * can discard the byte from its buffer. - */ - while ( c != 0xFF ) { - cinfo->marker->discarded_bytes++; - INPUT_SYNC( cinfo ); - INPUT_BYTE( cinfo, c, return FALSE ); - } - /* This loop swallows any duplicate FF bytes. Extra FFs are legal as - * pad bytes, so don't count them in discarded_bytes. We assume there - * will not be so many consecutive FF bytes as to overflow a suspending - * data source's input buffer. - */ - do { - INPUT_BYTE( cinfo, c, return FALSE ); - } while ( c == 0xFF ); - if ( c != 0 ) { - break; /* found a valid marker, exit loop */ - } - /* Reach here if we found a stuffed-zero data sequence (FF/00). - * Discard it and loop back to try again. - */ - cinfo->marker->discarded_bytes += 2; - INPUT_SYNC( cinfo ); - } - - if ( cinfo->marker->discarded_bytes != 0 ) { - WARNMS2( cinfo, JWRN_EXTRANEOUS_DATA, cinfo->marker->discarded_bytes, c ); - cinfo->marker->discarded_bytes = 0; - } - - cinfo->unread_marker = c; - - INPUT_SYNC( cinfo ); - return TRUE; -} - - -LOCAL boolean -first_marker( j_decompress_ptr cinfo ){ -/* Like next_marker, but used to obtain the initial SOI marker. */ -/* For this marker, we do not allow preceding garbage or fill; otherwise, - * we might well scan an entire input file before realizing it ain't JPEG. - * If an application wants to process non-JFIF files, it must seek to the - * SOI before calling the JPEG library. - */ - int c, c2; - INPUT_VARS( cinfo ); - - INPUT_BYTE( cinfo, c, return FALSE ); - INPUT_BYTE( cinfo, c2, return FALSE ); - if ( c != 0xFF || c2 != (int) M_SOI ) { - ERREXIT2( cinfo, JERR_NO_SOI, c, c2 ); - } - - cinfo->unread_marker = c2; - - INPUT_SYNC( cinfo ); - return TRUE; -} - - -/* - * Read markers until SOS or EOI. - * - * Returns same codes as are defined for jpeg_consume_input: - * JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI. - */ - -METHODDEF int -read_markers( j_decompress_ptr cinfo ){ - /* Outer loop repeats once for each marker. */ - for (;; ) { - /* Collect the marker proper, unless we already did. */ - /* NB: first_marker() enforces the requirement that SOI appear first. */ - if ( cinfo->unread_marker == 0 ) { - if ( !cinfo->marker->saw_SOI ) { - if ( !first_marker( cinfo ) ) { - return JPEG_SUSPENDED; - } - } - else { - if ( !next_marker( cinfo ) ) { - return JPEG_SUSPENDED; - } - } - } - /* At this point cinfo->unread_marker contains the marker code and the - * input point is just past the marker proper, but before any parameters. - * A suspension will cause us to return with this state still true. - */ - switch ( cinfo->unread_marker ) { - case M_SOI: - if ( !get_soi( cinfo ) ) { - return JPEG_SUSPENDED; - } - break; - - case M_SOF0: /* Baseline */ - case M_SOF1: /* Extended sequential, Huffman */ - if ( !get_sof( cinfo, FALSE, FALSE ) ) { - return JPEG_SUSPENDED; - } - break; - - case M_SOF2: /* Progressive, Huffman */ - if ( !get_sof( cinfo, TRUE, FALSE ) ) { - return JPEG_SUSPENDED; - } - break; - - case M_SOF9: /* Extended sequential, arithmetic */ - if ( !get_sof( cinfo, FALSE, TRUE ) ) { - return JPEG_SUSPENDED; - } - break; - - case M_SOF10: /* Progressive, arithmetic */ - if ( !get_sof( cinfo, TRUE, TRUE ) ) { - return JPEG_SUSPENDED; - } - break; - - /* Currently unsupported SOFn types */ - case M_SOF3: /* Lossless, Huffman */ - case M_SOF5: /* Differential sequential, Huffman */ - case M_SOF6: /* Differential progressive, Huffman */ - case M_SOF7: /* Differential lossless, Huffman */ - case M_JPG: /* Reserved for JPEG extensions */ - case M_SOF11: /* Lossless, arithmetic */ - case M_SOF13: /* Differential sequential, arithmetic */ - case M_SOF14: /* Differential progressive, arithmetic */ - case M_SOF15: /* Differential lossless, arithmetic */ - ERREXIT1( cinfo, JERR_SOF_UNSUPPORTED, cinfo->unread_marker ); - break; - - case M_SOS: - if ( !get_sos( cinfo ) ) { - return JPEG_SUSPENDED; - } - cinfo->unread_marker = 0; /* processed the marker */ - return JPEG_REACHED_SOS; - - case M_EOI: - TRACEMS( cinfo, 1, JTRC_EOI ); - cinfo->unread_marker = 0; /* processed the marker */ - return JPEG_REACHED_EOI; - - case M_DAC: - if ( !get_dac( cinfo ) ) { - return JPEG_SUSPENDED; - } - break; - - case M_DHT: - if ( !get_dht( cinfo ) ) { - return JPEG_SUSPENDED; - } - break; - - case M_DQT: - if ( !get_dqt( cinfo ) ) { - return JPEG_SUSPENDED; - } - break; - - case M_DRI: - if ( !get_dri( cinfo ) ) { - return JPEG_SUSPENDED; - } - break; - - case M_APP0: - case M_APP1: - case M_APP2: - case M_APP3: - case M_APP4: - case M_APP5: - case M_APP6: - case M_APP7: - case M_APP8: - case M_APP9: - case M_APP10: - case M_APP11: - case M_APP12: - case M_APP13: - case M_APP14: - case M_APP15: - if ( !( *cinfo->marker->process_APPn[cinfo->unread_marker - (int) M_APP0] )( cinfo ) ) { - return JPEG_SUSPENDED; - } - break; - - case M_COM: - if ( !( *cinfo->marker->process_COM )( cinfo ) ) { - return JPEG_SUSPENDED; - } - break; - - case M_RST0: /* these are all parameterless */ - case M_RST1: - case M_RST2: - case M_RST3: - case M_RST4: - case M_RST5: - case M_RST6: - case M_RST7: - case M_TEM: - TRACEMS1( cinfo, 1, JTRC_PARMLESS_MARKER, cinfo->unread_marker ); - break; - - case M_DNL: /* Ignore DNL ... perhaps the wrong thing */ - if ( !skip_variable( cinfo ) ) { - return JPEG_SUSPENDED; - } - break; - - default: /* must be DHP, EXP, JPGn, or RESn */ - /* For now, we treat the reserved markers as fatal errors since they are - * likely to be used to signal incompatible JPEG Part 3 extensions. - * Once the JPEG 3 version-number marker is well defined, this code - * ought to change! - */ - ERREXIT1( cinfo, JERR_UNKNOWN_MARKER, cinfo->unread_marker ); - break; - } - /* Successfully processed marker, so reset state variable */ - cinfo->unread_marker = 0; - } /* end loop */ -} - - -/* - * Read a restart marker, which is expected to appear next in the datastream; - * if the marker is not there, take appropriate recovery action. - * Returns FALSE if suspension is required. - * - * This is called by the entropy decoder after it has read an appropriate - * number of MCUs. cinfo->unread_marker may be nonzero if the entropy decoder - * has already read a marker from the data source. Under normal conditions - * cinfo->unread_marker will be reset to 0 before returning; if not reset, - * it holds a marker which the decoder will be unable to read past. - */ - -METHODDEF boolean -read_restart_marker( j_decompress_ptr cinfo ){ - /* Obtain a marker unless we already did. */ - /* Note that next_marker will complain if it skips any data. */ - if ( cinfo->unread_marker == 0 ) { - if ( !next_marker( cinfo ) ) { - return FALSE; - } - } - - if ( cinfo->unread_marker == - ( (int) M_RST0 + cinfo->marker->next_restart_num ) ) { - /* Normal case --- swallow the marker and let entropy decoder continue */ - TRACEMS1( cinfo, 2, JTRC_RST, cinfo->marker->next_restart_num ); - cinfo->unread_marker = 0; - } - else { - /* Uh-oh, the restart markers have been messed up. */ - /* Let the data source manager determine how to resync. */ - if ( !( *cinfo->src->resync_to_restart )( cinfo, - cinfo->marker->next_restart_num ) ) { - return FALSE; - } - } - - /* Update next-restart state */ - cinfo->marker->next_restart_num = ( cinfo->marker->next_restart_num + 1 ) & 7; - - return TRUE; -} - - -/* - * This is the default resync_to_restart method for data source managers - * to use if they don't have any better approach. Some data source managers - * may be able to back up, or may have additional knowledge about the data - * which permits a more intelligent recovery strategy; such managers would - * presumably supply their own resync method. - * - * read_restart_marker calls resync_to_restart if it finds a marker other than - * the restart marker it was expecting. (This code is *not* used unless - * a nonzero restart interval has been declared.) cinfo->unread_marker is - * the marker code actually found (might be anything, except 0 or FF). - * The desired restart marker number (0..7) is passed as a parameter. - * This routine is supposed to apply whatever error recovery strategy seems - * appropriate in order to position the input stream to the next data segment. - * Note that cinfo->unread_marker is treated as a marker appearing before - * the current data-source input point; usually it should be reset to zero - * before returning. - * Returns FALSE if suspension is required. - * - * This implementation is substantially constrained by wanting to treat the - * input as a data stream; this means we can't back up. Therefore, we have - * only the following actions to work with: - * 1. Simply discard the marker and let the entropy decoder resume at next - * byte of file. - * 2. Read forward until we find another marker, discarding intervening - * data. (In theory we could look ahead within the current bufferload, - * without having to discard data if we don't find the desired marker. - * This idea is not implemented here, in part because it makes behavior - * dependent on buffer size and chance buffer-boundary positions.) - * 3. Leave the marker unread (by failing to zero cinfo->unread_marker). - * This will cause the entropy decoder to process an empty data segment, - * inserting dummy zeroes, and then we will reprocess the marker. - * - * #2 is appropriate if we think the desired marker lies ahead, while #3 is - * appropriate if the found marker is a future restart marker (indicating - * that we have missed the desired restart marker, probably because it got - * corrupted). - * We apply #2 or #3 if the found marker is a restart marker no more than - * two counts behind or ahead of the expected one. We also apply #2 if the - * found marker is not a legal JPEG marker code (it's certainly bogus data). - * If the found marker is a restart marker more than 2 counts away, we do #1 - * (too much risk that the marker is erroneous; with luck we will be able to - * resync at some future point). - * For any valid non-restart JPEG marker, we apply #3. This keeps us from - * overrunning the end of a scan. An implementation limited to single-scan - * files might find it better to apply #2 for markers other than EOI, since - * any other marker would have to be bogus data in that case. - */ - -GLOBAL boolean -jpeg_resync_to_restart( j_decompress_ptr cinfo, int desired ){ - int marker = cinfo->unread_marker; - int action = 1; - - /* Always put up a warning. */ - WARNMS2( cinfo, JWRN_MUST_RESYNC, marker, desired ); - - /* Outer loop handles repeated decision after scanning forward. */ - for (;; ) { - if ( marker < (int) M_SOF0 ) { - action = 2; /* invalid marker */ - } - else if ( marker < (int) M_RST0 || marker > (int) M_RST7 ) { - action = 3; /* valid non-restart marker */ - } - else { - if ( marker == ( (int) M_RST0 + ( ( desired + 1 ) & 7 ) ) || - marker == ( (int) M_RST0 + ( ( desired + 2 ) & 7 ) ) ) { - action = 3; /* one of the next two expected restarts */ - } - else if ( marker == ( (int) M_RST0 + ( ( desired - 1 ) & 7 ) ) || - marker == ( (int) M_RST0 + ( ( desired - 2 ) & 7 ) ) ) { - action = 2; /* a prior restart, so advance */ - } - else{ - action = 1; /* desired restart or too far away */ - } - } - TRACEMS2( cinfo, 4, JTRC_RECOVERY_ACTION, marker, action ); - switch ( action ) { - case 1: - /* Discard marker and let entropy decoder resume processing. */ - cinfo->unread_marker = 0; - return TRUE; - case 2: - /* Scan to the next marker, and repeat the decision loop. */ - if ( !next_marker( cinfo ) ) { - return FALSE; - } - marker = cinfo->unread_marker; - break; - case 3: - /* Return without advancing past this marker. */ - /* Entropy decoder will be forced to process an empty segment. */ - return TRUE; - } - } /* end loop */ -} - - -/* - * Reset marker processing state to begin a fresh datastream. - */ - -METHODDEF void -reset_marker_reader( j_decompress_ptr cinfo ){ - cinfo->comp_info = NULL; /* until allocated by get_sof */ - cinfo->input_scan_number = 0; /* no SOS seen yet */ - cinfo->unread_marker = 0; /* no pending marker */ - cinfo->marker->saw_SOI = FALSE; /* set internal state too */ - cinfo->marker->saw_SOF = FALSE; - cinfo->marker->discarded_bytes = 0; -} - - -/* - * Initialize the marker reader module. - * This is called only once, when the decompression object is created. - */ - -GLOBAL void -jinit_marker_reader( j_decompress_ptr cinfo ){ - int i; - - /* Create subobject in permanent pool */ - cinfo->marker = (struct jpeg_marker_reader *) - ( *cinfo->mem->alloc_small )( (j_common_ptr) cinfo, JPOOL_PERMANENT, - SIZEOF( struct jpeg_marker_reader ) ); - /* Initialize method pointers */ - cinfo->marker->reset_marker_reader = reset_marker_reader; - cinfo->marker->read_markers = read_markers; - cinfo->marker->read_restart_marker = read_restart_marker; - cinfo->marker->process_COM = skip_variable; - for ( i = 0; i < 16; i++ ) - cinfo->marker->process_APPn[i] = skip_variable; - cinfo->marker->process_APPn[0] = get_app0; - cinfo->marker->process_APPn[14] = get_app14; - /* Reset marker processing state */ - reset_marker_reader( cinfo ); -} diff --git a/tools/urt/libs/jpeg6/jdmaster.cpp b/tools/urt/libs/jpeg6/jdmaster.cpp deleted file mode 100644 index ccc2fde..0000000 --- a/tools/urt/libs/jpeg6/jdmaster.cpp +++ /dev/null @@ -1,579 +0,0 @@ -/* - * jdmaster.c - * - * Copyright (C) 1991-1995, Thomas G. Lane. - * This file is part of the Independent JPEG Group's software. - * For conditions of distribution and use, see the accompanying README file. - * - * This file contains master control logic for the JPEG decompressor. - * These routines are concerned with selecting the modules to be executed - * and with determining the number of passes and the work to be done in each - * pass. - */ - -#define JPEG_INTERNALS -#include "jinclude.h" -#include "radiant_jpeglib.h" - - -/* Private state */ - -typedef struct { - struct jpeg_decomp_master pub; /* public fields */ - - int pass_number; /* # of passes completed */ - - boolean using_merged_upsample; /* TRUE if using merged upsample/cconvert */ - - /* Saved references to initialized quantizer modules, - * in case we need to switch modes. - */ - struct jpeg_color_quantizer * quantizer_1pass; - struct jpeg_color_quantizer * quantizer_2pass; -} my_decomp_master; - -typedef my_decomp_master * my_master_ptr; - - -/* - * Determine whether merged upsample/color conversion should be used. - * CRUCIAL: this must match the actual capabilities of jdmerge.c! - */ - -LOCAL boolean -use_merged_upsample( j_decompress_ptr cinfo ){ -#ifdef UPSAMPLE_MERGING_SUPPORTED - /* Merging is the equivalent of plain box-filter upsampling */ - if ( cinfo->do_fancy_upsampling || cinfo->CCIR601_sampling ) { - return FALSE; - } - /* jdmerge.c only supports YCC=>RGB color conversion */ - if ( cinfo->jpeg_color_space != JCS_YCbCr || cinfo->num_components != 3 || - cinfo->out_color_space != JCS_RGB || - cinfo->out_color_components != RGB_PIXELSIZE ) { - return FALSE; - } - /* and it only handles 2h1v or 2h2v sampling ratios */ - if ( cinfo->comp_info[0].h_samp_factor != 2 || - cinfo->comp_info[1].h_samp_factor != 1 || - cinfo->comp_info[2].h_samp_factor != 1 || - cinfo->comp_info[0].v_samp_factor > 2 || - cinfo->comp_info[1].v_samp_factor != 1 || - cinfo->comp_info[2].v_samp_factor != 1 ) { - return FALSE; - } - /* furthermore, it doesn't work if we've scaled the IDCTs differently */ - if ( cinfo->comp_info[0].DCT_scaled_size != cinfo->min_DCT_scaled_size || - cinfo->comp_info[1].DCT_scaled_size != cinfo->min_DCT_scaled_size || - cinfo->comp_info[2].DCT_scaled_size != cinfo->min_DCT_scaled_size ) { - return FALSE; - } - /* ??? also need to test for upsample-time rescaling, when & if supported */ - return TRUE; /* by golly, it'll work... */ -#else - return FALSE; -#endif -} - - -/* - * Compute output image dimensions and related values. - * NOTE: this is exported for possible use by application. - * Hence it mustn't do anything that can't be done twice. - * Also note that it may be called before the master module is initialized! - */ - -GLOBAL void -jpeg_calc_output_dimensions( j_decompress_ptr cinfo ){ -/* Do computations that are needed before master selection phase */ -#if 0 // JDC: commented out to remove warning - int ci; - jpeg_component_info *compptr; -#endif - - /* Prevent application from calling me at wrong times */ - if ( cinfo->global_state != DSTATE_READY ) { - ERREXIT1( cinfo, JERR_BAD_STATE, cinfo->global_state ); - } - -#ifdef IDCT_SCALING_SUPPORTED - - /* Compute actual output image dimensions and DCT scaling choices. */ - if ( cinfo->scale_num * 8 <= cinfo->scale_denom ) { - /* Provide 1/8 scaling */ - cinfo->output_width = (JDIMENSION) - jdiv_round_up( (long) cinfo->image_width, 8L ); - cinfo->output_height = (JDIMENSION) - jdiv_round_up( (long) cinfo->image_height, 8L ); - cinfo->min_DCT_scaled_size = 1; - } - else if ( cinfo->scale_num * 4 <= cinfo->scale_denom ) { - /* Provide 1/4 scaling */ - cinfo->output_width = (JDIMENSION) - jdiv_round_up( (long) cinfo->image_width, 4L ); - cinfo->output_height = (JDIMENSION) - jdiv_round_up( (long) cinfo->image_height, 4L ); - cinfo->min_DCT_scaled_size = 2; - } - else if ( cinfo->scale_num * 2 <= cinfo->scale_denom ) { - /* Provide 1/2 scaling */ - cinfo->output_width = (JDIMENSION) - jdiv_round_up( (long) cinfo->image_width, 2L ); - cinfo->output_height = (JDIMENSION) - jdiv_round_up( (long) cinfo->image_height, 2L ); - cinfo->min_DCT_scaled_size = 4; - } - else { - /* Provide 1/1 scaling */ - cinfo->output_width = cinfo->image_width; - cinfo->output_height = cinfo->image_height; - cinfo->min_DCT_scaled_size = DCTSIZE; - } - /* In selecting the actual DCT scaling for each component, we try to - * scale up the chroma components via IDCT scaling rather than upsampling. - * This saves time if the upsampler gets to use 1:1 scaling. - * Note this code assumes that the supported DCT scalings are powers of 2. - */ - for ( ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components; - ci++, compptr++ ) { - int ssize = cinfo->min_DCT_scaled_size; - while ( ssize < DCTSIZE && - ( compptr->h_samp_factor * ssize * 2 <= - cinfo->max_h_samp_factor * cinfo->min_DCT_scaled_size ) && - ( compptr->v_samp_factor * ssize * 2 <= - cinfo->max_v_samp_factor * cinfo->min_DCT_scaled_size ) ) { - ssize = ssize * 2; - } - compptr->DCT_scaled_size = ssize; - } - - /* Recompute downsampled dimensions of components; - * application needs to know these if using raw downsampled data. - */ - for ( ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components; - ci++, compptr++ ) { - /* Size in samples, after IDCT scaling */ - compptr->downsampled_width = (JDIMENSION) - jdiv_round_up( (long) cinfo->image_width * - (long) ( compptr->h_samp_factor * compptr->DCT_scaled_size ), - (long) ( cinfo->max_h_samp_factor * DCTSIZE ) ); - compptr->downsampled_height = (JDIMENSION) - jdiv_round_up( (long) cinfo->image_height * - (long) ( compptr->v_samp_factor * compptr->DCT_scaled_size ), - (long) ( cinfo->max_v_samp_factor * DCTSIZE ) ); - } - -#else /* !IDCT_SCALING_SUPPORTED */ - - /* Hardwire it to "no scaling" */ - cinfo->output_width = cinfo->image_width; - cinfo->output_height = cinfo->image_height; - /* jdinput.c has already initialized DCT_scaled_size to DCTSIZE, - * and has computed unscaled downsampled_width and downsampled_height. - */ - -#endif /* IDCT_SCALING_SUPPORTED */ - - /* Report number of components in selected colorspace. */ - /* Probably this should be in the color conversion module... */ - switch ( cinfo->out_color_space ) { - case JCS_GRAYSCALE: - cinfo->out_color_components = 1; - break; - case JCS_RGB: -#if RGB_PIXELSIZE != 3 - cinfo->out_color_components = RGB_PIXELSIZE; - break; -#endif /* else share code with YCbCr */ - case JCS_YCbCr: - cinfo->out_color_components = 3; - break; - case JCS_CMYK: - case JCS_YCCK: - cinfo->out_color_components = 4; - break; - default: /* else must be same colorspace as in file */ - cinfo->out_color_components = cinfo->num_components; - break; - } - cinfo->output_components = ( cinfo->quantize_colors ? 1 : - cinfo->out_color_components ); - - /* See if upsampler will want to emit more than one row at a time */ - if ( use_merged_upsample( cinfo ) ) { - cinfo->rec_outbuf_height = cinfo->max_v_samp_factor; - } - else{ - cinfo->rec_outbuf_height = 1; - } -} - - -/* - * Several decompression processes need to range-limit values to the range - * 0..MAXJSAMPLE; the input value may fall somewhat outside this range - * due to noise introduced by quantization, roundoff error, etc. These - * processes are inner loops and need to be as fast as possible. On most - * machines, particularly CPUs with pipelines or instruction prefetch, - * a (subscript-check-less) C table lookup - * x = sample_range_limit[x]; - * is faster than explicit tests - * if (x < 0) x = 0; - * else if (x > MAXJSAMPLE) x = MAXJSAMPLE; - * These processes all use a common table prepared by the routine below. - * - * For most steps we can mathematically guarantee that the initial value - * of x is within MAXJSAMPLE+1 of the legal range, so a table running from - * -(MAXJSAMPLE+1) to 2*MAXJSAMPLE+1 is sufficient. But for the initial - * limiting step (just after the IDCT), a wildly out-of-range value is - * possible if the input data is corrupt. To avoid any chance of indexing - * off the end of memory and getting a bad-pointer trap, we perform the - * post-IDCT limiting thus: - * x = range_limit[x & MASK]; - * where MASK is 2 bits wider than legal sample data, ie 10 bits for 8-bit - * samples. Under normal circumstances this is more than enough range and - * a correct output will be generated; with bogus input data the mask will - * cause wraparound, and we will safely generate a bogus-but-in-range output. - * For the post-IDCT step, we want to convert the data from signed to unsigned - * representation by adding CENTERJSAMPLE at the same time that we limit it. - * So the post-IDCT limiting table ends up looking like this: - * CENTERJSAMPLE,CENTERJSAMPLE+1,...,MAXJSAMPLE, - * MAXJSAMPLE (repeat 2*(MAXJSAMPLE+1)-CENTERJSAMPLE times), - * 0 (repeat 2*(MAXJSAMPLE+1)-CENTERJSAMPLE times), - * 0,1,...,CENTERJSAMPLE-1 - * Negative inputs select values from the upper half of the table after - * masking. - * - * We can save some space by overlapping the start of the post-IDCT table - * with the simpler range limiting table. The post-IDCT table begins at - * sample_range_limit + CENTERJSAMPLE. - * - * Note that the table is allocated in near data space on PCs; it's small - * enough and used often enough to justify this. - */ - -LOCAL void -prepare_range_limit_table( j_decompress_ptr cinfo ){ -/* Allocate and fill in the sample_range_limit table */ - JSAMPLE * table; - int i; - - table = (JSAMPLE *) - ( *cinfo->mem->alloc_small )( (j_common_ptr) cinfo, JPOOL_IMAGE, - ( 5 * ( MAXJSAMPLE + 1 ) + CENTERJSAMPLE ) * SIZEOF( JSAMPLE ) ); - table += ( MAXJSAMPLE + 1 ); /* allow negative subscripts of simple table */ - cinfo->sample_range_limit = table; - /* First segment of "simple" table: limit[x] = 0 for x < 0 */ - MEMZERO( table - ( MAXJSAMPLE + 1 ), ( MAXJSAMPLE + 1 ) * SIZEOF( JSAMPLE ) ); - /* Main part of "simple" table: limit[x] = x */ - for ( i = 0; i <= MAXJSAMPLE; i++ ) - table[i] = (JSAMPLE) i; - table += CENTERJSAMPLE; /* Point to where post-IDCT table starts */ - /* End of simple table, rest of first half of post-IDCT table */ - for ( i = CENTERJSAMPLE; i < 2 * ( MAXJSAMPLE + 1 ); i++ ) - table[i] = MAXJSAMPLE; - /* Second half of post-IDCT table */ - MEMZERO( table + ( 2 * ( MAXJSAMPLE + 1 ) ), - ( 2 * ( MAXJSAMPLE + 1 ) - CENTERJSAMPLE ) * SIZEOF( JSAMPLE ) ); - MEMCOPY( table + ( 4 * ( MAXJSAMPLE + 1 ) - CENTERJSAMPLE ), - cinfo->sample_range_limit, CENTERJSAMPLE * SIZEOF( JSAMPLE ) ); -} - - -/* - * Master selection of decompression modules. - * This is done once at jpeg_start_decompress time. We determine - * which modules will be used and give them appropriate initialization calls. - * We also initialize the decompressor input side to begin consuming data. - * - * Since jpeg_read_header has finished, we know what is in the SOF - * and (first) SOS markers. We also have all the application parameter - * settings. - */ - -LOCAL void -master_selection( j_decompress_ptr cinfo ){ - my_master_ptr master = (my_master_ptr) cinfo->master; - boolean use_c_buffer; - long samplesperrow; - JDIMENSION jd_samplesperrow; - - /* Initialize dimensions and other stuff */ - jpeg_calc_output_dimensions( cinfo ); - prepare_range_limit_table( cinfo ); - - /* Width of an output scanline must be representable as JDIMENSION. */ - samplesperrow = (long) cinfo->output_width * (long) cinfo->out_color_components; - jd_samplesperrow = (JDIMENSION) samplesperrow; - if ( (long) jd_samplesperrow != samplesperrow ) { - ERREXIT( cinfo, JERR_WIDTH_OVERFLOW ); - } - - /* Initialize my private state */ - master->pass_number = 0; - master->using_merged_upsample = use_merged_upsample( cinfo ); - - /* Color quantizer selection */ - master->quantizer_1pass = NULL; - master->quantizer_2pass = NULL; - /* No mode changes if not using buffered-image mode. */ - if ( !cinfo->quantize_colors || !cinfo->buffered_image ) { - cinfo->enable_1pass_quant = FALSE; - cinfo->enable_external_quant = FALSE; - cinfo->enable_2pass_quant = FALSE; - } - if ( cinfo->quantize_colors ) { - if ( cinfo->raw_data_out ) { - ERREXIT( cinfo, JERR_NOTIMPL ); - } - /* 2-pass quantizer only works in 3-component color space. */ - if ( cinfo->out_color_components != 3 ) { - cinfo->enable_1pass_quant = TRUE; - cinfo->enable_external_quant = FALSE; - cinfo->enable_2pass_quant = FALSE; - cinfo->colormap = NULL; - } - else if ( cinfo->colormap != NULL ) { - cinfo->enable_external_quant = TRUE; - } - else if ( cinfo->two_pass_quantize ) { - cinfo->enable_2pass_quant = TRUE; - } - else { - cinfo->enable_1pass_quant = TRUE; - } - - if ( cinfo->enable_1pass_quant ) { -#ifdef QUANT_1PASS_SUPPORTED - jinit_1pass_quantizer( cinfo ); - master->quantizer_1pass = cinfo->cquantize; -#else - ERREXIT( cinfo, JERR_NOT_COMPILED ); -#endif - } - - /* We use the 2-pass code to map to external colormaps. */ - if ( cinfo->enable_2pass_quant || cinfo->enable_external_quant ) { -#ifdef QUANT_2PASS_SUPPORTED - jinit_2pass_quantizer( cinfo ); - master->quantizer_2pass = cinfo->cquantize; -#else - ERREXIT( cinfo, JERR_NOT_COMPILED ); -#endif - } - /* If both quantizers are initialized, the 2-pass one is left active; - * this is necessary for starting with quantization to an external map. - */ - } - - /* Post-processing: in particular, color conversion first */ - if ( !cinfo->raw_data_out ) { - if ( master->using_merged_upsample ) { -#ifdef UPSAMPLE_MERGING_SUPPORTED - jinit_merged_upsampler( cinfo ); /* does color conversion too */ -#else - ERREXIT( cinfo, JERR_NOT_COMPILED ); -#endif - } - else { - jinit_color_deconverter( cinfo ); - jinit_upsampler( cinfo ); - } - jinit_d_post_controller( cinfo, cinfo->enable_2pass_quant ); - } - /* Inverse DCT */ - jinit_inverse_dct( cinfo ); - /* Entropy decoding: either Huffman or arithmetic coding. */ - if ( cinfo->arith_code ) { - ERREXIT( cinfo, JERR_ARITH_NOTIMPL ); - } - else { - if ( cinfo->progressive_mode ) { -#ifdef D_PROGRESSIVE_SUPPORTED - jinit_phuff_decoder( cinfo ); -#else - ERREXIT( cinfo, JERR_NO_PROGRESSIVE ); -#endif - } - else{ - jinit_huff_decoder( cinfo ); - } - } - - /* Initialize principal buffer controllers. */ - use_c_buffer = cinfo->inputctl->has_multiple_scans || cinfo->buffered_image; - jinit_d_coef_controller( cinfo, use_c_buffer ); - - if ( !cinfo->raw_data_out ) { - jinit_d_main_controller( cinfo, FALSE /* never need full buffer here */ ); - } - - /* We can now tell the memory manager to allocate virtual arrays. */ - ( *cinfo->mem->realize_virt_arrays )( (j_common_ptr) cinfo ); - - /* Initialize input side of decompressor to consume first scan. */ - ( *cinfo->inputctl->start_input_pass )( cinfo ); - -#ifdef D_MULTISCAN_FILES_SUPPORTED - /* If jpeg_start_decompress will read the whole file, initialize - * progress monitoring appropriately. The input step is counted - * as one pass. - */ - if ( cinfo->progress != NULL && !cinfo->buffered_image && - cinfo->inputctl->has_multiple_scans ) { - int nscans; - /* Estimate number of scans to set pass_limit. */ - if ( cinfo->progressive_mode ) { - /* Arbitrarily estimate 2 interleaved DC scans + 3 AC scans/component. */ - nscans = 2 + 3 * cinfo->num_components; - } - else { - /* For a nonprogressive multiscan file, estimate 1 scan per component. */ - nscans = cinfo->num_components; - } - cinfo->progress->pass_counter = 0L; - cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows * nscans; - cinfo->progress->completed_passes = 0; - cinfo->progress->total_passes = ( cinfo->enable_2pass_quant ? 3 : 2 ); - /* Count the input pass as done */ - master->pass_number++; - } -#endif /* D_MULTISCAN_FILES_SUPPORTED */ -} - - -/* - * Per-pass setup. - * This is called at the beginning of each output pass. We determine which - * modules will be active during this pass and give them appropriate - * start_pass calls. We also set is_dummy_pass to indicate whether this - * is a "real" output pass or a dummy pass for color quantization. - * (In the latter case, jdapi.c will crank the pass to completion.) - */ - -METHODDEF void -prepare_for_output_pass( j_decompress_ptr cinfo ){ - my_master_ptr master = (my_master_ptr) cinfo->master; - - if ( master->pub.is_dummy_pass ) { -#ifdef QUANT_2PASS_SUPPORTED - /* Final pass of 2-pass quantization */ - master->pub.is_dummy_pass = FALSE; - ( *cinfo->cquantize->start_pass )( cinfo, FALSE ); - ( *cinfo->post->start_pass )( cinfo, JBUF_CRANK_DEST ); - ( *cinfo->main->start_pass )( cinfo, JBUF_CRANK_DEST ); -#else - ERREXIT( cinfo, JERR_NOT_COMPILED ); -#endif /* QUANT_2PASS_SUPPORTED */ - } - else { - if ( cinfo->quantize_colors && cinfo->colormap == NULL ) { - /* Select new quantization method */ - if ( cinfo->two_pass_quantize && cinfo->enable_2pass_quant ) { - cinfo->cquantize = master->quantizer_2pass; - master->pub.is_dummy_pass = TRUE; - } - else if ( cinfo->enable_1pass_quant ) { - cinfo->cquantize = master->quantizer_1pass; - } - else { - ERREXIT( cinfo, JERR_MODE_CHANGE ); - } - } - ( *cinfo->idct->start_pass )( cinfo ); - ( *cinfo->coef->start_output_pass )( cinfo ); - if ( !cinfo->raw_data_out ) { - if ( !master->using_merged_upsample ) { - ( *cinfo->cconvert->start_pass )( cinfo ); - } - ( *cinfo->upsample->start_pass )( cinfo ); - if ( cinfo->quantize_colors ) { - ( *cinfo->cquantize->start_pass )( cinfo, master->pub.is_dummy_pass ); - } - ( *cinfo->post->start_pass )( cinfo, - ( master->pub.is_dummy_pass ? JBUF_SAVE_AND_PASS : JBUF_PASS_THRU ) ); - ( *cinfo->main->start_pass )( cinfo, JBUF_PASS_THRU ); - } - } - - /* Set up progress monitor's pass info if present */ - if ( cinfo->progress != NULL ) { - cinfo->progress->completed_passes = master->pass_number; - cinfo->progress->total_passes = master->pass_number + - ( master->pub.is_dummy_pass ? 2 : 1 ); - /* In buffered-image mode, we assume one more output pass if EOI not - * yet reached, but no more passes if EOI has been reached. - */ - if ( cinfo->buffered_image && !cinfo->inputctl->eoi_reached ) { - cinfo->progress->total_passes += ( cinfo->enable_2pass_quant ? 2 : 1 ); - } - } -} - - -/* - * Finish up at end of an output pass. - */ - -METHODDEF void -finish_output_pass( j_decompress_ptr cinfo ){ - my_master_ptr master = (my_master_ptr) cinfo->master; - - if ( cinfo->quantize_colors ) { - ( *cinfo->cquantize->finish_pass )( cinfo ); - } - master->pass_number++; -} - - -#ifdef D_MULTISCAN_FILES_SUPPORTED - -/* - * Switch to a new external colormap between output passes. - */ - -GLOBAL void -jpeg_new_colormap( j_decompress_ptr cinfo ){ - my_master_ptr master = (my_master_ptr) cinfo->master; - - /* Prevent application from calling me at wrong times */ - if ( cinfo->global_state != DSTATE_BUFIMAGE ) { - ERREXIT1( cinfo, JERR_BAD_STATE, cinfo->global_state ); - } - - if ( cinfo->quantize_colors && cinfo->enable_external_quant && - cinfo->colormap != NULL ) { - /* Select 2-pass quantizer for external colormap use */ - cinfo->cquantize = master->quantizer_2pass; - /* Notify quantizer of colormap change */ - ( *cinfo->cquantize->new_color_map )( cinfo ); - master->pub.is_dummy_pass = FALSE; /* just in case */ - } - else{ - ERREXIT( cinfo, JERR_MODE_CHANGE ); - } -} - -#endif /* D_MULTISCAN_FILES_SUPPORTED */ - - -/* - * Initialize master decompression control and select active modules. - * This is performed at the start of jpeg_start_decompress. - */ - -GLOBAL void -jinit_master_decompress( j_decompress_ptr cinfo ){ - my_master_ptr master; - - master = (my_master_ptr) - ( *cinfo->mem->alloc_small )( (j_common_ptr) cinfo, JPOOL_IMAGE, - SIZEOF( my_decomp_master ) ); - cinfo->master = (struct jpeg_decomp_master *) master; - master->pub.prepare_for_output_pass = prepare_for_output_pass; - master->pub.finish_output_pass = finish_output_pass; - - master->pub.is_dummy_pass = FALSE; - - master_selection( cinfo ); -} diff --git a/tools/urt/libs/jpeg6/jdpostct.cpp b/tools/urt/libs/jpeg6/jdpostct.cpp deleted file mode 100644 index d8ccb46..0000000 --- a/tools/urt/libs/jpeg6/jdpostct.cpp +++ /dev/null @@ -1,576 +0,0 @@ -/* - - * jdpostct.c - - * - - * Copyright (C) 1994-1995, Thomas G. Lane. - - * This file is part of the Independent JPEG Group's software. - - * For conditions of distribution and use, see the accompanying README file. - - * - - * This file contains the decompression postprocessing controller. - - * This controller manages the upsampling, color conversion, and color - - * quantization/reduction steps; specifically, it controls the buffering - - * between upsample/color conversion and color quantization/reduction. - - * - - * If no color quantization/reduction is required, then this module has no - - * work to do, and it just hands off to the upsample/color conversion code. - - * An integrated upsample/convert/quantize process would replace this module - - * entirely. - - */ - - - -#define JPEG_INTERNALS - -#include "jinclude.h" - -#include "radiant_jpeglib.h" - - - - - -/* Private buffer controller object */ - - - -typedef struct { - - struct jpeg_d_post_controller pub; /* public fields */ - - - - /* Color quantization source buffer: this holds output data from - - * the upsample/color conversion step to be passed to the quantizer. - - * For two-pass color quantization, we need a full-image buffer; - - * for one-pass operation, a strip buffer is sufficient. - - */ - - jvirt_sarray_ptr whole_image; /* virtual array, or NULL if one-pass */ - - JSAMPARRAY buffer; /* strip buffer, or current strip of virtual */ - - JDIMENSION strip_height; /* buffer size in rows */ - - /* for two-pass mode only: */ - - JDIMENSION starting_row; /* row # of first row in current strip */ - - JDIMENSION next_row; /* index of next row to fill/empty in strip */ - -} my_post_controller; - - - -typedef my_post_controller * my_post_ptr; - - - - - -/* Forward declarations */ - -METHODDEF void post_process_1pass - -JPP( ( j_decompress_ptr cinfo, - - JSAMPIMAGE input_buf, JDIMENSION * in_row_group_ctr, - - JDIMENSION in_row_groups_avail, - - JSAMPARRAY output_buf, JDIMENSION * out_row_ctr, - - JDIMENSION out_rows_avail ) ); - -#ifdef QUANT_2PASS_SUPPORTED - -METHODDEF void post_process_prepass - -JPP( ( j_decompress_ptr cinfo, - - JSAMPIMAGE input_buf, JDIMENSION * in_row_group_ctr, - - JDIMENSION in_row_groups_avail, - - JSAMPARRAY output_buf, JDIMENSION * out_row_ctr, - - JDIMENSION out_rows_avail ) ); - -METHODDEF void post_process_2pass - -JPP( ( j_decompress_ptr cinfo, - - JSAMPIMAGE input_buf, JDIMENSION * in_row_group_ctr, - - JDIMENSION in_row_groups_avail, - - JSAMPARRAY output_buf, JDIMENSION * out_row_ctr, - - JDIMENSION out_rows_avail ) ); - -#endif - - - - - -/* - - * Initialize for a processing pass. - - */ - - - -METHODDEF void - -start_pass_dpost( j_decompress_ptr cinfo, J_BUF_MODE pass_mode ){ - - my_post_ptr post = (my_post_ptr) cinfo->post; - - - - switch ( pass_mode ) { - - case JBUF_PASS_THRU: - - if ( cinfo->quantize_colors ) { - - /* Single-pass processing with color quantization. */ - - post->pub.post_process_data = post_process_1pass; - - /* We could be doing buffered-image output before starting a 2-pass - - * color quantization; in that case, jinit_d_post_controller did not - - * allocate a strip buffer. Use the virtual-array buffer as workspace. - - */ - - if ( post->buffer == NULL ) { - - post->buffer = ( *cinfo->mem->access_virt_sarray ) - - ( (j_common_ptr) cinfo, post->whole_image, - - (JDIMENSION) 0, post->strip_height, TRUE ); - - } - - } - else { - - /* For single-pass processing without color quantization, - - * I have no work to do; just call the upsampler directly. - - */ - - post->pub.post_process_data = cinfo->upsample->upsample; - - } - - break; - -#ifdef QUANT_2PASS_SUPPORTED - - case JBUF_SAVE_AND_PASS: - - /* First pass of 2-pass quantization */ - - if ( post->whole_image == NULL ) { - - ERREXIT( cinfo, JERR_BAD_BUFFER_MODE ); - } - - post->pub.post_process_data = post_process_prepass; - - break; - - case JBUF_CRANK_DEST: - - /* Second pass of 2-pass quantization */ - - if ( post->whole_image == NULL ) { - - ERREXIT( cinfo, JERR_BAD_BUFFER_MODE ); - } - - post->pub.post_process_data = post_process_2pass; - - break; - -#endif /* QUANT_2PASS_SUPPORTED */ - - default: - - ERREXIT( cinfo, JERR_BAD_BUFFER_MODE ); - - break; - - } - - post->starting_row = post->next_row = 0; - -} - - - - - -/* - - * Process some data in the one-pass (strip buffer) case. - - * This is used for color precision reduction as well as one-pass quantization. - - */ - - - -METHODDEF void - -post_process_1pass( j_decompress_ptr cinfo, - - JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr, - - JDIMENSION in_row_groups_avail, - - JSAMPARRAY output_buf, JDIMENSION *out_row_ctr, - - JDIMENSION out_rows_avail ){ - - my_post_ptr post = (my_post_ptr) cinfo->post; - - JDIMENSION num_rows, max_rows; - - - - /* Fill the buffer, but not more than what we can dump out in one go. */ - - /* Note we rely on the upsampler to detect bottom of image. */ - - max_rows = out_rows_avail - *out_row_ctr; - - if ( max_rows > post->strip_height ) { - - max_rows = post->strip_height; - } - - num_rows = 0; - - ( *cinfo->upsample->upsample )( cinfo, - - input_buf, in_row_group_ctr, in_row_groups_avail, - - post->buffer, &num_rows, max_rows ); - - /* Quantize and emit data. */ - - ( *cinfo->cquantize->color_quantize )( cinfo, - - post->buffer, output_buf + *out_row_ctr, (int) num_rows ); - - *out_row_ctr += num_rows; - -} - - - - - -#ifdef QUANT_2PASS_SUPPORTED - - - -/* - - * Process some data in the first pass of 2-pass quantization. - - */ - - - -METHODDEF void - -post_process_prepass( j_decompress_ptr cinfo, - - JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr, - - JDIMENSION in_row_groups_avail, - - JSAMPARRAY output_buf, JDIMENSION *out_row_ctr, - - JDIMENSION out_rows_avail ){ - - my_post_ptr post = (my_post_ptr) cinfo->post; - - JDIMENSION old_next_row, num_rows; - - - - /* Reposition virtual buffer if at start of strip. */ - - if ( post->next_row == 0 ) { - - post->buffer = ( *cinfo->mem->access_virt_sarray ) - - ( (j_common_ptr) cinfo, post->whole_image, - - post->starting_row, post->strip_height, TRUE ); - - } - - - - /* Upsample some data (up to a strip height's worth). */ - - old_next_row = post->next_row; - - ( *cinfo->upsample->upsample )( cinfo, - - input_buf, in_row_group_ctr, in_row_groups_avail, - - post->buffer, &post->next_row, post->strip_height ); - - - - /* Allow quantizer to scan new data. No data is emitted, */ - - /* but we advance out_row_ctr so outer loop can tell when we're done. */ - - if ( post->next_row > old_next_row ) { - - num_rows = post->next_row - old_next_row; - - ( *cinfo->cquantize->color_quantize )( cinfo, post->buffer + old_next_row, - - (JSAMPARRAY) NULL, (int) num_rows ); - - *out_row_ctr += num_rows; - - } - - - - /* Advance if we filled the strip. */ - - if ( post->next_row >= post->strip_height ) { - - post->starting_row += post->strip_height; - - post->next_row = 0; - - } - -} - - - - - -/* - - * Process some data in the second pass of 2-pass quantization. - - */ - - - -METHODDEF void - -post_process_2pass( j_decompress_ptr cinfo, - - JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr, - - JDIMENSION in_row_groups_avail, - - JSAMPARRAY output_buf, JDIMENSION *out_row_ctr, - - JDIMENSION out_rows_avail ){ - - my_post_ptr post = (my_post_ptr) cinfo->post; - - JDIMENSION num_rows, max_rows; - - - - /* Reposition virtual buffer if at start of strip. */ - - if ( post->next_row == 0 ) { - - post->buffer = ( *cinfo->mem->access_virt_sarray ) - - ( (j_common_ptr) cinfo, post->whole_image, - - post->starting_row, post->strip_height, FALSE ); - - } - - - - /* Determine number of rows to emit. */ - - num_rows = post->strip_height - post->next_row; /* available in strip */ - - max_rows = out_rows_avail - *out_row_ctr; /* available in output area */ - - if ( num_rows > max_rows ) { - - num_rows = max_rows; - } - - /* We have to check bottom of image here, can't depend on upsampler. */ - - max_rows = cinfo->output_height - post->starting_row; - - if ( num_rows > max_rows ) { - - num_rows = max_rows; - } - - - - /* Quantize and emit data. */ - - ( *cinfo->cquantize->color_quantize )( cinfo, - - post->buffer + post->next_row, output_buf + *out_row_ctr, - - (int) num_rows ); - - *out_row_ctr += num_rows; - - - - /* Advance if we filled the strip. */ - - post->next_row += num_rows; - - if ( post->next_row >= post->strip_height ) { - - post->starting_row += post->strip_height; - - post->next_row = 0; - - } - -} - - - -#endif /* QUANT_2PASS_SUPPORTED */ - - - - - -/* - - * Initialize postprocessing controller. - - */ - - - -GLOBAL void - -jinit_d_post_controller( j_decompress_ptr cinfo, boolean need_full_buffer ){ - - my_post_ptr post; - - - - post = (my_post_ptr) - - ( *cinfo->mem->alloc_small )( (j_common_ptr) cinfo, JPOOL_IMAGE, - - SIZEOF( my_post_controller ) ); - - cinfo->post = (struct jpeg_d_post_controller *) post; - - post->pub.start_pass = start_pass_dpost; - - post->whole_image = NULL; /* flag for no virtual arrays */ - - post->buffer = NULL; /* flag for no strip buffer */ - - - - /* Create the quantization buffer, if needed */ - - if ( cinfo->quantize_colors ) { - - /* The buffer strip height is max_v_samp_factor, which is typically - - * an efficient number of rows for upsampling to return. - - * (In the presence of output rescaling, we might want to be smarter?) - - */ - - post->strip_height = (JDIMENSION) cinfo->max_v_samp_factor; - - if ( need_full_buffer ) { - - /* Two-pass color quantization: need full-image storage. */ - - /* We round up the number of rows to a multiple of the strip height. */ - -#ifdef QUANT_2PASS_SUPPORTED - - post->whole_image = ( *cinfo->mem->request_virt_sarray ) - - ( (j_common_ptr) cinfo, JPOOL_IMAGE, FALSE, - - cinfo->output_width * cinfo->out_color_components, - - (JDIMENSION) jround_up( (long) cinfo->output_height, - - (long) post->strip_height ), - - post->strip_height ); - -#else - - ERREXIT( cinfo, JERR_BAD_BUFFER_MODE ); - -#endif /* QUANT_2PASS_SUPPORTED */ - - } - else { - - /* One-pass color quantization: just make a strip buffer. */ - - post->buffer = ( *cinfo->mem->alloc_sarray ) - - ( (j_common_ptr) cinfo, JPOOL_IMAGE, - - cinfo->output_width * cinfo->out_color_components, - - post->strip_height ); - - } - - } - -} diff --git a/tools/urt/libs/jpeg6/jdsample.cpp b/tools/urt/libs/jpeg6/jdsample.cpp deleted file mode 100644 index 2aa30ee..0000000 --- a/tools/urt/libs/jpeg6/jdsample.cpp +++ /dev/null @@ -1,951 +0,0 @@ -/* - - * jdsample.c - - * - - * Copyright (C) 1991-1994, Thomas G. Lane. - - * This file is part of the Independent JPEG Group's software. - - * For conditions of distribution and use, see the accompanying README file. - - * - - * This file contains upsampling routines. - - * - - * Upsampling input data is counted in "row groups". A row group - - * is defined to be (v_samp_factor * DCT_scaled_size / min_DCT_scaled_size) - - * sample rows of each component. Upsampling will normally produce - - * max_v_samp_factor pixel rows from each row group (but this could vary - - * if the upsampler is applying a scale factor of its own). - - * - - * An excellent reference for image resampling is - - * Digital Image Warping, George Wolberg, 1990. - - * Pub. by IEEE Computer Society Press, Los Alamitos, CA. ISBN 0-8186-8944-7. - - */ - - - -#define JPEG_INTERNALS - -#include "jinclude.h" - -#include "radiant_jpeglib.h" - - - - - -/* Pointer to routine to upsample a single component */ - -typedef JMETHOD ( void, upsample1_ptr, - - ( j_decompress_ptr cinfo, jpeg_component_info * compptr, - - JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr ) ); - - - -/* Private subobject */ - - - -typedef struct { - - struct jpeg_upsampler pub; /* public fields */ - - - - /* Color conversion buffer. When using separate upsampling and color - - * conversion steps, this buffer holds one upsampled row group until it - - * has been color converted and output. - - * Note: we do not allocate any storage for component(s) which are full-size, - - * ie do not need rescaling. The corresponding entry of color_buf[] is - - * simply set to point to the input data array, thereby avoiding copying. - - */ - - JSAMPARRAY color_buf[MAX_COMPONENTS]; - - - - /* Per-component upsampling method pointers */ - - upsample1_ptr methods[MAX_COMPONENTS]; - - - - int next_row_out; /* counts rows emitted from color_buf */ - - JDIMENSION rows_to_go; /* counts rows remaining in image */ - - - - /* Height of an input row group for each component. */ - - int rowgroup_height[MAX_COMPONENTS]; - - - - /* These arrays save pixel expansion factors so that int_expand need not - - * recompute them each time. They are unused for other upsampling methods. - - */ - - UINT8 h_expand[MAX_COMPONENTS]; - - UINT8 v_expand[MAX_COMPONENTS]; - -} my_upsampler; - - - -typedef my_upsampler * my_upsample_ptr; - - - - - -/* - - * Initialize for an upsampling pass. - - */ - - - -METHODDEF void - -start_pass_upsample( j_decompress_ptr cinfo ){ - - my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample; - - - - /* Mark the conversion buffer empty */ - - upsample->next_row_out = cinfo->max_v_samp_factor; - - /* Initialize total-height counter for detecting bottom of image */ - - upsample->rows_to_go = cinfo->output_height; - -} - - - - - -/* - - * Control routine to do upsampling (and color conversion). - - * - - * In this version we upsample each component independently. - - * We upsample one row group into the conversion buffer, then apply - - * color conversion a row at a time. - - */ - - - -METHODDEF void - -sep_upsample( j_decompress_ptr cinfo, - - JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr, - - JDIMENSION in_row_groups_avail, - - JSAMPARRAY output_buf, JDIMENSION *out_row_ctr, - - JDIMENSION out_rows_avail ){ - - my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample; - - int ci; - - jpeg_component_info * compptr; - - JDIMENSION num_rows; - - - - /* Fill the conversion buffer, if it's empty */ - - if ( upsample->next_row_out >= cinfo->max_v_samp_factor ) { - - for ( ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components; - - ci++, compptr++ ) { - - /* Invoke per-component upsample method. Notice we pass a POINTER - - * to color_buf[ci], so that fullsize_upsample can change it. - - */ - - ( *upsample->methods[ci] )( cinfo, compptr, - - input_buf[ci] + ( *in_row_group_ctr * upsample->rowgroup_height[ci] ), - - upsample->color_buf + ci ); - - } - - upsample->next_row_out = 0; - - } - - - - /* Color-convert and emit rows */ - - - - /* How many we have in the buffer: */ - - num_rows = (JDIMENSION) ( cinfo->max_v_samp_factor - upsample->next_row_out ); - - /* Not more than the distance to the end of the image. Need this test - - * in case the image height is not a multiple of max_v_samp_factor: - - */ - - if ( num_rows > upsample->rows_to_go ) { - - num_rows = upsample->rows_to_go; - } - - /* And not more than what the client can accept: */ - - out_rows_avail -= *out_row_ctr; - - if ( num_rows > out_rows_avail ) { - - num_rows = out_rows_avail; - } - - - - ( *cinfo->cconvert->color_convert )( cinfo, upsample->color_buf, - - (JDIMENSION) upsample->next_row_out, - - output_buf + *out_row_ctr, - - (int) num_rows ); - - - - /* Adjust counts */ - - *out_row_ctr += num_rows; - - upsample->rows_to_go -= num_rows; - - upsample->next_row_out += num_rows; - - /* When the buffer is emptied, declare this input row group consumed */ - - if ( upsample->next_row_out >= cinfo->max_v_samp_factor ) { - - ( *in_row_group_ctr )++; - } - -} - - - - - -/* - - * These are the routines invoked by sep_upsample to upsample pixel values - - * of a single component. One row group is processed per call. - - */ - - - - - -/* - - * For full-size components, we just make color_buf[ci] point at the - - * input buffer, and thus avoid copying any data. Note that this is - - * safe only because sep_upsample doesn't declare the input row group - - * "consumed" until we are done color converting and emitting it. - - */ - - - -METHODDEF void - -fullsize_upsample( j_decompress_ptr cinfo, jpeg_component_info * compptr, - - JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr ){ - - *output_data_ptr = input_data; - -} - - - - - -/* - - * This is a no-op version used for "uninteresting" components. - - * These components will not be referenced by color conversion. - - */ - - - -METHODDEF void - -noop_upsample( j_decompress_ptr cinfo, jpeg_component_info * compptr, - - JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr ){ - - *output_data_ptr = NULL; /* safety check */ - -} - - - - - -/* - - * This version handles any integral sampling ratios. - - * This is not used for typical JPEG files, so it need not be fast. - - * Nor, for that matter, is it particularly accurate: the algorithm is - - * simple replication of the input pixel onto the corresponding output - - * pixels. The hi-falutin sampling literature refers to this as a - - * "box filter". A box filter tends to introduce visible artifacts, - - * so if you are actually going to use 3:1 or 4:1 sampling ratios - - * you would be well advised to improve this code. - - */ - - - -METHODDEF void - -int_upsample( j_decompress_ptr cinfo, jpeg_component_info * compptr, - - JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr ){ - - my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample; - - JSAMPARRAY output_data = *output_data_ptr; - - register JSAMPROW inptr, outptr; - - register JSAMPLE invalue; - - register int h; - - JSAMPROW outend; - - int h_expand, v_expand; - - int inrow, outrow; - - - - h_expand = upsample->h_expand[compptr->component_index]; - - v_expand = upsample->v_expand[compptr->component_index]; - - - - inrow = outrow = 0; - - while ( outrow < cinfo->max_v_samp_factor ) { - - /* Generate one output row with proper horizontal expansion */ - - inptr = input_data[inrow]; - - outptr = output_data[outrow]; - - outend = outptr + cinfo->output_width; - - while ( outptr < outend ) { - - invalue = *inptr++; /* don't need GETJSAMPLE() here */ - - for ( h = h_expand; h > 0; h-- ) { - - *outptr++ = invalue; - - } - - } - - /* Generate any additional output rows by duplicating the first one */ - - if ( v_expand > 1 ) { - - jcopy_sample_rows( output_data, outrow, output_data, outrow + 1, - - v_expand - 1, cinfo->output_width ); - - } - - inrow++; - - outrow += v_expand; - - } - -} - - - - - -/* - - * Fast processing for the common case of 2:1 horizontal and 1:1 vertical. - - * It's still a box filter. - - */ - - - -METHODDEF void - -h2v1_upsample( j_decompress_ptr cinfo, jpeg_component_info * compptr, - - JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr ){ - - JSAMPARRAY output_data = *output_data_ptr; - - register JSAMPROW inptr, outptr; - - register JSAMPLE invalue; - - JSAMPROW outend; - - int inrow; - - - - for ( inrow = 0; inrow < cinfo->max_v_samp_factor; inrow++ ) { - - inptr = input_data[inrow]; - - outptr = output_data[inrow]; - - outend = outptr + cinfo->output_width; - - while ( outptr < outend ) { - - invalue = *inptr++; /* don't need GETJSAMPLE() here */ - - *outptr++ = invalue; - - *outptr++ = invalue; - - } - - } - -} - - - - - -/* - - * Fast processing for the common case of 2:1 horizontal and 2:1 vertical. - - * It's still a box filter. - - */ - - - -METHODDEF void - -h2v2_upsample( j_decompress_ptr cinfo, jpeg_component_info * compptr, - - JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr ){ - - JSAMPARRAY output_data = *output_data_ptr; - - register JSAMPROW inptr, outptr; - - register JSAMPLE invalue; - - JSAMPROW outend; - - int inrow, outrow; - - - - inrow = outrow = 0; - - while ( outrow < cinfo->max_v_samp_factor ) { - - inptr = input_data[inrow]; - - outptr = output_data[outrow]; - - outend = outptr + cinfo->output_width; - - while ( outptr < outend ) { - - invalue = *inptr++; /* don't need GETJSAMPLE() here */ - - *outptr++ = invalue; - - *outptr++ = invalue; - - } - - jcopy_sample_rows( output_data, outrow, output_data, outrow + 1, - - 1, cinfo->output_width ); - - inrow++; - - outrow += 2; - - } - -} - - - - - -/* - - * Fancy processing for the common case of 2:1 horizontal and 1:1 vertical. - - * - - * The upsampling algorithm is linear interpolation between pixel centers, - - * also known as a "triangle filter". This is a good compromise between - - * speed and visual quality. The centers of the output pixels are 1/4 and 3/4 - - * of the way between input pixel centers. - - * - - * A note about the "bias" calculations: when rounding fractional values to - - * integer, we do not want to always round 0.5 up to the next integer. - - * If we did that, we'd introduce a noticeable bias towards larger values. - - * Instead, this code is arranged so that 0.5 will be rounded up or down at - - * alternate pixel locations (a simple ordered dither pattern). - - */ - - - -METHODDEF void - -h2v1_fancy_upsample( j_decompress_ptr cinfo, jpeg_component_info * compptr, - - JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr ){ - - JSAMPARRAY output_data = *output_data_ptr; - - register JSAMPROW inptr, outptr; - - register int invalue; - - register JDIMENSION colctr; - - int inrow; - - - - for ( inrow = 0; inrow < cinfo->max_v_samp_factor; inrow++ ) { - - inptr = input_data[inrow]; - - outptr = output_data[inrow]; - - /* Special case for first column */ - - invalue = GETJSAMPLE( *inptr++ ); - - *outptr++ = (JSAMPLE) invalue; - - *outptr++ = (JSAMPLE) ( ( invalue * 3 + GETJSAMPLE( *inptr ) + 2 ) >> 2 ); - - - - for ( colctr = compptr->downsampled_width - 2; colctr > 0; colctr-- ) { - - /* General case: 3/4 * nearer pixel + 1/4 * further pixel */ - - invalue = GETJSAMPLE( *inptr++ ) * 3; - - *outptr++ = (JSAMPLE) ( ( invalue + GETJSAMPLE( inptr[-2] ) + 1 ) >> 2 ); - - *outptr++ = (JSAMPLE) ( ( invalue + GETJSAMPLE( *inptr ) + 2 ) >> 2 ); - - } - - - - /* Special case for last column */ - - invalue = GETJSAMPLE( *inptr ); - - *outptr++ = (JSAMPLE) ( ( invalue * 3 + GETJSAMPLE( inptr[-1] ) + 1 ) >> 2 ); - - *outptr++ = (JSAMPLE) invalue; - - } - -} - - - - - -/* - - * Fancy processing for the common case of 2:1 horizontal and 2:1 vertical. - - * Again a triangle filter; see comments for h2v1 case, above. - - * - - * It is OK for us to reference the adjacent input rows because we demanded - - * context from the main buffer controller (see initialization code). - - */ - - - -METHODDEF void - -h2v2_fancy_upsample( j_decompress_ptr cinfo, jpeg_component_info * compptr, - - JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr ){ - - JSAMPARRAY output_data = *output_data_ptr; - - register JSAMPROW inptr0, inptr1, outptr; - -#if BITS_IN_JSAMPLE == 8 - - register int thiscolsum, lastcolsum, nextcolsum; - -#else - - register INT32 thiscolsum, lastcolsum, nextcolsum; - -#endif - - register JDIMENSION colctr; - - int inrow, outrow, v; - - - - inrow = outrow = 0; - - while ( outrow < cinfo->max_v_samp_factor ) { - - for ( v = 0; v < 2; v++ ) { - - /* inptr0 points to nearest input row, inptr1 points to next nearest */ - - inptr0 = input_data[inrow]; - - if ( v == 0 ) { /* next nearest is row above */ - - inptr1 = input_data[inrow - 1]; - } - - else{ /* next nearest is row below */ - - inptr1 = input_data[inrow + 1]; - } - - outptr = output_data[outrow++]; - - - - /* Special case for first column */ - - thiscolsum = GETJSAMPLE( *inptr0++ ) * 3 + GETJSAMPLE( *inptr1++ ); - - nextcolsum = GETJSAMPLE( *inptr0++ ) * 3 + GETJSAMPLE( *inptr1++ ); - - *outptr++ = (JSAMPLE) ( ( thiscolsum * 4 + 8 ) >> 4 ); - - *outptr++ = (JSAMPLE) ( ( thiscolsum * 3 + nextcolsum + 7 ) >> 4 ); - - lastcolsum = thiscolsum; thiscolsum = nextcolsum; - - - - for ( colctr = compptr->downsampled_width - 2; colctr > 0; colctr-- ) { - - /* General case: 3/4 * nearer pixel + 1/4 * further pixel in each */ - - /* dimension, thus 9/16, 3/16, 3/16, 1/16 overall */ - - nextcolsum = GETJSAMPLE( *inptr0++ ) * 3 + GETJSAMPLE( *inptr1++ ); - - *outptr++ = (JSAMPLE) ( ( thiscolsum * 3 + lastcolsum + 8 ) >> 4 ); - - *outptr++ = (JSAMPLE) ( ( thiscolsum * 3 + nextcolsum + 7 ) >> 4 ); - - lastcolsum = thiscolsum; thiscolsum = nextcolsum; - - } - - - - /* Special case for last column */ - - *outptr++ = (JSAMPLE) ( ( thiscolsum * 3 + lastcolsum + 8 ) >> 4 ); - - *outptr++ = (JSAMPLE) ( ( thiscolsum * 4 + 7 ) >> 4 ); - - } - - inrow++; - - } - -} - - - - - -/* - - * Module initialization routine for upsampling. - - */ - - - -GLOBAL void - -jinit_upsampler( j_decompress_ptr cinfo ){ - - my_upsample_ptr upsample; - - int ci; - - jpeg_component_info * compptr; - - boolean need_buffer, do_fancy; - - int h_in_group, v_in_group, h_out_group, v_out_group; - - - - upsample = (my_upsample_ptr) - - ( *cinfo->mem->alloc_small )( (j_common_ptr) cinfo, JPOOL_IMAGE, - - SIZEOF( my_upsampler ) ); - - cinfo->upsample = (struct jpeg_upsampler *) upsample; - - upsample->pub.start_pass = start_pass_upsample; - - upsample->pub.upsample = sep_upsample; - - upsample->pub.need_context_rows = FALSE; /* until we find out differently */ - - - - if ( cinfo->CCIR601_sampling ) { /* this isn't supported */ - - ERREXIT( cinfo, JERR_CCIR601_NOTIMPL ); - } - - - - /* jdmainct.c doesn't support context rows when min_DCT_scaled_size = 1, - - * so don't ask for it. - - */ - - do_fancy = cinfo->do_fancy_upsampling && cinfo->min_DCT_scaled_size > 1; - - - - /* Verify we can handle the sampling factors, select per-component methods, - - * and create storage as needed. - - */ - - for ( ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components; - - ci++, compptr++ ) { - - /* Compute size of an "input group" after IDCT scaling. This many samples - - * are to be converted to max_h_samp_factor * max_v_samp_factor pixels. - - */ - - h_in_group = ( compptr->h_samp_factor * compptr->DCT_scaled_size ) / - - cinfo->min_DCT_scaled_size; - - v_in_group = ( compptr->v_samp_factor * compptr->DCT_scaled_size ) / - - cinfo->min_DCT_scaled_size; - - h_out_group = cinfo->max_h_samp_factor; - - v_out_group = cinfo->max_v_samp_factor; - - upsample->rowgroup_height[ci] = v_in_group; /* save for use later */ - - need_buffer = TRUE; - - if ( !compptr->component_needed ) { - - /* Don't bother to upsample an uninteresting component. */ - - upsample->methods[ci] = noop_upsample; - - need_buffer = FALSE; - - } - else if ( h_in_group == h_out_group && v_in_group == v_out_group ) { - - /* Fullsize components can be processed without any work. */ - - upsample->methods[ci] = fullsize_upsample; - - need_buffer = FALSE; - - } - else if ( h_in_group * 2 == h_out_group && - - v_in_group == v_out_group ) { - - /* Special cases for 2h1v upsampling */ - - if ( do_fancy && compptr->downsampled_width > 2 ) { - - upsample->methods[ci] = h2v1_fancy_upsample; - } - - else{ - - upsample->methods[ci] = h2v1_upsample; - } - - } - else if ( h_in_group * 2 == h_out_group && - - v_in_group * 2 == v_out_group ) { - - /* Special cases for 2h2v upsampling */ - - if ( do_fancy && compptr->downsampled_width > 2 ) { - - upsample->methods[ci] = h2v2_fancy_upsample; - - upsample->pub.need_context_rows = TRUE; - - } - else{ - - upsample->methods[ci] = h2v2_upsample; - } - - } - else if ( ( h_out_group % h_in_group ) == 0 && - - ( v_out_group % v_in_group ) == 0 ) { - - /* Generic integral-factors upsampling method */ - - upsample->methods[ci] = int_upsample; - - upsample->h_expand[ci] = (UINT8) ( h_out_group / h_in_group ); - - upsample->v_expand[ci] = (UINT8) ( v_out_group / v_in_group ); - - } - else{ - - ERREXIT( cinfo, JERR_FRACT_SAMPLE_NOTIMPL ); - } - - if ( need_buffer ) { - - upsample->color_buf[ci] = ( *cinfo->mem->alloc_sarray ) - - ( (j_common_ptr) cinfo, JPOOL_IMAGE, - - (JDIMENSION) jround_up( (long) cinfo->output_width, - - (long) cinfo->max_h_samp_factor ), - - (JDIMENSION) cinfo->max_v_samp_factor ); - - } - - } - -} diff --git a/tools/urt/libs/jpeg6/jdtrans.cpp b/tools/urt/libs/jpeg6/jdtrans.cpp deleted file mode 100644 index b70fbdf..0000000 --- a/tools/urt/libs/jpeg6/jdtrans.cpp +++ /dev/null @@ -1,249 +0,0 @@ -/* - - * jdtrans.c - - * - - * Copyright (C) 1995, Thomas G. Lane. - - * This file is part of the Independent JPEG Group's software. - - * For conditions of distribution and use, see the accompanying README file. - - * - - * This file contains library routines for transcoding decompression, - - * that is, reading raw DCT coefficient arrays from an input JPEG file. - - * The routines in jdapimin.c will also be needed by a transcoder. - - */ - - - -#define JPEG_INTERNALS - -#include "jinclude.h" - -#include "radiant_jpeglib.h" - - - - - -/* Forward declarations */ - -LOCAL void transdecode_master_selection JPP( (j_decompress_ptr cinfo) ); - - - - - -/* - - * Read the coefficient arrays from a JPEG file. - - * jpeg_read_header must be completed before calling this. - - * - - * The entire image is read into a set of virtual coefficient-block arrays, - - * one per component. The return value is a pointer to the array of - - * virtual-array descriptors. These can be manipulated directly via the - - * JPEG memory manager, or handed off to jpeg_write_coefficients(). - - * To release the memory occupied by the virtual arrays, call - - * jpeg_finish_decompress() when done with the data. - - * - - * Returns NULL if suspended. This case need be checked only if - - * a suspending data source is used. - - */ - - - -GLOBAL jvirt_barray_ptr * - -jpeg_read_coefficients( j_decompress_ptr cinfo ){ - - if ( cinfo->global_state == DSTATE_READY ) { - - /* First call: initialize active modules */ - - transdecode_master_selection( cinfo ); - - cinfo->global_state = DSTATE_RDCOEFS; - - } - else if ( cinfo->global_state != DSTATE_RDCOEFS ) { - - ERREXIT1( cinfo, JERR_BAD_STATE, cinfo->global_state ); - } - - /* Absorb whole file into the coef buffer */ - - for (;; ) { - - int retcode; - - /* Call progress monitor hook if present */ - - if ( cinfo->progress != NULL ) { - - ( *cinfo->progress->progress_monitor )( (j_common_ptr) cinfo ); - } - - /* Absorb some more input */ - - retcode = ( *cinfo->inputctl->consume_input )( cinfo ); - - if ( retcode == JPEG_SUSPENDED ) { - - return NULL; - } - - if ( retcode == JPEG_REACHED_EOI ) { - - break; - } - - /* Advance progress counter if appropriate */ - - if ( cinfo->progress != NULL && - - ( retcode == JPEG_ROW_COMPLETED || retcode == JPEG_REACHED_SOS ) ) { - - if ( ++cinfo->progress->pass_counter >= cinfo->progress->pass_limit ) { - - /* startup underestimated number of scans; ratchet up one scan */ - - cinfo->progress->pass_limit += (long) cinfo->total_iMCU_rows; - - } - - } - - } - - /* Set state so that jpeg_finish_decompress does the right thing */ - - cinfo->global_state = DSTATE_STOPPING; - - return cinfo->coef->coef_arrays; - -} - - - - - -/* - - * Master selection of decompression modules for transcoding. - - * This substitutes for jdmaster.c's initialization of the full decompressor. - - */ - - - -LOCAL void - -transdecode_master_selection( j_decompress_ptr cinfo ){ - - /* Entropy decoding: either Huffman or arithmetic coding. */ - - if ( cinfo->arith_code ) { - - ERREXIT( cinfo, JERR_ARITH_NOTIMPL ); - - } - else { - - if ( cinfo->progressive_mode ) { - -#ifdef D_PROGRESSIVE_SUPPORTED - - jinit_phuff_decoder( cinfo ); - -#else - - ERREXIT( cinfo, JERR_NOT_COMPILED ); - -#endif - - } - else{ - - jinit_huff_decoder( cinfo ); - } - - } - - - - /* Always get a full-image coefficient buffer. */ - - jinit_d_coef_controller( cinfo, TRUE ); - - - - /* We can now tell the memory manager to allocate virtual arrays. */ - - ( *cinfo->mem->realize_virt_arrays )( (j_common_ptr) cinfo ); - - - - /* Initialize input side of decompressor to consume first scan. */ - - ( *cinfo->inputctl->start_input_pass )( cinfo ); - - - - /* Initialize progress monitoring. */ - - if ( cinfo->progress != NULL ) { - - int nscans; - - /* Estimate number of scans to set pass_limit. */ - - if ( cinfo->progressive_mode ) { - - /* Arbitrarily estimate 2 interleaved DC scans + 3 AC scans/component. */ - - nscans = 2 + 3 * cinfo->num_components; - - } - else if ( cinfo->inputctl->has_multiple_scans ) { - - /* For a nonprogressive multiscan file, estimate 1 scan per component. */ - - nscans = cinfo->num_components; - - } - else { - - nscans = 1; - - } - - cinfo->progress->pass_counter = 0L; - - cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows * nscans; - - cinfo->progress->completed_passes = 0; - - cinfo->progress->total_passes = 1; - - } - -} diff --git a/tools/urt/libs/jpeg6/jerror.cpp b/tools/urt/libs/jpeg6/jerror.cpp deleted file mode 100644 index 317488b..0000000 --- a/tools/urt/libs/jpeg6/jerror.cpp +++ /dev/null @@ -1,235 +0,0 @@ -/* - * jerror.c - * - * Copyright (C) 1991-1994, Thomas G. Lane. - * This file is part of the Independent JPEG Group's software. - * For conditions of distribution and use, see the accompanying README file. - * - * This file contains simple error-reporting and trace-message routines. - * These are suitable for Unix-like systems and others where writing to - * stderr is the right thing to do. Many applications will want to replace - * some or all of these routines. - * - * These routines are used by both the compression and decompression code. - */ - -/* this is not a core library module, so it doesn't define JPEG_INTERNALS */ -#include "jinclude.h" -#include "radiant_jpeglib.h" -#include "jversion.h" -#include "jerror.h" - -#ifndef EXIT_FAILURE /* define exit() codes if not provided */ -#define EXIT_FAILURE 1 -#endif - - -/* - * Create the message string table. - * We do this from the master message list in jerror.h by re-reading - * jerror.h with a suitable definition for macro JMESSAGE. - * The message table is made an external symbol just in case any applications - * want to refer to it directly. - */ - -#ifdef NEED_SHORT_EXTERNAL_NAMES -#define jpeg_std_message_table jMsgTable -#endif - -#define JMESSAGE( code,string ) string, - -const char * const jpeg_std_message_table[] = { -#include "jerror.h" - NULL -}; - -// Rad additions, longjmp out of the LoadJPGBuff -GLOBAL jmp_buf rad_loadfailed; -GLOBAL char rad_errormsg[JMSG_LENGTH_MAX]; - -/* - * Error exit handler: must not return to caller. - * - * Applications may override this if they want to get control back after - * an error. Typically one would longjmp somewhere instead of exiting. - * The setjmp buffer can be made a private field within an expanded error - * handler object. Note that the info needed to generate an error message - * is stored in the error object, so you can generate the message now or - * later, at your convenience. - * You should make sure that the JPEG object is cleaned up (with jpeg_abort - * or jpeg_destroy) at some point. - */ - -METHODDEF void -error_exit( j_common_ptr cinfo ){ -// char buffer[JMSG_LENGTH_MAX]; - - /* Create the message */ - ( *cinfo->err->format_message )( cinfo,rad_errormsg ); - - /* Let the memory manager delete any temp files before we die */ - jpeg_destroy( cinfo ); - - longjmp( rad_loadfailed, -1 ); -} - - -/* - * Actual output of an error or trace message. - * Applications may override this method to send JPEG messages somewhere - * other than stderr. - */ - -METHODDEF void -output_message( j_common_ptr cinfo ){ - char buffer[JMSG_LENGTH_MAX]; - - /* Create the message */ - ( *cinfo->err->format_message )( cinfo, buffer ); - - /* Send it to stderr, adding a newline */ - printf( "%s\n", buffer ); -} - - -/* - * Decide whether to emit a trace or warning message. - * msg_level is one of: - * -1: recoverable corrupt-data warning, may want to abort. - * 0: important advisory messages (always display to user). - * 1: first level of tracing detail. - * 2,3,...: successively more detailed tracing messages. - * An application might override this method if it wanted to abort on warnings - * or change the policy about which messages to display. - */ - -METHODDEF void -emit_message( j_common_ptr cinfo, int msg_level ){ - struct jpeg_error_mgr * err = cinfo->err; - - if ( msg_level < 0 ) { - /* It's a warning message. Since corrupt files may generate many warnings, - * the policy implemented here is to show only the first warning, - * unless trace_level >= 3. - */ - if ( err->num_warnings == 0 || err->trace_level >= 3 ) { - ( *err->output_message )( cinfo ); - } - /* Always count warnings in num_warnings. */ - err->num_warnings++; - } - else { - /* It's a trace message. Show it if trace_level >= msg_level. */ - if ( err->trace_level >= msg_level ) { - ( *err->output_message )( cinfo ); - } - } -} - - -/* - * Format a message string for the most recent JPEG error or message. - * The message is stored into buffer, which should be at least JMSG_LENGTH_MAX - * characters. Note that no '\n' character is added to the string. - * Few applications should need to override this method. - */ - -METHODDEF void -format_message( j_common_ptr cinfo, char * buffer ){ - struct jpeg_error_mgr * err = cinfo->err; - int msg_code = err->msg_code; - const char * msgtext = NULL; - const char * msgptr; - char ch; - boolean isstring; - - /* Look up message string in proper table */ - if ( msg_code > 0 && msg_code <= err->last_jpeg_message ) { - msgtext = err->jpeg_message_table[msg_code]; - } - else if ( err->addon_message_table != NULL && - msg_code >= err->first_addon_message && - msg_code <= err->last_addon_message ) { - msgtext = err->addon_message_table[msg_code - err->first_addon_message]; - } - - /* Defend against bogus message number */ - if ( msgtext == NULL ) { - err->msg_parm.i[0] = msg_code; - msgtext = err->jpeg_message_table[0]; - } - - /* Check for string parameter, as indicated by %s in the message text */ - isstring = FALSE; - msgptr = msgtext; - while ( ( ch = *msgptr++ ) != '\0' ) { - if ( ch == '%' ) { - if ( *msgptr == 's' ) { - isstring = TRUE; - } - break; - } - } - - /* Format the message into the passed buffer */ - if ( isstring ) { - sprintf( buffer, msgtext, err->msg_parm.s ); - } - else{ - sprintf( buffer, msgtext, - err->msg_parm.i[0], err->msg_parm.i[1], - err->msg_parm.i[2], err->msg_parm.i[3], - err->msg_parm.i[4], err->msg_parm.i[5], - err->msg_parm.i[6], err->msg_parm.i[7] ); - } -} - - -/* - * Reset error state variables at start of a new image. - * This is called during compression startup to reset trace/error - * processing to default state, without losing any application-specific - * method pointers. An application might possibly want to override - * this method if it has additional error processing state. - */ - -METHODDEF void -reset_error_mgr( j_common_ptr cinfo ){ - cinfo->err->num_warnings = 0; - /* trace_level is not reset since it is an application-supplied parameter */ - cinfo->err->msg_code = 0; /* may be useful as a flag for "no error" */ -} - - -/* - * Fill in the standard error-handling methods in a jpeg_error_mgr object. - * Typical call is: - * struct jpeg_compress_struct cinfo; - * struct jpeg_error_mgr err; - * - * cinfo.err = jpeg_std_error(&err); - * after which the application may override some of the methods. - */ - -GLOBAL struct jpeg_error_mgr * -jpeg_std_error( struct jpeg_error_mgr * err ){ - err->error_exit = error_exit; - err->emit_message = emit_message; - err->output_message = output_message; - err->format_message = format_message; - err->reset_error_mgr = reset_error_mgr; - - err->trace_level = 0; /* default = no tracing */ - err->num_warnings = 0; /* no warnings emitted yet */ - err->msg_code = 0; /* may be useful as a flag for "no error" */ - - /* Initialize message table pointers */ - err->jpeg_message_table = jpeg_std_message_table; - err->last_jpeg_message = (int) JMSG_LASTMSGCODE - 1; - - err->addon_message_table = NULL; - err->first_addon_message = 0; /* for safety */ - err->last_addon_message = 0; - - return err; -} diff --git a/tools/urt/libs/jpeg6/jerror.h b/tools/urt/libs/jpeg6/jerror.h deleted file mode 100644 index a1ee2a0..0000000 --- a/tools/urt/libs/jpeg6/jerror.h +++ /dev/null @@ -1,278 +0,0 @@ -/* - * jerror.h - * - * Copyright (C) 1994-1995, Thomas G. Lane. - * This file is part of the Independent JPEG Group's software. - * For conditions of distribution and use, see the accompanying README file. - * - * This file defines the error and message codes for the JPEG library. - * Edit this file to add new codes, or to translate the message strings to - * some other language. - * A set of error-reporting macros are defined too. Some applications using - * the JPEG library may wish to include this file to get the error codes - * and/or the macros. - */ - -/* - * To define the enum list of message codes, include this file without - * defining macro JMESSAGE. To create a message string table, include it - * again with a suitable JMESSAGE definition (see jerror.c for an example). - */ -#ifndef JMESSAGE -#ifndef JERROR_H -/* First time through, define the enum list */ -#define JMAKE_ENUM_LIST -#else -/* Repeated inclusions of this file are no-ops unless JMESSAGE is defined */ -#define JMESSAGE( code,string ) -#endif /* JERROR_H */ -#endif /* JMESSAGE */ - -#ifdef JMAKE_ENUM_LIST - -typedef enum { - -#define JMESSAGE( code,string ) code, - -#endif /* JMAKE_ENUM_LIST */ - -JMESSAGE ( JMSG_NOMESSAGE, "Bogus message code %d" ) /* Must be first entry! */ - -/* For maintenance convenience, list is alphabetical by message code name */ -JMESSAGE ( JERR_ARITH_NOTIMPL, - "Sorry, there are legal restrictions on arithmetic coding" ) -JMESSAGE ( JERR_BAD_ALIGN_TYPE, "ALIGN_TYPE is wrong, please fix" ) -JMESSAGE ( JERR_BAD_ALLOC_CHUNK, "MAX_ALLOC_CHUNK is wrong, please fix" ) -JMESSAGE ( JERR_BAD_BUFFER_MODE, "Bogus buffer control mode" ) -JMESSAGE ( JERR_BAD_COMPONENT_ID, "Invalid component ID %d in SOS" ) -JMESSAGE ( JERR_BAD_DCTSIZE, "IDCT output block size %d not supported" ) -JMESSAGE ( JERR_BAD_IN_COLORSPACE, "Bogus input colorspace" ) -JMESSAGE ( JERR_BAD_J_COLORSPACE, "Bogus JPEG colorspace" ) -JMESSAGE ( JERR_BAD_LENGTH, "Bogus marker length" ) -JMESSAGE ( JERR_BAD_MCU_SIZE, "Sampling factors too large for interleaved scan" ) -JMESSAGE ( JERR_BAD_POOL_ID, "Invalid memory pool code %d" ) -JMESSAGE ( JERR_BAD_PRECISION, "Unsupported JPEG data precision %d" ) -JMESSAGE ( JERR_BAD_PROGRESSION, - "Invalid progressive parameters Ss=%d Se=%d Ah=%d Al=%d" ) -JMESSAGE ( JERR_BAD_PROG_SCRIPT, - "Invalid progressive parameters at scan script entry %d" ) -JMESSAGE ( JERR_BAD_SAMPLING, "Bogus sampling factors" ) -JMESSAGE ( JERR_BAD_SCAN_SCRIPT, "Invalid scan script at entry %d" ) -JMESSAGE ( JERR_BAD_STATE, "Improper call to JPEG library in state %d" ) -JMESSAGE ( JERR_BAD_VIRTUAL_ACCESS, "Bogus virtual array access" ) -JMESSAGE ( JERR_BUFFER_SIZE, "Buffer passed to JPEG library is too small" ) -JMESSAGE ( JERR_CANT_SUSPEND, "Suspension not allowed here" ) -JMESSAGE ( JERR_CCIR601_NOTIMPL, "CCIR601 sampling not implemented yet" ) -JMESSAGE ( JERR_COMPONENT_COUNT, "Too many color components: %d, max %d" ) -JMESSAGE ( JERR_CONVERSION_NOTIMPL, "Unsupported color conversion request" ) -JMESSAGE ( JERR_DAC_INDEX, "Bogus DAC index %d" ) -JMESSAGE ( JERR_DAC_VALUE, "Bogus DAC value 0x%x" ) -JMESSAGE ( JERR_DHT_COUNTS, "Bogus DHT counts" ) -JMESSAGE ( JERR_DHT_INDEX, "Bogus DHT index %d" ) -JMESSAGE ( JERR_DQT_INDEX, "Bogus DQT index %d" ) -JMESSAGE ( JERR_EMPTY_IMAGE, "Empty JPEG image (DNL not supported)" ) -JMESSAGE ( JERR_EMS_READ, "Read from EMS failed" ) -JMESSAGE ( JERR_EMS_WRITE, "Write to EMS failed" ) -JMESSAGE ( JERR_EOI_EXPECTED, "Didn't expect more than one scan" ) -JMESSAGE ( JERR_FILE_READ, "Input file read error" ) -JMESSAGE ( JERR_FILE_WRITE, "Output file write error --- out of disk space?" ) -JMESSAGE ( JERR_FRACT_SAMPLE_NOTIMPL, "Fractional sampling not implemented yet" ) -JMESSAGE ( JERR_HUFF_CLEN_OVERFLOW, "Huffman code size table overflow" ) -JMESSAGE ( JERR_HUFF_MISSING_CODE, "Missing Huffman code table entry" ) -JMESSAGE ( JERR_IMAGE_TOO_BIG, "Maximum supported image dimension is %u pixels" ) -JMESSAGE ( JERR_INPUT_EMPTY, "Empty input file" ) -JMESSAGE ( JERR_INPUT_EOF, "Premature end of input file" ) -JMESSAGE ( JERR_MISMATCHED_QUANT_TABLE, - "Cannot transcode due to multiple use of quantization table %d" ) -JMESSAGE ( JERR_MISSING_DATA, "Scan script does not transmit all data" ) -JMESSAGE ( JERR_MODE_CHANGE, "Invalid color quantization mode change" ) -JMESSAGE ( JERR_NOTIMPL, "Not implemented yet" ) -JMESSAGE ( JERR_NOT_COMPILED, "Requested feature was omitted at compile time" ) -JMESSAGE ( JERR_NO_PROGRESSIVE, "Progressive JPEGs not supported, use regular JPEG instead" ) -JMESSAGE ( JERR_NO_BACKING_STORE, "Backing store not supported" ) -JMESSAGE ( JERR_NO_HUFF_TABLE, "Huffman table 0x%02x was not defined" ) -JMESSAGE ( JERR_NO_IMAGE, "JPEG datastream contains no image" ) -JMESSAGE ( JERR_NO_QUANT_TABLE, "Quantization table 0x%02x was not defined" ) -JMESSAGE ( JERR_NO_SOI, "Not a JPEG file: starts with 0x%02x 0x%02x" ) -JMESSAGE ( JERR_OUT_OF_MEMORY, "Insufficient memory (case %d)" ) -JMESSAGE ( JERR_QUANT_COMPONENTS, - "Cannot quantize more than %d color components" ) -JMESSAGE ( JERR_QUANT_FEW_COLORS, "Cannot quantize to fewer than %d colors" ) -JMESSAGE ( JERR_QUANT_MANY_COLORS, "Cannot quantize to more than %d colors" ) -JMESSAGE ( JERR_SOF_DUPLICATE, "Invalid JPEG file structure: two SOF markers" ) -JMESSAGE ( JERR_SOF_NO_SOS, "Invalid JPEG file structure: missing SOS marker" ) -JMESSAGE ( JERR_SOF_UNSUPPORTED, "Unsupported JPEG process: SOF type 0x%02x" ) -JMESSAGE ( JERR_SOI_DUPLICATE, "Invalid JPEG file structure: two SOI markers" ) -JMESSAGE ( JERR_SOS_NO_SOF, "Invalid JPEG file structure: SOS before SOF" ) -JMESSAGE ( JERR_TFILE_CREATE, "Failed to create temporary file %s" ) -JMESSAGE ( JERR_TFILE_READ, "Read failed on temporary file" ) -JMESSAGE ( JERR_TFILE_SEEK, "Seek failed on temporary file" ) -JMESSAGE ( JERR_TFILE_WRITE, - "Write failed on temporary file --- out of disk space?" ) -JMESSAGE ( JERR_TOO_LITTLE_DATA, "Application transferred too few scanlines" ) -JMESSAGE ( JERR_UNKNOWN_MARKER, "Unsupported marker type 0x%02x" ) -JMESSAGE ( JERR_VIRTUAL_BUG, "Virtual array controller messed up" ) -JMESSAGE ( JERR_WIDTH_OVERFLOW, "Image too wide for this implementation" ) -JMESSAGE ( JERR_XMS_READ, "Read from XMS failed" ) -JMESSAGE ( JERR_XMS_WRITE, "Write to XMS failed" ) -JMESSAGE ( JMSG_COPYRIGHT, JCOPYRIGHT ) -JMESSAGE ( JMSG_VERSION, JVERSION ) -JMESSAGE ( JTRC_16BIT_TABLES, - "Caution: quantization tables are too coarse for baseline JPEG" ) -JMESSAGE ( JTRC_ADOBE, - "Adobe APP14 marker: version %d, flags 0x%04x 0x%04x, transform %d" ) -JMESSAGE ( JTRC_APP0, "Unknown APP0 marker (not JFIF), length %u" ) -JMESSAGE ( JTRC_APP14, "Unknown APP14 marker (not Adobe), length %u" ) -JMESSAGE ( JTRC_DAC, "Define Arithmetic Table 0x%02x: 0x%02x" ) -JMESSAGE ( JTRC_DHT, "Define Huffman Table 0x%02x" ) -JMESSAGE ( JTRC_DQT, "Define Quantization Table %d precision %d" ) -JMESSAGE ( JTRC_DRI, "Define Restart Interval %u" ) -JMESSAGE ( JTRC_EMS_CLOSE, "Freed EMS handle %u" ) -JMESSAGE ( JTRC_EMS_OPEN, "Obtained EMS handle %u" ) -JMESSAGE ( JTRC_EOI, "End Of Image" ) -JMESSAGE ( JTRC_HUFFBITS, " %3d %3d %3d %3d %3d %3d %3d %3d" ) -JMESSAGE ( JTRC_JFIF, "JFIF APP0 marker, density %dx%d %d" ) -JMESSAGE ( JTRC_JFIF_BADTHUMBNAILSIZE, - "Warning: thumbnail image size does not match data length %u" ) -JMESSAGE ( JTRC_JFIF_MINOR, "Unknown JFIF minor revision number %d.%02d" ) -JMESSAGE ( JTRC_JFIF_THUMBNAIL, " with %d x %d thumbnail image" ) -JMESSAGE ( JTRC_MISC_MARKER, "Skipping marker 0x%02x, length %u" ) -JMESSAGE ( JTRC_PARMLESS_MARKER, "Unexpected marker 0x%02x" ) -JMESSAGE ( JTRC_QUANTVALS, " %4u %4u %4u %4u %4u %4u %4u %4u" ) -JMESSAGE ( JTRC_QUANT_3_NCOLORS, "Quantizing to %d = %d*%d*%d colors" ) -JMESSAGE ( JTRC_QUANT_NCOLORS, "Quantizing to %d colors" ) -JMESSAGE ( JTRC_QUANT_SELECTED, "Selected %d colors for quantization" ) -JMESSAGE ( JTRC_RECOVERY_ACTION, "At marker 0x%02x, recovery action %d" ) -JMESSAGE ( JTRC_RST, "RST%d" ) -JMESSAGE ( JTRC_SMOOTH_NOTIMPL, - "Smoothing not supported with nonstandard sampling ratios" ) -JMESSAGE ( JTRC_SOF, "Start Of Frame 0x%02x: width=%u, height=%u, components=%d" ) -JMESSAGE ( JTRC_SOF_COMPONENT, " Component %d: %dhx%dv q=%d" ) -JMESSAGE ( JTRC_SOI, "Start of Image" ) -JMESSAGE ( JTRC_SOS, "Start Of Scan: %d components" ) -JMESSAGE ( JTRC_SOS_COMPONENT, " Component %d: dc=%d ac=%d" ) -JMESSAGE ( JTRC_SOS_PARAMS, " Ss=%d, Se=%d, Ah=%d, Al=%d" ) -JMESSAGE ( JTRC_TFILE_CLOSE, "Closed temporary file %s" ) -JMESSAGE ( JTRC_TFILE_OPEN, "Opened temporary file %s" ) -JMESSAGE ( JTRC_UNKNOWN_IDS, - "Unrecognized component IDs %d %d %d, assuming YCbCr" ) -JMESSAGE ( JTRC_XMS_CLOSE, "Freed XMS handle %u" ) -JMESSAGE ( JTRC_XMS_OPEN, "Obtained XMS handle %u" ) -JMESSAGE ( JWRN_ADOBE_XFORM, "Unknown Adobe color transform code %d" ) -JMESSAGE ( JWRN_BOGUS_PROGRESSION, - "Inconsistent progression sequence for component %d coefficient %d" ) -JMESSAGE ( JWRN_EXTRANEOUS_DATA, - "Corrupt JPEG data: %u extraneous bytes before marker 0x%02x" ) -JMESSAGE ( JWRN_HIT_MARKER, "Corrupt JPEG data: premature end of data segment" ) -JMESSAGE ( JWRN_HUFF_BAD_CODE, "Corrupt JPEG data: bad Huffman code" ) -JMESSAGE ( JWRN_JFIF_MAJOR, "Warning: unknown JFIF revision number %d.%02d" ) -JMESSAGE ( JWRN_JPEG_EOF, "Premature end of JPEG file" ) -JMESSAGE ( JWRN_MUST_RESYNC, - "Corrupt JPEG data: found marker 0x%02x instead of RST%d" ) -JMESSAGE ( JWRN_NOT_SEQUENTIAL, "Invalid SOS parameters for sequential JPEG" ) -JMESSAGE ( JWRN_TOO_MUCH_DATA, "Application transferred too many scanlines" ) - -#ifdef JMAKE_ENUM_LIST - -JMSG_LASTMSGCODE -} J_MESSAGE_CODE; - -#undef JMAKE_ENUM_LIST -#endif /* JMAKE_ENUM_LIST */ - -/* Zap JMESSAGE macro so that future re-inclusions do nothing by default */ -#undef JMESSAGE - -#ifndef JERROR_H -#define JERROR_H - -// Rad additions, using longjmp to recover from errors -#include -EXTERN jmp_buf rad_loadfailed; -EXTERN char rad_errormsg[JMSG_LENGTH_MAX]; - -/* Macros to simplify using the error and trace message stuff */ -/* The first parameter is either type of cinfo pointer */ - -/* Fatal errors (print message and exit) */ -#define ERREXIT( cinfo,code ) \ - ( ( cinfo )->err->msg_code = ( code ), \ - ( *( cinfo )->err->error_exit )( (j_common_ptr) ( cinfo ) ) ) -#define ERREXIT1( cinfo,code,p1 ) \ - ( ( cinfo )->err->msg_code = ( code ), \ - ( cinfo )->err->msg_parm.i[0] = ( p1 ), \ - ( *( cinfo )->err->error_exit )( (j_common_ptr) ( cinfo ) ) ) -#define ERREXIT2( cinfo,code,p1,p2 ) \ - ( ( cinfo )->err->msg_code = ( code ), \ - ( cinfo )->err->msg_parm.i[0] = ( p1 ), \ - ( cinfo )->err->msg_parm.i[1] = ( p2 ), \ - ( *( cinfo )->err->error_exit )( (j_common_ptr) ( cinfo ) ) ) -#define ERREXIT3( cinfo,code,p1,p2,p3 ) \ - ( ( cinfo )->err->msg_code = ( code ), \ - ( cinfo )->err->msg_parm.i[0] = ( p1 ), \ - ( cinfo )->err->msg_parm.i[1] = ( p2 ), \ - ( cinfo )->err->msg_parm.i[2] = ( p3 ), \ - ( *( cinfo )->err->error_exit )( (j_common_ptr) ( cinfo ) ) ) -#define ERREXIT4( cinfo,code,p1,p2,p3,p4 ) \ - ( ( cinfo )->err->msg_code = ( code ), \ - ( cinfo )->err->msg_parm.i[0] = ( p1 ), \ - ( cinfo )->err->msg_parm.i[1] = ( p2 ), \ - ( cinfo )->err->msg_parm.i[2] = ( p3 ), \ - ( cinfo )->err->msg_parm.i[3] = ( p4 ), \ - ( *( cinfo )->err->error_exit )( (j_common_ptr) ( cinfo ) ) ) -#define ERREXITS( cinfo,code,str ) \ - ( ( cinfo )->err->msg_code = ( code ), \ - strncpy( ( cinfo )->err->msg_parm.s, ( str ), JMSG_STR_PARM_MAX ), \ - ( *( cinfo )->err->error_exit )( (j_common_ptr) ( cinfo ) ) ) - -#define MAKESTMT( stuff ) do { stuff } while ( 0 ) - -/* Nonfatal errors (we can keep going, but the data is probably corrupt) */ -#define WARNMS( cinfo,code ) \ - ( ( cinfo )->err->msg_code = ( code ), \ - ( *( cinfo )->err->emit_message )( (j_common_ptr) ( cinfo ), -1 ) ) -#define WARNMS1( cinfo,code,p1 ) \ - ( ( cinfo )->err->msg_code = ( code ), \ - ( cinfo )->err->msg_parm.i[0] = ( p1 ), \ - ( *( cinfo )->err->emit_message )( (j_common_ptr) ( cinfo ), -1 ) ) -#define WARNMS2( cinfo,code,p1,p2 ) \ - ( ( cinfo )->err->msg_code = ( code ), \ - ( cinfo )->err->msg_parm.i[0] = ( p1 ), \ - ( cinfo )->err->msg_parm.i[1] = ( p2 ), \ - ( *( cinfo )->err->emit_message )( (j_common_ptr) ( cinfo ), -1 ) ) - -/* Informational/debugging messages */ -#define TRACEMS( cinfo,lvl,code ) \ - ( ( cinfo )->err->msg_code = ( code ), \ - ( *( cinfo )->err->emit_message )( (j_common_ptr) ( cinfo ), ( lvl ) ) ) -#define TRACEMS1( cinfo,lvl,code,p1 ) \ - ( ( cinfo )->err->msg_code = ( code ), \ - ( cinfo )->err->msg_parm.i[0] = ( p1 ), \ - ( *( cinfo )->err->emit_message )( (j_common_ptr) ( cinfo ), ( lvl ) ) ) -#define TRACEMS2( cinfo,lvl,code,p1,p2 ) \ - ( ( cinfo )->err->msg_code = ( code ), \ - ( cinfo )->err->msg_parm.i[0] = ( p1 ), \ - ( cinfo )->err->msg_parm.i[1] = ( p2 ), \ - ( *( cinfo )->err->emit_message )( (j_common_ptr) ( cinfo ), ( lvl ) ) ) -#define TRACEMS3( cinfo,lvl,code,p1,p2,p3 ) \ - MAKESTMT( int * _mp = ( cinfo )->err->msg_parm.i; \ - _mp[0] = ( p1 ); _mp[1] = ( p2 ); _mp[2] = ( p3 ); \ - ( cinfo )->err->msg_code = ( code ); \ - ( *( cinfo )->err->emit_message )( (j_common_ptr) ( cinfo ), ( lvl ) ); ) -#define TRACEMS4( cinfo,lvl,code,p1,p2,p3,p4 ) \ - MAKESTMT( int * _mp = ( cinfo )->err->msg_parm.i; \ - _mp[0] = ( p1 ); _mp[1] = ( p2 ); _mp[2] = ( p3 ); _mp[3] = ( p4 ); \ - ( cinfo )->err->msg_code = ( code ); \ - ( *( cinfo )->err->emit_message )( (j_common_ptr) ( cinfo ), ( lvl ) ); ) -#define TRACEMS8( cinfo,lvl,code,p1,p2,p3,p4,p5,p6,p7,p8 ) \ - MAKESTMT( int * _mp = ( cinfo )->err->msg_parm.i; \ - _mp[0] = ( p1 ); _mp[1] = ( p2 ); _mp[2] = ( p3 ); _mp[3] = ( p4 ); \ - _mp[4] = ( p5 ); _mp[5] = ( p6 ); _mp[6] = ( p7 ); _mp[7] = ( p8 ); \ - ( cinfo )->err->msg_code = ( code ); \ - ( *( cinfo )->err->emit_message )( (j_common_ptr) ( cinfo ), ( lvl ) ); ) -#define TRACEMSS( cinfo,lvl,code,str ) \ - ( ( cinfo )->err->msg_code = ( code ), \ - strncpy( ( cinfo )->err->msg_parm.s, ( str ), JMSG_STR_PARM_MAX ), \ - ( *( cinfo )->err->emit_message )( (j_common_ptr) ( cinfo ), ( lvl ) ) ) - -#endif /* JERROR_H */ diff --git a/tools/urt/libs/jpeg6/jfdctflt.cpp b/tools/urt/libs/jpeg6/jfdctflt.cpp deleted file mode 100644 index f2a630c..0000000 --- a/tools/urt/libs/jpeg6/jfdctflt.cpp +++ /dev/null @@ -1,333 +0,0 @@ -/* - - * jfdctflt.c - - * - - * Copyright (C) 1994, Thomas G. Lane. - - * This file is part of the Independent JPEG Group's software. - - * For conditions of distribution and use, see the accompanying README file. - - * - - * This file contains a floating-point implementation of the - - * forward DCT (Discrete Cosine Transform). - - * - - * This implementation should be more accurate than either of the integer - - * DCT implementations. However, it may not give the same results on all - - * machines because of differences in roundoff behavior. Speed will depend - - * on the hardware's floating point capacity. - - * - - * A 2-D DCT can be done by 1-D DCT on each row followed by 1-D DCT - - * on each column. Direct algorithms are also available, but they are - - * much more complex and seem not to be any faster when reduced to code. - - * - - * This implementation is based on Arai, Agui, and Nakajima's algorithm for - - * scaled DCT. Their original paper (Trans. IEICE E-71(11):1095) is in - - * Japanese, but the algorithm is described in the Pennebaker & Mitchell - - * JPEG textbook (see REFERENCES section in file README). The following code - - * is based directly on figure 4-8 in P&M. - - * While an 8-point DCT cannot be done in less than 11 multiplies, it is - - * possible to arrange the computation so that many of the multiplies are - - * simple scalings of the final outputs. These multiplies can then be - - * folded into the multiplications or divisions by the JPEG quantization - - * table entries. The AA&N method leaves only 5 multiplies and 29 adds - - * to be done in the DCT itself. - - * The primary disadvantage of this method is that with a fixed-point - - * implementation, accuracy is lost due to imprecise representation of the - - * scaled quantization values. However, that problem does not arise if - - * we use floating point arithmetic. - - */ - - - -#define JPEG_INTERNALS - -#include "jinclude.h" - -#include "radiant_jpeglib.h" - -#include "jdct.h" /* Private declarations for DCT subsystem */ - - - -#ifdef DCT_FLOAT_SUPPORTED - - - - - -/* - - * This module is specialized to the case DCTSIZE = 8. - - */ - - - -#if DCTSIZE != 8 - -Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */ - -#endif - - - - - -/* - - * Perform the forward DCT on one block of samples. - - */ - - - -GLOBAL void - -jpeg_fdct_float( FAST_FLOAT * data ){ - - FAST_FLOAT tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7; - - FAST_FLOAT tmp10, tmp11, tmp12, tmp13; - - FAST_FLOAT z1, z2, z3, z4, z5, z11, z13; - - FAST_FLOAT *dataptr; - - int ctr; - - - - /* Pass 1: process rows. */ - - - - dataptr = data; - - for ( ctr = DCTSIZE - 1; ctr >= 0; ctr-- ) { - - tmp0 = dataptr[0] + dataptr[7]; - - tmp7 = dataptr[0] - dataptr[7]; - - tmp1 = dataptr[1] + dataptr[6]; - - tmp6 = dataptr[1] - dataptr[6]; - - tmp2 = dataptr[2] + dataptr[5]; - - tmp5 = dataptr[2] - dataptr[5]; - - tmp3 = dataptr[3] + dataptr[4]; - - tmp4 = dataptr[3] - dataptr[4]; - - - - /* Even part */ - - - - tmp10 = tmp0 + tmp3; /* phase 2 */ - - tmp13 = tmp0 - tmp3; - - tmp11 = tmp1 + tmp2; - - tmp12 = tmp1 - tmp2; - - - - dataptr[0] = tmp10 + tmp11; /* phase 3 */ - - dataptr[4] = tmp10 - tmp11; - - - - z1 = ( tmp12 + tmp13 ) * ( (FAST_FLOAT) 0.707106781 ); /* c4 */ - - dataptr[2] = tmp13 + z1; /* phase 5 */ - - dataptr[6] = tmp13 - z1; - - - - /* Odd part */ - - - - tmp10 = tmp4 + tmp5; /* phase 2 */ - - tmp11 = tmp5 + tmp6; - - tmp12 = tmp6 + tmp7; - - - - /* The rotator is modified from fig 4-8 to avoid extra negations. */ - - z5 = ( tmp10 - tmp12 ) * ( (FAST_FLOAT) 0.382683433 ); /* c6 */ - - z2 = ( (FAST_FLOAT) 0.541196100 ) * tmp10 + z5; /* c2-c6 */ - - z4 = ( (FAST_FLOAT) 1.306562965 ) * tmp12 + z5; /* c2+c6 */ - - z3 = tmp11 * ( (FAST_FLOAT) 0.707106781 ); /* c4 */ - - - - z11 = tmp7 + z3; /* phase 5 */ - - z13 = tmp7 - z3; - - - - dataptr[5] = z13 + z2; /* phase 6 */ - - dataptr[3] = z13 - z2; - - dataptr[1] = z11 + z4; - - dataptr[7] = z11 - z4; - - - - dataptr += DCTSIZE; /* advance pointer to next row */ - - } - - - - /* Pass 2: process columns. */ - - - - dataptr = data; - - for ( ctr = DCTSIZE - 1; ctr >= 0; ctr-- ) { - - tmp0 = dataptr[DCTSIZE * 0] + dataptr[DCTSIZE * 7]; - - tmp7 = dataptr[DCTSIZE * 0] - dataptr[DCTSIZE * 7]; - - tmp1 = dataptr[DCTSIZE * 1] + dataptr[DCTSIZE * 6]; - - tmp6 = dataptr[DCTSIZE * 1] - dataptr[DCTSIZE * 6]; - - tmp2 = dataptr[DCTSIZE * 2] + dataptr[DCTSIZE * 5]; - - tmp5 = dataptr[DCTSIZE * 2] - dataptr[DCTSIZE * 5]; - - tmp3 = dataptr[DCTSIZE * 3] + dataptr[DCTSIZE * 4]; - - tmp4 = dataptr[DCTSIZE * 3] - dataptr[DCTSIZE * 4]; - - - - /* Even part */ - - - - tmp10 = tmp0 + tmp3; /* phase 2 */ - - tmp13 = tmp0 - tmp3; - - tmp11 = tmp1 + tmp2; - - tmp12 = tmp1 - tmp2; - - - - dataptr[DCTSIZE * 0] = tmp10 + tmp11; /* phase 3 */ - - dataptr[DCTSIZE * 4] = tmp10 - tmp11; - - - - z1 = ( tmp12 + tmp13 ) * ( (FAST_FLOAT) 0.707106781 ); /* c4 */ - - dataptr[DCTSIZE * 2] = tmp13 + z1; /* phase 5 */ - - dataptr[DCTSIZE * 6] = tmp13 - z1; - - - - /* Odd part */ - - - - tmp10 = tmp4 + tmp5; /* phase 2 */ - - tmp11 = tmp5 + tmp6; - - tmp12 = tmp6 + tmp7; - - - - /* The rotator is modified from fig 4-8 to avoid extra negations. */ - - z5 = ( tmp10 - tmp12 ) * ( (FAST_FLOAT) 0.382683433 ); /* c6 */ - - z2 = ( (FAST_FLOAT) 0.541196100 ) * tmp10 + z5; /* c2-c6 */ - - z4 = ( (FAST_FLOAT) 1.306562965 ) * tmp12 + z5; /* c2+c6 */ - - z3 = tmp11 * ( (FAST_FLOAT) 0.707106781 ); /* c4 */ - - - - z11 = tmp7 + z3; /* phase 5 */ - - z13 = tmp7 - z3; - - - - dataptr[DCTSIZE * 5] = z13 + z2; /* phase 6 */ - - dataptr[DCTSIZE * 3] = z13 - z2; - - dataptr[DCTSIZE * 1] = z11 + z4; - - dataptr[DCTSIZE * 7] = z11 - z4; - - - - dataptr++; /* advance pointer to next column */ - - } - -} - - - -#endif /* DCT_FLOAT_SUPPORTED */ diff --git a/tools/urt/libs/jpeg6/jidctflt.cpp b/tools/urt/libs/jpeg6/jidctflt.cpp deleted file mode 100644 index b54a836..0000000 --- a/tools/urt/libs/jpeg6/jidctflt.cpp +++ /dev/null @@ -1,479 +0,0 @@ -/* - - * jidctflt.c - - * - - * Copyright (C) 1994, Thomas G. Lane. - - * This file is part of the Independent JPEG Group's software. - - * For conditions of distribution and use, see the accompanying README file. - - * - - * This file contains a floating-point implementation of the - - * inverse DCT (Discrete Cosine Transform). In the IJG code, this routine - - * must also perform dequantization of the input coefficients. - - * - - * This implementation should be more accurate than either of the integer - - * IDCT implementations. However, it may not give the same results on all - - * machines because of differences in roundoff behavior. Speed will depend - - * on the hardware's floating point capacity. - - * - - * A 2-D IDCT can be done by 1-D IDCT on each column followed by 1-D IDCT - - * on each row (or vice versa, but it's more convenient to emit a row at - - * a time). Direct algorithms are also available, but they are much more - - * complex and seem not to be any faster when reduced to code. - - * - - * This implementation is based on Arai, Agui, and Nakajima's algorithm for - - * scaled DCT. Their original paper (Trans. IEICE E-71(11):1095) is in - - * Japanese, but the algorithm is described in the Pennebaker & Mitchell - - * JPEG textbook (see REFERENCES section in file README). The following code - - * is based directly on figure 4-8 in P&M. - - * While an 8-point DCT cannot be done in less than 11 multiplies, it is - - * possible to arrange the computation so that many of the multiplies are - - * simple scalings of the final outputs. These multiplies can then be - - * folded into the multiplications or divisions by the JPEG quantization - - * table entries. The AA&N method leaves only 5 multiplies and 29 adds - - * to be done in the DCT itself. - - * The primary disadvantage of this method is that with a fixed-point - - * implementation, accuracy is lost due to imprecise representation of the - - * scaled quantization values. However, that problem does not arise if - - * we use floating point arithmetic. - - */ - - - -#define JPEG_INTERNALS - -#include "jinclude.h" - -#include "radiant_jpeglib.h" - -#include "jdct.h" /* Private declarations for DCT subsystem */ - - - -#ifdef DCT_FLOAT_SUPPORTED - - - - - -/* - - * This module is specialized to the case DCTSIZE = 8. - - */ - - - -#if DCTSIZE != 8 - -Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */ - -#endif - - - - - -/* Dequantize a coefficient by multiplying it by the multiplier-table - - * entry; produce a float result. - - */ - - - -#define DEQUANTIZE( coef,quantval ) ( ( (FAST_FLOAT) ( coef ) ) * ( quantval ) ) - - - - - -/* - - * Perform dequantization and inverse DCT on one block of coefficients. - - */ - - - -GLOBAL void - -jpeg_idct_float( j_decompress_ptr cinfo, jpeg_component_info * compptr, - - JCOEFPTR coef_block, - - JSAMPARRAY output_buf, JDIMENSION output_col ){ - - FAST_FLOAT tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7; - - FAST_FLOAT tmp10, tmp11, tmp12, tmp13; - - FAST_FLOAT z5, z10, z11, z12, z13; - - JCOEFPTR inptr; - - FLOAT_MULT_TYPE * quantptr; - - FAST_FLOAT * wsptr; - - JSAMPROW outptr; - - JSAMPLE *range_limit = IDCT_range_limit( cinfo ); - - int ctr; - - FAST_FLOAT workspace[DCTSIZE2]; /* buffers data between passes */ - - SHIFT_TEMPS - - - - /* Pass 1: process columns from input, store into work array. */ - - - - inptr = coef_block; - - quantptr = (FLOAT_MULT_TYPE *) compptr->dct_table; - - wsptr = workspace; - - for ( ctr = DCTSIZE; ctr > 0; ctr-- ) { - - /* Due to quantization, we will usually find that many of the input - - * coefficients are zero, especially the AC terms. We can exploit this - - * by short-circuiting the IDCT calculation for any column in which all - - * the AC terms are zero. In that case each output is equal to the - - * DC coefficient (with scale factor as needed). - - * With typical images and quantization tables, half or more of the - - * column DCT calculations can be simplified this way. - - */ - - - - if ( ( inptr[DCTSIZE * 1] | inptr[DCTSIZE * 2] | inptr[DCTSIZE * 3] | - - inptr[DCTSIZE * 4] | inptr[DCTSIZE * 5] | inptr[DCTSIZE * 6] | - - inptr[DCTSIZE * 7] ) == 0 ) { - - /* AC terms all zero */ - - FAST_FLOAT dcval = DEQUANTIZE( inptr[DCTSIZE * 0], quantptr[DCTSIZE * 0] ); - - - - wsptr[DCTSIZE * 0] = dcval; - - wsptr[DCTSIZE * 1] = dcval; - - wsptr[DCTSIZE * 2] = dcval; - - wsptr[DCTSIZE * 3] = dcval; - - wsptr[DCTSIZE * 4] = dcval; - - wsptr[DCTSIZE * 5] = dcval; - - wsptr[DCTSIZE * 6] = dcval; - - wsptr[DCTSIZE * 7] = dcval; - - - - inptr++; /* advance pointers to next column */ - - quantptr++; - - wsptr++; - - continue; - - } - - - - /* Even part */ - - - - tmp0 = DEQUANTIZE( inptr[DCTSIZE * 0], quantptr[DCTSIZE * 0] ); - - tmp1 = DEQUANTIZE( inptr[DCTSIZE * 2], quantptr[DCTSIZE * 2] ); - - tmp2 = DEQUANTIZE( inptr[DCTSIZE * 4], quantptr[DCTSIZE * 4] ); - - tmp3 = DEQUANTIZE( inptr[DCTSIZE * 6], quantptr[DCTSIZE * 6] ); - - - - tmp10 = tmp0 + tmp2; /* phase 3 */ - - tmp11 = tmp0 - tmp2; - - - - tmp13 = tmp1 + tmp3; /* phases 5-3 */ - - tmp12 = ( tmp1 - tmp3 ) * ( (FAST_FLOAT) 1.414213562 ) - tmp13; /* 2*c4 */ - - - - tmp0 = tmp10 + tmp13; /* phase 2 */ - - tmp3 = tmp10 - tmp13; - - tmp1 = tmp11 + tmp12; - - tmp2 = tmp11 - tmp12; - - - - /* Odd part */ - - - - tmp4 = DEQUANTIZE( inptr[DCTSIZE * 1], quantptr[DCTSIZE * 1] ); - - tmp5 = DEQUANTIZE( inptr[DCTSIZE * 3], quantptr[DCTSIZE * 3] ); - - tmp6 = DEQUANTIZE( inptr[DCTSIZE * 5], quantptr[DCTSIZE * 5] ); - - tmp7 = DEQUANTIZE( inptr[DCTSIZE * 7], quantptr[DCTSIZE * 7] ); - - - - z13 = tmp6 + tmp5; /* phase 6 */ - - z10 = tmp6 - tmp5; - - z11 = tmp4 + tmp7; - - z12 = tmp4 - tmp7; - - - - tmp7 = z11 + z13; /* phase 5 */ - - tmp11 = ( z11 - z13 ) * ( (FAST_FLOAT) 1.414213562 ); /* 2*c4 */ - - - - z5 = ( z10 + z12 ) * ( (FAST_FLOAT) 1.847759065 ); /* 2*c2 */ - - tmp10 = ( (FAST_FLOAT) 1.082392200 ) * z12 - z5; /* 2*(c2-c6) */ - - tmp12 = ( (FAST_FLOAT) -2.613125930 ) * z10 + z5; /* -2*(c2+c6) */ - - - - tmp6 = tmp12 - tmp7; /* phase 2 */ - - tmp5 = tmp11 - tmp6; - - tmp4 = tmp10 + tmp5; - - - - wsptr[DCTSIZE * 0] = tmp0 + tmp7; - - wsptr[DCTSIZE * 7] = tmp0 - tmp7; - - wsptr[DCTSIZE * 1] = tmp1 + tmp6; - - wsptr[DCTSIZE * 6] = tmp1 - tmp6; - - wsptr[DCTSIZE * 2] = tmp2 + tmp5; - - wsptr[DCTSIZE * 5] = tmp2 - tmp5; - - wsptr[DCTSIZE * 4] = tmp3 + tmp4; - - wsptr[DCTSIZE * 3] = tmp3 - tmp4; - - - - inptr++; /* advance pointers to next column */ - - quantptr++; - - wsptr++; - - } - - - - /* Pass 2: process rows from work array, store into output array. */ - - /* Note that we must descale the results by a factor of 8 == 2**3. */ - - - - wsptr = workspace; - - for ( ctr = 0; ctr < DCTSIZE; ctr++ ) { - - outptr = output_buf[ctr] + output_col; - - /* Rows of zeroes can be exploited in the same way as we did with columns. - - * However, the column calculation has created many nonzero AC terms, so - - * the simplification applies less often (typically 5% to 10% of the time). - - * And testing floats for zero is relatively expensive, so we don't bother. - - */ - - - - /* Even part */ - - - - tmp10 = wsptr[0] + wsptr[4]; - - tmp11 = wsptr[0] - wsptr[4]; - - - - tmp13 = wsptr[2] + wsptr[6]; - - tmp12 = ( wsptr[2] - wsptr[6] ) * ( (FAST_FLOAT) 1.414213562 ) - tmp13; - - - - tmp0 = tmp10 + tmp13; - - tmp3 = tmp10 - tmp13; - - tmp1 = tmp11 + tmp12; - - tmp2 = tmp11 - tmp12; - - - - /* Odd part */ - - - - z13 = wsptr[5] + wsptr[3]; - - z10 = wsptr[5] - wsptr[3]; - - z11 = wsptr[1] + wsptr[7]; - - z12 = wsptr[1] - wsptr[7]; - - - - tmp7 = z11 + z13; - - tmp11 = ( z11 - z13 ) * ( (FAST_FLOAT) 1.414213562 ); - - - - z5 = ( z10 + z12 ) * ( (FAST_FLOAT) 1.847759065 ); /* 2*c2 */ - - tmp10 = ( (FAST_FLOAT) 1.082392200 ) * z12 - z5; /* 2*(c2-c6) */ - - tmp12 = ( (FAST_FLOAT) -2.613125930 ) * z10 + z5; /* -2*(c2+c6) */ - - - - tmp6 = tmp12 - tmp7; - - tmp5 = tmp11 - tmp6; - - tmp4 = tmp10 + tmp5; - - - - /* Final output stage: scale down by a factor of 8 and range-limit */ - - - - outptr[0] = range_limit[(int) DESCALE( (INT32) ( tmp0 + tmp7 ), 3 ) - - & RANGE_MASK]; - - outptr[7] = range_limit[(int) DESCALE( (INT32) ( tmp0 - tmp7 ), 3 ) - - & RANGE_MASK]; - - outptr[1] = range_limit[(int) DESCALE( (INT32) ( tmp1 + tmp6 ), 3 ) - - & RANGE_MASK]; - - outptr[6] = range_limit[(int) DESCALE( (INT32) ( tmp1 - tmp6 ), 3 ) - - & RANGE_MASK]; - - outptr[2] = range_limit[(int) DESCALE( (INT32) ( tmp2 + tmp5 ), 3 ) - - & RANGE_MASK]; - - outptr[5] = range_limit[(int) DESCALE( (INT32) ( tmp2 - tmp5 ), 3 ) - - & RANGE_MASK]; - - outptr[4] = range_limit[(int) DESCALE( (INT32) ( tmp3 + tmp4 ), 3 ) - - & RANGE_MASK]; - - outptr[3] = range_limit[(int) DESCALE( (INT32) ( tmp3 - tmp4 ), 3 ) - - & RANGE_MASK]; - - - - wsptr += DCTSIZE; /* advance pointer to next row */ - - } - -} - - - -#endif /* DCT_FLOAT_SUPPORTED */ diff --git a/tools/urt/libs/jpeg6/jinclude.h b/tools/urt/libs/jpeg6/jinclude.h deleted file mode 100644 index eb2d3c2..0000000 --- a/tools/urt/libs/jpeg6/jinclude.h +++ /dev/null @@ -1,91 +0,0 @@ -/* - * jinclude.h - * - * Copyright (C) 1991-1994, Thomas G. Lane. - * This file is part of the Independent JPEG Group's software. - * For conditions of distribution and use, see the accompanying README file. - * - * This file exists to provide a single place to fix any problems with - * including the wrong system include files. (Common problems are taken - * care of by the standard jconfig symbols, but on really weird systems - * you may have to edit this file.) - * - * NOTE: this file is NOT intended to be included by applications using the - * JPEG library. Most applications need only include jpeglib.h. - */ - - -/* Include auto-config file to find out which system include files we need. */ - -#include "jconfig.h" /* auto configuration options */ -#define JCONFIG_INCLUDED /* so that jpeglib.h doesn't do it again */ - -/* - * We need the NULL macro and size_t typedef. - * On an ANSI-conforming system it is sufficient to include . - * Otherwise, we get them from or ; we may have to - * pull in as well. - * Note that the core JPEG library does not require ; - * only the default error handler and data source/destination modules do. - * But we must pull it in because of the references to FILE in jpeglib.h. - * You can remove those references if you want to compile without . - */ - -#ifdef HAVE_STDDEF_H -#include -#endif - -#ifdef HAVE_STDLIB_H -#include -#endif - -#ifdef NEED_SYS_TYPES_H -#include -#endif - -#include - -/* - * We need memory copying and zeroing functions, plus strncpy(). - * ANSI and System V implementations declare these in . - * BSD doesn't have the mem() functions, but it does have bcopy()/bzero(). - * Some systems may declare memset and memcpy in . - * - * NOTE: we assume the size parameters to these functions are of type size_t. - * Change the casts in these macros if not! - */ - -#ifdef NEED_BSD_STRINGS - -#include -#define MEMZERO( target,size ) bzero( (void *)( target ), (size_t)( size ) ) -#define MEMCOPY( dest,src,size ) bcopy( (const void *)( src ), (void *)( dest ), (size_t)( size ) ) - -#else /* not BSD, assume ANSI/SysV string lib */ - -#include -#define MEMZERO( target,size ) memset( (void *)( target ), 0, (size_t)( size ) ) -#define MEMCOPY( dest,src,size ) memcpy( (void *)( dest ), (const void *)( src ), (size_t)( size ) ) - -#endif - -/* - * In ANSI C, and indeed any rational implementation, size_t is also the - * type returned by sizeof(). However, it seems there are some irrational - * implementations out there, in which sizeof() returns an int even though - * size_t is defined as long or unsigned long. To ensure consistent results - * we always use this SIZEOF() macro in place of using sizeof() directly. - */ - -#define SIZEOF( object ) ( (size_t) sizeof( object ) ) - -/* - * The modules that use fread() and fwrite() always invoke them through - * these macros. On some systems you may need to twiddle the argument casts. - * CAUTION: argument order is different from underlying functions! - */ - -#define JFREAD( file,buf,sizeofbuf ) \ - ( (size_t) fread( (void *) ( buf ), (size_t) 1, (size_t) ( sizeofbuf ), ( file ) ) ) -#define JFWRITE( file,buf,sizeofbuf ) \ - ( (size_t) fwrite( (const void *) ( buf ), (size_t) 1, (size_t) ( sizeofbuf ), ( file ) ) ) diff --git a/tools/urt/libs/jpeg6/jmemmgr.cpp b/tools/urt/libs/jpeg6/jmemmgr.cpp deleted file mode 100644 index 2ec1d38..0000000 --- a/tools/urt/libs/jpeg6/jmemmgr.cpp +++ /dev/null @@ -1,2238 +0,0 @@ -/* - - * jmemmgr.c - - * - - * Copyright (C) 1991-1995, Thomas G. Lane. - - * This file is part of the Independent JPEG Group's software. - - * For conditions of distribution and use, see the accompanying README file. - - * - - * This file contains the JPEG system-independent memory management - - * routines. This code is usable across a wide variety of machines; most - - * of the system dependencies have been isolated in a separate file. - - * The major functions provided here are: - - * * pool-based allocation and freeing of memory; - - * * policy decisions about how to divide available memory among the - - * virtual arrays; - - * * control logic for swapping virtual arrays between main memory and - - * backing storage. - - * The separate system-dependent file provides the actual backing-storage - - * access code, and it contains the policy decision about how much total - - * main memory to use. - - * This file is system-dependent in the sense that some of its functions - - * are unnecessary in some systems. For example, if there is enough virtual - - * memory so that backing storage will never be used, much of the virtual - - * array control logic could be removed. (Of course, if you have that much - - * memory then you shouldn't care about a little bit of unused code...) - - */ - - - -#define JPEG_INTERNALS - -#define AM_MEMORY_MANAGER /* we define jvirt_Xarray_control structs */ - -#include "jinclude.h" - -#include "radiant_jpeglib.h" - -#include "jmemsys.h" /* import the system-dependent declarations */ - - - -#ifndef NO_GETENV - -#ifndef HAVE_STDLIB_H /* should declare getenv() */ - -extern char * getenv JPP( (const char * name) ); - -#endif - -#endif - - - - - -/* - - * Some important notes: - - * The allocation routines provided here must never return NULL. - - * They should exit to error_exit if unsuccessful. - - * - - * It's not a good idea to try to merge the sarray and barray routines, - - * even though they are textually almost the same, because samples are - - * usually stored as bytes while coefficients are shorts or ints. Thus, - - * in machines where byte pointers have a different representation from - - * word pointers, the resulting machine code could not be the same. - - */ - - - - - -/* - - * Many machines require storage alignment: longs must start on 4-byte - - * boundaries, doubles on 8-byte boundaries, etc. On such machines, malloc() - - * always returns pointers that are multiples of the worst-case alignment - - * requirement, and we had better do so too. - - * There isn't any really portable way to determine the worst-case alignment - - * requirement. This module assumes that the alignment requirement is - - * multiples of sizeof(ALIGN_TYPE). - - * By default, we define ALIGN_TYPE as double. This is necessary on some - - * workstations (where doubles really do need 8-byte alignment) and will work - - * fine on nearly everything. If your machine has lesser alignment needs, - - * you can save a few bytes by making ALIGN_TYPE smaller. - - * The only place I know of where this will NOT work is certain Macintosh - - * 680x0 compilers that define double as a 10-byte IEEE extended float. - - * Doing 10-byte alignment is counterproductive because longwords won't be - - * aligned well. Put "#define ALIGN_TYPE long" in jconfig.h if you have - - * such a compiler. - - */ - - - -#ifndef ALIGN_TYPE /* so can override from jconfig.h */ - -#define ALIGN_TYPE double - -#endif - - - - - -/* - - * We allocate objects from "pools", where each pool is gotten with a single - - * request to jpeg_get_small() or jpeg_get_large(). There is no per-object - - * overhead within a pool, except for alignment padding. Each pool has a - - * header with a link to the next pool of the same class. - - * Small and large pool headers are identical except that the latter's - - * link pointer must be FAR on 80x86 machines. - - * Notice that the "real" header fields are union'ed with a dummy ALIGN_TYPE - - * field. This forces the compiler to make SIZEOF(small_pool_hdr) a multiple - - * of the alignment requirement of ALIGN_TYPE. - - */ - - - -typedef union small_pool_struct * small_pool_ptr; - - - -typedef union small_pool_struct { - - struct { - - small_pool_ptr next; /* next in list of pools */ - - size_t bytes_used; /* how many bytes already used within pool */ - - size_t bytes_left; /* bytes still available in this pool */ - - } hdr; - - ALIGN_TYPE dummy; /* included in union to ensure alignment */ - -} small_pool_hdr; - - - -typedef union large_pool_struct FAR * large_pool_ptr; - - - -typedef union large_pool_struct { - - struct { - - large_pool_ptr next; /* next in list of pools */ - - size_t bytes_used; /* how many bytes already used within pool */ - - size_t bytes_left; /* bytes still available in this pool */ - - } hdr; - - ALIGN_TYPE dummy; /* included in union to ensure alignment */ - -} large_pool_hdr; - - - - - -/* - - * Here is the full definition of a memory manager object. - - */ - - - -typedef struct { - - struct jpeg_memory_mgr pub; /* public fields */ - - - - /* Each pool identifier (lifetime class) names a linked list of pools. */ - - small_pool_ptr small_list[JPOOL_NUMPOOLS]; - - large_pool_ptr large_list[JPOOL_NUMPOOLS]; - - - - /* Since we only have one lifetime class of virtual arrays, only one - - * linked list is necessary (for each datatype). Note that the virtual - - * array control blocks being linked together are actually stored somewhere - - * in the small-pool list. - - */ - - jvirt_sarray_ptr virt_sarray_list; - - jvirt_barray_ptr virt_barray_list; - - - - /* This counts total space obtained from jpeg_get_small/large */ - - long total_space_allocated; - - - - /* alloc_sarray and alloc_barray set this value for use by virtual - - * array routines. - - */ - - JDIMENSION last_rowsperchunk; /* from most recent alloc_sarray/barray */ - -} my_memory_mgr; - - - -typedef my_memory_mgr * my_mem_ptr; - - - - - -/* - - * The control blocks for virtual arrays. - - * Note that these blocks are allocated in the "small" pool area. - - * System-dependent info for the associated backing store (if any) is hidden - - * inside the backing_store_info struct. - - */ - - - -struct jvirt_sarray_control { - - JSAMPARRAY mem_buffer; /* => the in-memory buffer */ - - JDIMENSION rows_in_array; /* total virtual array height */ - - JDIMENSION samplesperrow; /* width of array (and of memory buffer) */ - - JDIMENSION maxaccess; /* max rows accessed by access_virt_sarray */ - - JDIMENSION rows_in_mem; /* height of memory buffer */ - - JDIMENSION rowsperchunk; /* allocation chunk size in mem_buffer */ - - JDIMENSION cur_start_row; /* first logical row # in the buffer */ - - JDIMENSION first_undef_row; /* row # of first uninitialized row */ - - boolean pre_zero; /* pre-zero mode requested? */ - - boolean dirty; /* do current buffer contents need written? */ - - boolean b_s_open; /* is backing-store data valid? */ - - jvirt_sarray_ptr next; /* link to next virtual sarray control block */ - - backing_store_info b_s_info; /* System-dependent control info */ - -}; - - - -struct jvirt_barray_control { - - JBLOCKARRAY mem_buffer; /* => the in-memory buffer */ - - JDIMENSION rows_in_array; /* total virtual array height */ - - JDIMENSION blocksperrow; /* width of array (and of memory buffer) */ - - JDIMENSION maxaccess; /* max rows accessed by access_virt_barray */ - - JDIMENSION rows_in_mem; /* height of memory buffer */ - - JDIMENSION rowsperchunk; /* allocation chunk size in mem_buffer */ - - JDIMENSION cur_start_row; /* first logical row # in the buffer */ - - JDIMENSION first_undef_row; /* row # of first uninitialized row */ - - boolean pre_zero; /* pre-zero mode requested? */ - - boolean dirty; /* do current buffer contents need written? */ - - boolean b_s_open; /* is backing-store data valid? */ - - jvirt_barray_ptr next; /* link to next virtual barray control block */ - - backing_store_info b_s_info; /* System-dependent control info */ - -}; - - - - - -#ifdef MEM_STATS /* optional extra stuff for statistics */ - - - -LOCAL void - -print_mem_stats( j_common_ptr cinfo, int pool_id ){ - - my_mem_ptr mem = (my_mem_ptr) cinfo->mem; - - small_pool_ptr shdr_ptr; - - large_pool_ptr lhdr_ptr; - - - - /* Since this is only a debugging stub, we can cheat a little by using - - * fprintf directly rather than going through the trace message code. - - * This is helpful because message parm array can't handle longs. - - */ - - fprintf( stderr, "Freeing pool %d, total space = %ld\n", - - pool_id, mem->total_space_allocated ); - - - - for ( lhdr_ptr = mem->large_list[pool_id]; lhdr_ptr != NULL; - - lhdr_ptr = lhdr_ptr->hdr.next ) { - - fprintf( stderr, " Large chunk used %ld\n", - - (long) lhdr_ptr->hdr.bytes_used ); - - } - - - - for ( shdr_ptr = mem->small_list[pool_id]; shdr_ptr != NULL; - - shdr_ptr = shdr_ptr->hdr.next ) { - - fprintf( stderr, " Small chunk used %ld free %ld\n", - - (long) shdr_ptr->hdr.bytes_used, - - (long) shdr_ptr->hdr.bytes_left ); - - } - -} - - - -#endif /* MEM_STATS */ - - - - - -LOCAL void - -out_of_memory( j_common_ptr cinfo, int which ){ -/* Report an out-of-memory error and stop execution */ -/* If we compiled MEM_STATS support, report alloc requests before dying */ - -#ifdef MEM_STATS - - cinfo->err->trace_level = 2; /* force self_destruct to report stats */ - -#endif - - ERREXIT1( cinfo, JERR_OUT_OF_MEMORY, which ); - -} - - - - - -/* - - * Allocation of "small" objects. - - * - - * For these, we use pooled storage. When a new pool must be created, - - * we try to get enough space for the current request plus a "slop" factor, - - * where the slop will be the amount of leftover space in the new pool. - - * The speed vs. space tradeoff is largely determined by the slop values. - - * A different slop value is provided for each pool class (lifetime), - - * and we also distinguish the first pool of a class from later ones. - - * NOTE: the values given work fairly well on both 16- and 32-bit-int - - * machines, but may be too small if longs are 64 bits or more. - - */ - - - -static const size_t first_pool_slop[JPOOL_NUMPOOLS] = - -{ - - 1600, /* first PERMANENT pool */ - - 16000 /* first IMAGE pool */ - -}; - - - -static const size_t extra_pool_slop[JPOOL_NUMPOOLS] = - -{ - - 0, /* additional PERMANENT pools */ - - 5000 /* additional IMAGE pools */ - -}; - - - -#define MIN_SLOP 50 /* greater than 0 to avoid futile looping */ - - - - - -METHODDEF void * - -alloc_small( j_common_ptr cinfo, int pool_id, size_t sizeofobject ){ -/* Allocate a "small" object */ - - my_mem_ptr mem = (my_mem_ptr) cinfo->mem; - - small_pool_ptr hdr_ptr, prev_hdr_ptr; - - char * data_ptr; - - size_t odd_bytes, min_request, slop; - - - - /* Check for unsatisfiable request (do now to ensure no overflow below) */ - - if ( sizeofobject > (size_t) ( MAX_ALLOC_CHUNK - SIZEOF( small_pool_hdr ) ) ) { - - out_of_memory( cinfo, 1 ); /* request exceeds malloc's ability */ - - - - } - /* Round up the requested size to a multiple of SIZEOF(ALIGN_TYPE) */ - - odd_bytes = sizeofobject % SIZEOF( ALIGN_TYPE ); - - if ( odd_bytes > 0 ) { - - sizeofobject += SIZEOF( ALIGN_TYPE ) - odd_bytes; - } - - - - /* See if space is available in any existing pool */ - - if ( pool_id < 0 || pool_id >= JPOOL_NUMPOOLS ) { - - ERREXIT1( cinfo, JERR_BAD_POOL_ID, pool_id ); /* safety check */ - - } - prev_hdr_ptr = NULL; - - hdr_ptr = mem->small_list[pool_id]; - - while ( hdr_ptr != NULL ) { - - if ( hdr_ptr->hdr.bytes_left >= sizeofobject ) { - - break; /* found pool with enough space */ - - } - prev_hdr_ptr = hdr_ptr; - - hdr_ptr = hdr_ptr->hdr.next; - - } - - - - /* Time to make a new pool? */ - - if ( hdr_ptr == NULL ) { - - /* min_request is what we need now, slop is what will be leftover */ - - min_request = sizeofobject + SIZEOF( small_pool_hdr ); - - if ( prev_hdr_ptr == NULL ) { /* first pool in class? */ - - slop = first_pool_slop[pool_id]; - } - - else{ - - slop = extra_pool_slop[pool_id]; - } - - /* Don't ask for more than MAX_ALLOC_CHUNK */ - - if ( slop > (size_t) ( MAX_ALLOC_CHUNK - min_request ) ) { - - slop = (size_t) ( MAX_ALLOC_CHUNK - min_request ); - } - - /* Try to get space, if fail reduce slop and try again */ - - for (;; ) { - - hdr_ptr = (small_pool_ptr) jpeg_get_small( cinfo, min_request + slop ); - - if ( hdr_ptr != NULL ) { - - break; - } - - slop /= 2; - - if ( slop < MIN_SLOP ) { /* give up when it gets real small */ - - out_of_memory( cinfo, 2 ); /* jpeg_get_small failed */ - - } - } - - mem->total_space_allocated += min_request + slop; - - /* Success, initialize the new pool header and add to end of list */ - - hdr_ptr->hdr.next = NULL; - - hdr_ptr->hdr.bytes_used = 0; - - hdr_ptr->hdr.bytes_left = sizeofobject + slop; - - if ( prev_hdr_ptr == NULL ) { /* first pool in class? */ - - mem->small_list[pool_id] = hdr_ptr; - } - - else{ - - prev_hdr_ptr->hdr.next = hdr_ptr; - } - - } - - - - /* OK, allocate the object from the current pool */ - - data_ptr = (char *) ( hdr_ptr + 1 ); /* point to first data byte in pool */ - - data_ptr += hdr_ptr->hdr.bytes_used; /* point to place for object */ - - hdr_ptr->hdr.bytes_used += sizeofobject; - - hdr_ptr->hdr.bytes_left -= sizeofobject; - - - - return (void *) data_ptr; - -} - - - - - -/* - - * Allocation of "large" objects. - - * - - * The external semantics of these are the same as "small" objects, - - * except that FAR pointers are used on 80x86. However the pool - - * management heuristics are quite different. We assume that each - - * request is large enough that it may as well be passed directly to - - * jpeg_get_large; the pool management just links everything together - - * so that we can free it all on demand. - - * Note: the major use of "large" objects is in JSAMPARRAY and JBLOCKARRAY - - * structures. The routines that create these structures (see below) - - * deliberately bunch rows together to ensure a large request size. - - */ - - - -METHODDEF void FAR * - -alloc_large( j_common_ptr cinfo, int pool_id, size_t sizeofobject ){ -/* Allocate a "large" object */ - - my_mem_ptr mem = (my_mem_ptr) cinfo->mem; - - large_pool_ptr hdr_ptr; - - size_t odd_bytes; - - - - /* Check for unsatisfiable request (do now to ensure no overflow below) */ - - if ( sizeofobject > (size_t) ( MAX_ALLOC_CHUNK - SIZEOF( large_pool_hdr ) ) ) { - - out_of_memory( cinfo, 3 ); /* request exceeds malloc's ability */ - - - - } - /* Round up the requested size to a multiple of SIZEOF(ALIGN_TYPE) */ - - odd_bytes = sizeofobject % SIZEOF( ALIGN_TYPE ); - - if ( odd_bytes > 0 ) { - - sizeofobject += SIZEOF( ALIGN_TYPE ) - odd_bytes; - } - - - - /* Always make a new pool */ - - if ( pool_id < 0 || pool_id >= JPOOL_NUMPOOLS ) { - - ERREXIT1( cinfo, JERR_BAD_POOL_ID, pool_id ); /* safety check */ - - - - } - hdr_ptr = (large_pool_ptr) jpeg_get_large( cinfo, sizeofobject + - - SIZEOF( large_pool_hdr ) ); - - if ( hdr_ptr == NULL ) { - - out_of_memory( cinfo, 4 ); /* jpeg_get_large failed */ - - } - mem->total_space_allocated += sizeofobject + SIZEOF( large_pool_hdr ); - - - - /* Success, initialize the new pool header and add to list */ - - hdr_ptr->hdr.next = mem->large_list[pool_id]; - - /* We maintain space counts in each pool header for statistical purposes, - - * even though they are not needed for allocation. - - */ - - hdr_ptr->hdr.bytes_used = sizeofobject; - - hdr_ptr->hdr.bytes_left = 0; - - mem->large_list[pool_id] = hdr_ptr; - - - - return (void FAR *) ( hdr_ptr + 1 ); /* point to first data byte in pool */ - -} - - - - - -/* - - * Creation of 2-D sample arrays. - - * The pointers are in near heap, the samples themselves in FAR heap. - - * - - * To minimize allocation overhead and to allow I/O of large contiguous - - * blocks, we allocate the sample rows in groups of as many rows as possible - - * without exceeding MAX_ALLOC_CHUNK total bytes per allocation request. - - * NB: the virtual array control routines, later in this file, know about - - * this chunking of rows. The rowsperchunk value is left in the mem manager - - * object so that it can be saved away if this sarray is the workspace for - - * a virtual array. - - */ - - - -METHODDEF JSAMPARRAY - -alloc_sarray( j_common_ptr cinfo, int pool_id, - - JDIMENSION samplesperrow, JDIMENSION numrows ){ -/* Allocate a 2-D sample array */ - - my_mem_ptr mem = (my_mem_ptr) cinfo->mem; - - JSAMPARRAY result; - - JSAMPROW workspace; - - JDIMENSION rowsperchunk, currow, i; - - long ltemp; - - - - /* Calculate max # of rows allowed in one allocation chunk */ - - ltemp = ( MAX_ALLOC_CHUNK - SIZEOF( large_pool_hdr ) ) / - - ( (long) samplesperrow * SIZEOF( JSAMPLE ) ); - - if ( ltemp <= 0 ) { - - ERREXIT( cinfo, JERR_WIDTH_OVERFLOW ); - } - - if ( ltemp < (long) numrows ) { - - rowsperchunk = (JDIMENSION) ltemp; - } - - else{ - - rowsperchunk = numrows; - } - - mem->last_rowsperchunk = rowsperchunk; - - - - /* Get space for row pointers (small object) */ - - result = (JSAMPARRAY) alloc_small( cinfo, pool_id, - - (size_t) ( numrows * SIZEOF( JSAMPROW ) ) ); - - - - /* Get the rows themselves (large objects) */ - - currow = 0; - - while ( currow < numrows ) { - - rowsperchunk = MIN( rowsperchunk, numrows - currow ); - - workspace = (JSAMPROW) alloc_large( cinfo, pool_id, - - (size_t) ( (size_t) rowsperchunk * (size_t) samplesperrow - - * SIZEOF( JSAMPLE ) ) ); - - for ( i = rowsperchunk; i > 0; i-- ) { - - result[currow++] = workspace; - - workspace += samplesperrow; - - } - - } - - - - return result; - -} - - - - - -/* - - * Creation of 2-D coefficient-block arrays. - - * This is essentially the same as the code for sample arrays, above. - - */ - - - -METHODDEF JBLOCKARRAY - -alloc_barray( j_common_ptr cinfo, int pool_id, - - JDIMENSION blocksperrow, JDIMENSION numrows ){ -/* Allocate a 2-D coefficient-block array */ - - my_mem_ptr mem = (my_mem_ptr) cinfo->mem; - - JBLOCKARRAY result; - - JBLOCKROW workspace; - - JDIMENSION rowsperchunk, currow, i; - - long ltemp; - - - - /* Calculate max # of rows allowed in one allocation chunk */ - - ltemp = ( MAX_ALLOC_CHUNK - SIZEOF( large_pool_hdr ) ) / - - ( (long) blocksperrow * SIZEOF( JBLOCK ) ); - - if ( ltemp <= 0 ) { - - ERREXIT( cinfo, JERR_WIDTH_OVERFLOW ); - } - - if ( ltemp < (long) numrows ) { - - rowsperchunk = (JDIMENSION) ltemp; - } - - else{ - - rowsperchunk = numrows; - } - - mem->last_rowsperchunk = rowsperchunk; - - - - /* Get space for row pointers (small object) */ - - result = (JBLOCKARRAY) alloc_small( cinfo, pool_id, - - (size_t) ( numrows * SIZEOF( JBLOCKROW ) ) ); - - - - /* Get the rows themselves (large objects) */ - - currow = 0; - - while ( currow < numrows ) { - - rowsperchunk = MIN( rowsperchunk, numrows - currow ); - - workspace = (JBLOCKROW) alloc_large( cinfo, pool_id, - - (size_t) ( (size_t) rowsperchunk * (size_t) blocksperrow - - * SIZEOF( JBLOCK ) ) ); - - for ( i = rowsperchunk; i > 0; i-- ) { - - result[currow++] = workspace; - - workspace += blocksperrow; - - } - - } - - - - return result; - -} - - - - - -/* - - * About virtual array management: - - * - - * The above "normal" array routines are only used to allocate strip buffers - - * (as wide as the image, but just a few rows high). Full-image-sized buffers - - * are handled as "virtual" arrays. The array is still accessed a strip at a - - * time, but the memory manager must save the whole array for repeated - - * accesses. The intended implementation is that there is a strip buffer in - - * memory (as high as is possible given the desired memory limit), plus a - - * backing file that holds the rest of the array. - - * - - * The request_virt_array routines are told the total size of the image and - - * the maximum number of rows that will be accessed at once. The in-memory - - * buffer must be at least as large as the maxaccess value. - - * - - * The request routines create control blocks but not the in-memory buffers. - - * That is postponed until realize_virt_arrays is called. At that time the - - * total amount of space needed is known (approximately, anyway), so free - - * memory can be divided up fairly. - - * - - * The access_virt_array routines are responsible for making a specific strip - - * area accessible (after reading or writing the backing file, if necessary). - - * Note that the access routines are told whether the caller intends to modify - - * the accessed strip; during a read-only pass this saves having to rewrite - - * data to disk. The access routines are also responsible for pre-zeroing - - * any newly accessed rows, if pre-zeroing was requested. - - * - - * In current usage, the access requests are usually for nonoverlapping - - * strips; that is, successive access start_row numbers differ by exactly - - * num_rows = maxaccess. This means we can get good performance with simple - - * buffer dump/reload logic, by making the in-memory buffer be a multiple - - * of the access height; then there will never be accesses across bufferload - - * boundaries. The code will still work with overlapping access requests, - - * but it doesn't handle bufferload overlaps very efficiently. - - */ - - - - - -METHODDEF jvirt_sarray_ptr - -request_virt_sarray( j_common_ptr cinfo, int pool_id, boolean pre_zero, - - JDIMENSION samplesperrow, JDIMENSION numrows, - - JDIMENSION maxaccess ){ -/* Request a virtual 2-D sample array */ - - my_mem_ptr mem = (my_mem_ptr) cinfo->mem; - - jvirt_sarray_ptr result; - - - - /* Only IMAGE-lifetime virtual arrays are currently supported */ - - if ( pool_id != JPOOL_IMAGE ) { - - ERREXIT1( cinfo, JERR_BAD_POOL_ID, pool_id ); /* safety check */ - - - - } - /* get control block */ - - result = (jvirt_sarray_ptr) alloc_small( cinfo, pool_id, - - SIZEOF( struct jvirt_sarray_control ) ); - - - - result->mem_buffer = NULL; /* marks array not yet realized */ - - result->rows_in_array = numrows; - - result->samplesperrow = samplesperrow; - - result->maxaccess = maxaccess; - - result->pre_zero = pre_zero; - - result->b_s_open = FALSE; /* no associated backing-store object */ - - result->next = mem->virt_sarray_list; /* add to list of virtual arrays */ - - mem->virt_sarray_list = result; - - - - return result; - -} - - - - - -METHODDEF jvirt_barray_ptr - -request_virt_barray( j_common_ptr cinfo, int pool_id, boolean pre_zero, - - JDIMENSION blocksperrow, JDIMENSION numrows, - - JDIMENSION maxaccess ){ -/* Request a virtual 2-D coefficient-block array */ - - my_mem_ptr mem = (my_mem_ptr) cinfo->mem; - - jvirt_barray_ptr result; - - - - /* Only IMAGE-lifetime virtual arrays are currently supported */ - - if ( pool_id != JPOOL_IMAGE ) { - - ERREXIT1( cinfo, JERR_BAD_POOL_ID, pool_id ); /* safety check */ - - - - } - /* get control block */ - - result = (jvirt_barray_ptr) alloc_small( cinfo, pool_id, - - SIZEOF( struct jvirt_barray_control ) ); - - - - result->mem_buffer = NULL; /* marks array not yet realized */ - - result->rows_in_array = numrows; - - result->blocksperrow = blocksperrow; - - result->maxaccess = maxaccess; - - result->pre_zero = pre_zero; - - result->b_s_open = FALSE; /* no associated backing-store object */ - - result->next = mem->virt_barray_list; /* add to list of virtual arrays */ - - mem->virt_barray_list = result; - - - - return result; - -} - - - - - -METHODDEF void - -realize_virt_arrays( j_common_ptr cinfo ){ -/* Allocate the in-memory buffers for any unrealized virtual arrays */ - - my_mem_ptr mem = (my_mem_ptr) cinfo->mem; - - long space_per_minheight, maximum_space, avail_mem; - - long minheights, max_minheights; - - jvirt_sarray_ptr sptr; - - jvirt_barray_ptr bptr; - - - - /* Compute the minimum space needed (maxaccess rows in each buffer) - - * and the maximum space needed (full image height in each buffer). - - * These may be of use to the system-dependent jpeg_mem_available routine. - - */ - - space_per_minheight = 0; - - maximum_space = 0; - - for ( sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next ) { - - if ( sptr->mem_buffer == NULL ) { /* if not realized yet */ - - space_per_minheight += (long) sptr->maxaccess * - - (long) sptr->samplesperrow * SIZEOF( JSAMPLE ); - - maximum_space += (long) sptr->rows_in_array * - - (long) sptr->samplesperrow * SIZEOF( JSAMPLE ); - - } - - } - - for ( bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next ) { - - if ( bptr->mem_buffer == NULL ) { /* if not realized yet */ - - space_per_minheight += (long) bptr->maxaccess * - - (long) bptr->blocksperrow * SIZEOF( JBLOCK ); - - maximum_space += (long) bptr->rows_in_array * - - (long) bptr->blocksperrow * SIZEOF( JBLOCK ); - - } - - } - - - - if ( space_per_minheight <= 0 ) { - - return; /* no unrealized arrays, no work */ - - - - } - /* Determine amount of memory to actually use; this is system-dependent. */ - - avail_mem = jpeg_mem_available( cinfo, space_per_minheight, maximum_space, - - mem->total_space_allocated ); - - - - /* If the maximum space needed is available, make all the buffers full - - * height; otherwise parcel it out with the same number of minheights - - * in each buffer. - - */ - - if ( avail_mem >= maximum_space ) { - - max_minheights = 1000000000L; - } - - else { - - max_minheights = avail_mem / space_per_minheight; - - /* If there doesn't seem to be enough space, try to get the minimum - - * anyway. This allows a "stub" implementation of jpeg_mem_available(). - - */ - - if ( max_minheights <= 0 ) { - - max_minheights = 1; - } - - } - - - - /* Allocate the in-memory buffers and initialize backing store as needed. */ - - - - for ( sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next ) { - - if ( sptr->mem_buffer == NULL ) { /* if not realized yet */ - - minheights = ( (long) sptr->rows_in_array - 1L ) / sptr->maxaccess + 1L; - - if ( minheights <= max_minheights ) { - - /* This buffer fits in memory */ - - sptr->rows_in_mem = sptr->rows_in_array; - - } - else { - - /* It doesn't fit in memory, create backing store. */ - - sptr->rows_in_mem = (JDIMENSION) ( max_minheights * sptr->maxaccess ); - - jpeg_open_backing_store( cinfo, &sptr->b_s_info, - - (long) sptr->rows_in_array * - - (long) sptr->samplesperrow * - - (long) SIZEOF( JSAMPLE ) ); - - sptr->b_s_open = TRUE; - - } - - sptr->mem_buffer = alloc_sarray( cinfo, JPOOL_IMAGE, - - sptr->samplesperrow, sptr->rows_in_mem ); - - sptr->rowsperchunk = mem->last_rowsperchunk; - - sptr->cur_start_row = 0; - - sptr->first_undef_row = 0; - - sptr->dirty = FALSE; - - } - - } - - - - for ( bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next ) { - - if ( bptr->mem_buffer == NULL ) { /* if not realized yet */ - - minheights = ( (long) bptr->rows_in_array - 1L ) / bptr->maxaccess + 1L; - - if ( minheights <= max_minheights ) { - - /* This buffer fits in memory */ - - bptr->rows_in_mem = bptr->rows_in_array; - - } - else { - - /* It doesn't fit in memory, create backing store. */ - - bptr->rows_in_mem = (JDIMENSION) ( max_minheights * bptr->maxaccess ); - - jpeg_open_backing_store( cinfo, &bptr->b_s_info, - - (long) bptr->rows_in_array * - - (long) bptr->blocksperrow * - - (long) SIZEOF( JBLOCK ) ); - - bptr->b_s_open = TRUE; - - } - - bptr->mem_buffer = alloc_barray( cinfo, JPOOL_IMAGE, - - bptr->blocksperrow, bptr->rows_in_mem ); - - bptr->rowsperchunk = mem->last_rowsperchunk; - - bptr->cur_start_row = 0; - - bptr->first_undef_row = 0; - - bptr->dirty = FALSE; - - } - - } - -} - - - - - -LOCAL void - -do_sarray_io( j_common_ptr cinfo, jvirt_sarray_ptr ptr, boolean writing ){ -/* Do backing store read or write of a virtual sample array */ - - long bytesperrow, file_offset, byte_count, rows, thisrow, i; - - - - bytesperrow = (long) ptr->samplesperrow * SIZEOF( JSAMPLE ); - - file_offset = ptr->cur_start_row * bytesperrow; - - /* Loop to read or write each allocation chunk in mem_buffer */ - - for ( i = 0; i < (long) ptr->rows_in_mem; i += ptr->rowsperchunk ) { - - /* One chunk, but check for short chunk at end of buffer */ - - rows = MIN( (long) ptr->rowsperchunk, (long) ptr->rows_in_mem - i ); - - /* Transfer no more than is currently defined */ - - thisrow = (long) ptr->cur_start_row + i; - - rows = MIN( rows, (long) ptr->first_undef_row - thisrow ); - - /* Transfer no more than fits in file */ - - rows = MIN( rows, (long) ptr->rows_in_array - thisrow ); - - if ( rows <= 0 ) { /* this chunk might be past end of file! */ - - break; - } - - byte_count = rows * bytesperrow; - - if ( writing ) { - - ( *ptr->b_s_info.write_backing_store )( cinfo, &ptr->b_s_info, - - (void FAR *) ptr->mem_buffer[i], - - file_offset, byte_count ); - } - - else{ - - ( *ptr->b_s_info.read_backing_store )( cinfo, &ptr->b_s_info, - - (void FAR *) ptr->mem_buffer[i], - - file_offset, byte_count ); - } - - file_offset += byte_count; - - } - -} - - - - - -LOCAL void - -do_barray_io( j_common_ptr cinfo, jvirt_barray_ptr ptr, boolean writing ){ -/* Do backing store read or write of a virtual coefficient-block array */ - - long bytesperrow, file_offset, byte_count, rows, thisrow, i; - - - - bytesperrow = (long) ptr->blocksperrow * SIZEOF( JBLOCK ); - - file_offset = ptr->cur_start_row * bytesperrow; - - /* Loop to read or write each allocation chunk in mem_buffer */ - - for ( i = 0; i < (long) ptr->rows_in_mem; i += ptr->rowsperchunk ) { - - /* One chunk, but check for short chunk at end of buffer */ - - rows = MIN( (long) ptr->rowsperchunk, (long) ptr->rows_in_mem - i ); - - /* Transfer no more than is currently defined */ - - thisrow = (long) ptr->cur_start_row + i; - - rows = MIN( rows, (long) ptr->first_undef_row - thisrow ); - - /* Transfer no more than fits in file */ - - rows = MIN( rows, (long) ptr->rows_in_array - thisrow ); - - if ( rows <= 0 ) { /* this chunk might be past end of file! */ - - break; - } - - byte_count = rows * bytesperrow; - - if ( writing ) { - - ( *ptr->b_s_info.write_backing_store )( cinfo, &ptr->b_s_info, - - (void FAR *) ptr->mem_buffer[i], - - file_offset, byte_count ); - } - - else{ - - ( *ptr->b_s_info.read_backing_store )( cinfo, &ptr->b_s_info, - - (void FAR *) ptr->mem_buffer[i], - - file_offset, byte_count ); - } - - file_offset += byte_count; - - } - -} - - - - - -METHODDEF JSAMPARRAY - -access_virt_sarray( j_common_ptr cinfo, jvirt_sarray_ptr ptr, - - JDIMENSION start_row, JDIMENSION num_rows, - - boolean writable ){ -/* Access the part of a virtual sample array starting at start_row */ -/* and extending for num_rows rows. writable is true if */ -/* caller intends to modify the accessed area. */ - - JDIMENSION end_row = start_row + num_rows; - - JDIMENSION undef_row; - - - - /* debugging check */ - - if ( end_row > ptr->rows_in_array || num_rows > ptr->maxaccess || - - ptr->mem_buffer == NULL ) { - - ERREXIT( cinfo, JERR_BAD_VIRTUAL_ACCESS ); - } - - - - /* Make the desired part of the virtual array accessible */ - - if ( start_row < ptr->cur_start_row || - - end_row > ptr->cur_start_row + ptr->rows_in_mem ) { - - if ( !ptr->b_s_open ) { - - ERREXIT( cinfo, JERR_VIRTUAL_BUG ); - } - - /* Flush old buffer contents if necessary */ - - if ( ptr->dirty ) { - - do_sarray_io( cinfo, ptr, TRUE ); - - ptr->dirty = FALSE; - - } - - /* Decide what part of virtual array to access. - - * Algorithm: if target address > current window, assume forward scan, - - * load starting at target address. If target address < current window, - - * assume backward scan, load so that target area is top of window. - - * Note that when switching from forward write to forward read, will have - - * start_row = 0, so the limiting case applies and we load from 0 anyway. - - */ - - if ( start_row > ptr->cur_start_row ) { - - ptr->cur_start_row = start_row; - - } - else { - - /* use long arithmetic here to avoid overflow & unsigned problems */ - - long ltemp; - - - - ltemp = (long) end_row - (long) ptr->rows_in_mem; - - if ( ltemp < 0 ) { - - ltemp = 0; /* don't fall off front end of file */ - - } - ptr->cur_start_row = (JDIMENSION) ltemp; - - } - - /* Read in the selected part of the array. - - * During the initial write pass, we will do no actual read - - * because the selected part is all undefined. - - */ - - do_sarray_io( cinfo, ptr, FALSE ); - - } - - /* Ensure the accessed part of the array is defined; prezero if needed. - - * To improve locality of access, we only prezero the part of the array - - * that the caller is about to access, not the entire in-memory array. - - */ - - if ( ptr->first_undef_row < end_row ) { - - if ( ptr->first_undef_row < start_row ) { - - if ( writable ) { /* writer skipped over a section of array */ - - ERREXIT( cinfo, JERR_BAD_VIRTUAL_ACCESS ); - } - - undef_row = start_row; /* but reader is allowed to read ahead */ - - } - else { - - undef_row = ptr->first_undef_row; - - } - - if ( writable ) { - - ptr->first_undef_row = end_row; - } - - if ( ptr->pre_zero ) { - - size_t bytesperrow = (size_t) ptr->samplesperrow * SIZEOF( JSAMPLE ); - - undef_row -= ptr->cur_start_row; /* make indexes relative to buffer */ - - end_row -= ptr->cur_start_row; - - while ( undef_row < end_row ) { - - jzero_far( (void FAR *) ptr->mem_buffer[undef_row], bytesperrow ); - - undef_row++; - - } - - } - else { - - if ( !writable ) { /* reader looking at undefined data */ - - ERREXIT( cinfo, JERR_BAD_VIRTUAL_ACCESS ); - } - - } - - } - - /* Flag the buffer dirty if caller will write in it */ - - if ( writable ) { - - ptr->dirty = TRUE; - } - - /* Return address of proper part of the buffer */ - - return ptr->mem_buffer + ( start_row - ptr->cur_start_row ); - -} - - - - - -METHODDEF JBLOCKARRAY - -access_virt_barray( j_common_ptr cinfo, jvirt_barray_ptr ptr, - - JDIMENSION start_row, JDIMENSION num_rows, - - boolean writable ){ -/* Access the part of a virtual block array starting at start_row */ -/* and extending for num_rows rows. writable is true if */ -/* caller intends to modify the accessed area. */ - - JDIMENSION end_row = start_row + num_rows; - - JDIMENSION undef_row; - - - - /* debugging check */ - - if ( end_row > ptr->rows_in_array || num_rows > ptr->maxaccess || - - ptr->mem_buffer == NULL ) { - - ERREXIT( cinfo, JERR_BAD_VIRTUAL_ACCESS ); - } - - - - /* Make the desired part of the virtual array accessible */ - - if ( start_row < ptr->cur_start_row || - - end_row > ptr->cur_start_row + ptr->rows_in_mem ) { - - if ( !ptr->b_s_open ) { - - ERREXIT( cinfo, JERR_VIRTUAL_BUG ); - } - - /* Flush old buffer contents if necessary */ - - if ( ptr->dirty ) { - - do_barray_io( cinfo, ptr, TRUE ); - - ptr->dirty = FALSE; - - } - - /* Decide what part of virtual array to access. - - * Algorithm: if target address > current window, assume forward scan, - - * load starting at target address. If target address < current window, - - * assume backward scan, load so that target area is top of window. - - * Note that when switching from forward write to forward read, will have - - * start_row = 0, so the limiting case applies and we load from 0 anyway. - - */ - - if ( start_row > ptr->cur_start_row ) { - - ptr->cur_start_row = start_row; - - } - else { - - /* use long arithmetic here to avoid overflow & unsigned problems */ - - long ltemp; - - - - ltemp = (long) end_row - (long) ptr->rows_in_mem; - - if ( ltemp < 0 ) { - - ltemp = 0; /* don't fall off front end of file */ - - } - ptr->cur_start_row = (JDIMENSION) ltemp; - - } - - /* Read in the selected part of the array. - - * During the initial write pass, we will do no actual read - - * because the selected part is all undefined. - - */ - - do_barray_io( cinfo, ptr, FALSE ); - - } - - /* Ensure the accessed part of the array is defined; prezero if needed. - - * To improve locality of access, we only prezero the part of the array - - * that the caller is about to access, not the entire in-memory array. - - */ - - if ( ptr->first_undef_row < end_row ) { - - if ( ptr->first_undef_row < start_row ) { - - if ( writable ) { /* writer skipped over a section of array */ - - ERREXIT( cinfo, JERR_BAD_VIRTUAL_ACCESS ); - } - - undef_row = start_row; /* but reader is allowed to read ahead */ - - } - else { - - undef_row = ptr->first_undef_row; - - } - - if ( writable ) { - - ptr->first_undef_row = end_row; - } - - if ( ptr->pre_zero ) { - - size_t bytesperrow = (size_t) ptr->blocksperrow * SIZEOF( JBLOCK ); - - undef_row -= ptr->cur_start_row; /* make indexes relative to buffer */ - - end_row -= ptr->cur_start_row; - - while ( undef_row < end_row ) { - - jzero_far( (void FAR *) ptr->mem_buffer[undef_row], bytesperrow ); - - undef_row++; - - } - - } - else { - - if ( !writable ) { /* reader looking at undefined data */ - - ERREXIT( cinfo, JERR_BAD_VIRTUAL_ACCESS ); - } - - } - - } - - /* Flag the buffer dirty if caller will write in it */ - - if ( writable ) { - - ptr->dirty = TRUE; - } - - /* Return address of proper part of the buffer */ - - return ptr->mem_buffer + ( start_row - ptr->cur_start_row ); - -} - - - - - -/* - - * Release all objects belonging to a specified pool. - - */ - - - -METHODDEF void - -free_pool( j_common_ptr cinfo, int pool_id ){ - - my_mem_ptr mem = (my_mem_ptr) cinfo->mem; - - small_pool_ptr shdr_ptr; - - large_pool_ptr lhdr_ptr; - - size_t space_freed; - - - - if ( pool_id < 0 || pool_id >= JPOOL_NUMPOOLS ) { - - ERREXIT1( cinfo, JERR_BAD_POOL_ID, pool_id ); /* safety check */ - - - - } -#ifdef MEM_STATS - - if ( cinfo->err->trace_level > 1 ) { - - print_mem_stats( cinfo, pool_id ); /* print pool's memory usage statistics */ - - } -#endif - - - - /* If freeing IMAGE pool, close any virtual arrays first */ - - if ( pool_id == JPOOL_IMAGE ) { - - jvirt_sarray_ptr sptr; - - jvirt_barray_ptr bptr; - - - - for ( sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next ) { - - if ( sptr->b_s_open ) { /* there may be no backing store */ - - sptr->b_s_open = FALSE; /* prevent recursive close if error */ - - ( *sptr->b_s_info.close_backing_store )( cinfo, &sptr->b_s_info ); - - } - - } - - mem->virt_sarray_list = NULL; - - for ( bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next ) { - - if ( bptr->b_s_open ) { /* there may be no backing store */ - - bptr->b_s_open = FALSE; /* prevent recursive close if error */ - - ( *bptr->b_s_info.close_backing_store )( cinfo, &bptr->b_s_info ); - - } - - } - - mem->virt_barray_list = NULL; - - } - - - - /* Release large objects */ - - lhdr_ptr = mem->large_list[pool_id]; - - mem->large_list[pool_id] = NULL; - - - - while ( lhdr_ptr != NULL ) { - - large_pool_ptr next_lhdr_ptr = lhdr_ptr->hdr.next; - - space_freed = lhdr_ptr->hdr.bytes_used + - - lhdr_ptr->hdr.bytes_left + - - SIZEOF( large_pool_hdr ); - - jpeg_free_large( cinfo, (void FAR *) lhdr_ptr, space_freed ); - - mem->total_space_allocated -= space_freed; - - lhdr_ptr = next_lhdr_ptr; - - } - - - - /* Release small objects */ - - shdr_ptr = mem->small_list[pool_id]; - - mem->small_list[pool_id] = NULL; - - - - while ( shdr_ptr != NULL ) { - - small_pool_ptr next_shdr_ptr = shdr_ptr->hdr.next; - - space_freed = shdr_ptr->hdr.bytes_used + - - shdr_ptr->hdr.bytes_left + - - SIZEOF( small_pool_hdr ); - - jpeg_free_small( cinfo, (void *) shdr_ptr, space_freed ); - - mem->total_space_allocated -= space_freed; - - shdr_ptr = next_shdr_ptr; - - } - -} - - - - - -/* - - * Close up shop entirely. - - * Note that this cannot be called unless cinfo->mem is non-NULL. - - */ - - - -METHODDEF void - -self_destruct( j_common_ptr cinfo ){ - - int pool; - - - - /* Close all backing store, release all memory. - - * Releasing pools in reverse order might help avoid fragmentation - - * with some (brain-damaged) malloc libraries. - - */ - - for ( pool = JPOOL_NUMPOOLS - 1; pool >= JPOOL_PERMANENT; pool-- ) { - - free_pool( cinfo, pool ); - - } - - - - /* Release the memory manager control block too. */ - - jpeg_free_small( cinfo, (void *) cinfo->mem, SIZEOF( my_memory_mgr ) ); - - cinfo->mem = NULL; /* ensures I will be called only once */ - - - - jpeg_mem_term( cinfo ); /* system-dependent cleanup */ - -} - - - - - -/* - - * Memory manager initialization. - - * When this is called, only the error manager pointer is valid in cinfo! - - */ - - - -GLOBAL void - -jinit_memory_mgr( j_common_ptr cinfo ){ - - my_mem_ptr mem; - - long max_to_use; - - int pool; - - size_t test_mac; - - - - cinfo->mem = NULL; /* for safety if init fails */ - - - - /* Check for configuration errors. - - * SIZEOF(ALIGN_TYPE) should be a power of 2; otherwise, it probably - - * doesn't reflect any real hardware alignment requirement. - - * The test is a little tricky: for X>0, X and X-1 have no one-bits - - * in common if and only if X is a power of 2, ie has only one one-bit. - - * Some compilers may give an "unreachable code" warning here; ignore it. - - */ - - if ( ( SIZEOF( ALIGN_TYPE ) & ( SIZEOF( ALIGN_TYPE ) - 1 ) ) != 0 ) { - - ERREXIT( cinfo, JERR_BAD_ALIGN_TYPE ); - } - - /* MAX_ALLOC_CHUNK must be representable as type size_t, and must be - - * a multiple of SIZEOF(ALIGN_TYPE). - - * Again, an "unreachable code" warning may be ignored here. - - * But a "constant too large" warning means you need to fix MAX_ALLOC_CHUNK. - - */ - - test_mac = (size_t) MAX_ALLOC_CHUNK; - - if ( (long) test_mac != MAX_ALLOC_CHUNK || - - ( MAX_ALLOC_CHUNK % SIZEOF( ALIGN_TYPE ) ) != 0 ) { - - ERREXIT( cinfo, JERR_BAD_ALLOC_CHUNK ); - } - - - - max_to_use = jpeg_mem_init( cinfo ); /* system-dependent initialization */ - - - - /* Attempt to allocate memory manager's control block */ - - mem = (my_mem_ptr) jpeg_get_small( cinfo, SIZEOF( my_memory_mgr ) ); - - - - if ( mem == NULL ) { - - jpeg_mem_term( cinfo ); /* system-dependent cleanup */ - - ERREXIT1( cinfo, JERR_OUT_OF_MEMORY, 0 ); - - } - - - - /* OK, fill in the method pointers */ - - mem->pub.alloc_small = alloc_small; - - mem->pub.alloc_large = alloc_large; - - mem->pub.alloc_sarray = alloc_sarray; - - mem->pub.alloc_barray = alloc_barray; - - mem->pub.request_virt_sarray = request_virt_sarray; - - mem->pub.request_virt_barray = request_virt_barray; - - mem->pub.realize_virt_arrays = realize_virt_arrays; - - mem->pub.access_virt_sarray = access_virt_sarray; - - mem->pub.access_virt_barray = access_virt_barray; - - mem->pub.free_pool = free_pool; - - mem->pub.self_destruct = self_destruct; - - - - /* Initialize working state */ - - mem->pub.max_memory_to_use = max_to_use; - - - - for ( pool = JPOOL_NUMPOOLS - 1; pool >= JPOOL_PERMANENT; pool-- ) { - - mem->small_list[pool] = NULL; - - mem->large_list[pool] = NULL; - - } - - mem->virt_sarray_list = NULL; - - mem->virt_barray_list = NULL; - - - - mem->total_space_allocated = SIZEOF( my_memory_mgr ); - - - - /* Declare ourselves open for business */ - - cinfo->mem = &mem->pub; - - - - /* Check for an environment variable JPEGMEM; if found, override the - - * default max_memory setting from jpeg_mem_init. Note that the - - * surrounding application may again override this value. - - * If your system doesn't support getenv(), define NO_GETENV to disable - - * this feature. - - */ - -#ifndef NO_GETENV - - { char * memenv; - - - - if ( ( memenv = getenv( "JPEGMEM" ) ) != NULL ) { - - char ch = 'x'; - - - - if ( sscanf( memenv, "%ld%c", &max_to_use, &ch ) > 0 ) { - - if ( ch == 'm' || ch == 'M' ) { - - max_to_use *= 1000L; - } - - mem->pub.max_memory_to_use = max_to_use * 1000L; - - } - - } - } - -#endif - - - -} diff --git a/tools/urt/libs/jpeg6/jmemnobs.cpp b/tools/urt/libs/jpeg6/jmemnobs.cpp deleted file mode 100644 index 90a4a69..0000000 --- a/tools/urt/libs/jpeg6/jmemnobs.cpp +++ /dev/null @@ -1,189 +0,0 @@ -/* - - * jmemnobs.c - - * - - * Copyright (C) 1992-1994, Thomas G. Lane. - - * This file is part of the Independent JPEG Group's software. - - * For conditions of distribution and use, see the accompanying README file. - - * - - * This file provides a really simple implementation of the system- - - * dependent portion of the JPEG memory manager. This implementation - - * assumes that no backing-store files are needed: all required space - - * can be obtained from ri.Malloc(). - - * This is very portable in the sense that it'll compile on almost anything, - - * but you'd better have lots of main memory (or virtual memory) if you want - - * to process big images. - - * Note that the max_memory_to_use option is ignored by this implementation. - - */ - - - -#define JPEG_INTERNALS - -#include "jinclude.h" - -#include "radiant_jpeglib.h" - -#include "jmemsys.h" /* import the system-dependent declarations */ - - - -/* - - * Memory allocation and ri.Freeing are controlled by the regular library - - * routines ri.Malloc() and ri.Free(). - - */ - - - -GLOBAL void * - -jpeg_get_small( j_common_ptr cinfo, size_t sizeofobject ){ - - return (void *) malloc( sizeofobject ); - -} - - - -GLOBAL void - -jpeg_free_small( j_common_ptr cinfo, void * object, size_t sizeofobject ){ - - free( object ); - -} - - - - - -/* - - * "Large" objects are treated the same as "small" ones. - - * NB: although we include FAR keywords in the routine declarations, - - * this file won't actually work in 80x86 small/medium model; at least, - - * you probably won't be able to process useful-size images in only 64KB. - - */ - - - -GLOBAL void FAR * - -jpeg_get_large( j_common_ptr cinfo, size_t sizeofobject ){ - - return (void FAR *) malloc( sizeofobject ); - -} - - - -GLOBAL void - -jpeg_free_large( j_common_ptr cinfo, void FAR * object, size_t sizeofobject ){ - - free( object ); - -} - - - - - -/* - - * This routine computes the total memory space available for allocation. - - * Here we always say, "we got all you want bud!" - - */ - - - -GLOBAL long - -jpeg_mem_available( j_common_ptr cinfo, long min_bytes_needed, - - long max_bytes_needed, long already_allocated ){ - - return max_bytes_needed; - -} - - - - - -/* - - * Backing store (temporary file) management. - - * Since jpeg_mem_available always promised the moon, - - * this should never be called and we can just error out. - - */ - - - -GLOBAL void - -jpeg_open_backing_store( j_common_ptr cinfo, backing_store_ptr info, - - long total_bytes_needed ){ - - ERREXIT( cinfo, JERR_NO_BACKING_STORE ); - -} - - - - - -/* - - * These routines take care of any system-dependent initialization and - - * cleanup required. Here, there isn't any. - - */ - - - -GLOBAL long - -jpeg_mem_init( j_common_ptr cinfo ){ - - return 0; /* just set max_memory_to_use to 0 */ - -} - - - -GLOBAL void - -jpeg_mem_term( j_common_ptr cinfo ){ - - /* no work */ - -} diff --git a/tools/urt/libs/jpeg6/jmemsys.h b/tools/urt/libs/jpeg6/jmemsys.h deleted file mode 100644 index f2103e7..0000000 --- a/tools/urt/libs/jpeg6/jmemsys.h +++ /dev/null @@ -1,363 +0,0 @@ -/* - - * jmemsys.h - - * - - * Copyright (C) 1992-1994, Thomas G. Lane. - - * This file is part of the Independent JPEG Group's software. - - * For conditions of distribution and use, see the accompanying README file. - - * - - * This include file defines the interface between the system-independent - - * and system-dependent portions of the JPEG memory manager. No other - - * modules need include it. (The system-independent portion is jmemmgr.c; - - * there are several different versions of the system-dependent portion.) - - * - - * This file works as-is for the system-dependent memory managers supplied - - * in the IJG distribution. You may need to modify it if you write a - - * custom memory manager. If system-dependent changes are needed in - - * this file, the best method is to #ifdef them based on a configuration - - * symbol supplied in jconfig.h, as we have done with USE_MSDOS_MEMMGR. - - */ - - - - - -/* Short forms of external names for systems with brain-damaged linkers. */ - - - -#ifdef NEED_SHORT_EXTERNAL_NAMES - -#define jpeg_get_small jGetSmall - -#define jpeg_free_small jFreeSmall - -#define jpeg_get_large jGetLarge - -#define jpeg_free_large jFreeLarge - -#define jpeg_mem_available jMemAvail - -#define jpeg_open_backing_store jOpenBackStore - -#define jpeg_mem_init jMemInit - -#define jpeg_mem_term jMemTerm - -#endif /* NEED_SHORT_EXTERNAL_NAMES */ - - - - - -/* - - * These two functions are used to allocate and release small chunks of - - * memory. (Typically the total amount requested through jpeg_get_small is - - * no more than 20K or so; this will be requested in chunks of a few K each.) - - * Behavior should be the same as for the standard library functions malloc - - * and free; in particular, jpeg_get_small must return NULL on failure. - - * On most systems, these ARE malloc and free. jpeg_free_small is passed the - - * size of the object being freed, just in case it's needed. - - * On an 80x86 machine using small-data memory model, these manage near heap. - - */ - - - -EXTERN void * jpeg_get_small JPP( ( j_common_ptr cinfo, size_t sizeofobject ) ); - -EXTERN void jpeg_free_small JPP( ( j_common_ptr cinfo, void * object, - - size_t sizeofobject ) ); - - - -/* - - * These two functions are used to allocate and release large chunks of - - * memory (up to the total free space designated by jpeg_mem_available). - - * The interface is the same as above, except that on an 80x86 machine, - - * far pointers are used. On most other machines these are identical to - - * the jpeg_get/free_small routines; but we keep them separate anyway, - - * in case a different allocation strategy is desirable for large chunks. - - */ - - - -EXTERN void FAR * jpeg_get_large JPP( ( j_common_ptr cinfo,size_t sizeofobject ) ); - -EXTERN void jpeg_free_large JPP( ( j_common_ptr cinfo, void FAR * object, - - size_t sizeofobject ) ); - - - -/* - - * The macro MAX_ALLOC_CHUNK designates the maximum number of bytes that may - - * be requested in a single call to jpeg_get_large (and jpeg_get_small for that - - * matter, but that case should never come into play). This macro is needed - - * to model the 64Kb-segment-size limit of far addressing on 80x86 machines. - - * On those machines, we expect that jconfig.h will provide a proper value. - - * On machines with 32-bit flat address spaces, any large constant may be used. - - * - - * NB: jmemmgr.c expects that MAX_ALLOC_CHUNK will be representable as type - - * size_t and will be a multiple of sizeof(align_type). - - */ - - - -#ifndef MAX_ALLOC_CHUNK /* may be overridden in jconfig.h */ - -#define MAX_ALLOC_CHUNK 1000000000L - -#endif - - - -/* - - * This routine computes the total space still available for allocation by - - * jpeg_get_large. If more space than this is needed, backing store will be - - * used. NOTE: any memory already allocated must not be counted. - - * - - * There is a minimum space requirement, corresponding to the minimum - - * feasible buffer sizes; jmemmgr.c will request that much space even if - - * jpeg_mem_available returns zero. The maximum space needed, enough to hold - - * all working storage in memory, is also passed in case it is useful. - - * Finally, the total space already allocated is passed. If no better - - * method is available, cinfo->mem->max_memory_to_use - already_allocated - - * is often a suitable calculation. - - * - - * It is OK for jpeg_mem_available to underestimate the space available - - * (that'll just lead to more backing-store access than is really necessary). - - * However, an overestimate will lead to failure. Hence it's wise to subtract - - * a slop factor from the true available space. 5% should be enough. - - * - - * On machines with lots of virtual memory, any large constant may be returned. - - * Conversely, zero may be returned to always use the minimum amount of memory. - - */ - - - -EXTERN long jpeg_mem_available JPP( ( j_common_ptr cinfo, - - long min_bytes_needed, - - long max_bytes_needed, - - long already_allocated ) ); - - - - - -/* - - * This structure holds whatever state is needed to access a single - - * backing-store object. The read/write/close method pointers are called - - * by jmemmgr.c to manipulate the backing-store object; all other fields - - * are private to the system-dependent backing store routines. - - */ - - - -#define TEMP_NAME_LENGTH 64 /* max length of a temporary file's name */ - - - -#ifdef USE_MSDOS_MEMMGR /* DOS-specific junk */ - - - -typedef unsigned short XMSH; /* type of extended-memory handles */ - -typedef unsigned short EMSH; /* type of expanded-memory handles */ - - - -typedef union { - - short file_handle; /* DOS file handle if it's a temp file */ - - XMSH xms_handle; /* handle if it's a chunk of XMS */ - - EMSH ems_handle; /* handle if it's a chunk of EMS */ - -} handle_union; - - - -#endif /* USE_MSDOS_MEMMGR */ - - - -typedef struct backing_store_struct * backing_store_ptr; - - - -typedef struct backing_store_struct { - - /* Methods for reading/writing/closing this backing-store object */ - - JMETHOD( void, read_backing_store, ( j_common_ptr cinfo, - - backing_store_ptr info, - - void FAR * buffer_address, - - long file_offset, long byte_count ) ); - - JMETHOD( void, write_backing_store, ( j_common_ptr cinfo, - - backing_store_ptr info, - - void FAR * buffer_address, - - long file_offset, long byte_count ) ); - - JMETHOD( void, close_backing_store, ( j_common_ptr cinfo, - - backing_store_ptr info ) ); - - - - /* Private fields for system-dependent backing-store management */ - -#ifdef USE_MSDOS_MEMMGR - - /* For the MS-DOS manager (jmemdos.c), we need: */ - - handle_union handle; /* reference to backing-store storage object */ - - char temp_name[TEMP_NAME_LENGTH]; /* name if it's a file */ - -#else - - /* For a typical implementation with temp files, we need: */ - - FILE * temp_file; /* stdio reference to temp file */ - - char temp_name[TEMP_NAME_LENGTH]; /* name of temp file */ - -#endif - -} backing_store_info; - - - -/* - - * Initial opening of a backing-store object. This must fill in the - - * read/write/close pointers in the object. The read/write routines - - * may take an error exit if the specified maximum file size is exceeded. - - * (If jpeg_mem_available always returns a large value, this routine can - - * just take an error exit.) - - */ - - - -EXTERN void jpeg_open_backing_store JPP( ( j_common_ptr cinfo, - - backing_store_ptr info, - - long total_bytes_needed ) ); - - - - - -/* - - * These routines take care of any system-dependent initialization and - - * cleanup required. jpeg_mem_init will be called before anything is - - * allocated (and, therefore, nothing in cinfo is of use except the error - - * manager pointer). It should return a suitable default value for - - * max_memory_to_use; this may subsequently be overridden by the surrounding - - * application. (Note that max_memory_to_use is only important if - - * jpeg_mem_available chooses to consult it ... no one else will.) - - * jpeg_mem_term may assume that all requested memory has been freed and that - - * all opened backing-store objects have been closed. - - */ - - - -EXTERN long jpeg_mem_init JPP( (j_common_ptr cinfo) ); - -EXTERN void jpeg_mem_term JPP( (j_common_ptr cinfo) ); diff --git a/tools/urt/libs/jpeg6/jmorecfg.h b/tools/urt/libs/jpeg6/jmorecfg.h deleted file mode 100644 index f996a70..0000000 --- a/tools/urt/libs/jpeg6/jmorecfg.h +++ /dev/null @@ -1,693 +0,0 @@ -/* - - * jmorecfg.h - - * - - * Copyright (C) 1991-1995, Thomas G. Lane. - - * This file is part of the Independent JPEG Group's software. - - * For conditions of distribution and use, see the accompanying README file. - - * - - * This file contains additional configuration options that customize the - - * JPEG software for special applications or support machine-dependent - - * optimizations. Most users will not need to touch this file. - - */ - - - - - -/* - - * Define BITS_IN_JSAMPLE as either - - * 8 for 8-bit sample values (the usual setting) - - * 12 for 12-bit sample values - - * Only 8 and 12 are legal data precisions for lossy JPEG according to the - - * JPEG standard, and the IJG code does not support anything else! - - * We do not support run-time selection of data precision, sorry. - - */ - - - -#define BITS_IN_JSAMPLE 8 /* use 8 or 12 */ - - - - - -/* - - * Maximum number of components (color channels) allowed in JPEG image. - - * To meet the letter of the JPEG spec, set this to 255. However, darn - - * few applications need more than 4 channels (maybe 5 for CMYK + alpha - - * mask). We recommend 10 as a reasonable compromise; use 4 if you are - - * really short on memory. (Each allowed component costs a hundred or so - - * bytes of storage, whether actually used in an image or not.) - - */ - - - -#define MAX_COMPONENTS 10 /* maximum number of image components */ - - - - - -/* - - * Basic data types. - - * You may need to change these if you have a machine with unusual data - - * type sizes; for example, "char" not 8 bits, "short" not 16 bits, - - * or "long" not 32 bits. We don't care whether "int" is 16 or 32 bits, - - * but it had better be at least 16. - - */ - - - -/* Representation of a single sample (pixel element value). - - * We frequently allocate large arrays of these, so it's important to keep - - * them small. But if you have memory to burn and access to char or short - - * arrays is very slow on your hardware, you might want to change these. - - */ - - - -#if BITS_IN_JSAMPLE == 8 - -/* JSAMPLE should be the smallest type that will hold the values 0..255. - - * You can use a signed char by having GETJSAMPLE mask it with 0xFF. - - */ - - - -#ifdef HAVE_UNSIGNED_CHAR - - - -typedef unsigned char JSAMPLE; - -#define GETJSAMPLE( value ) ( (int) ( value ) ) - - - -#else /* not HAVE_UNSIGNED_CHAR */ - - - -typedef char JSAMPLE; - -#ifdef CHAR_IS_UNSIGNED - -#define GETJSAMPLE( value ) ( (int) ( value ) ) - -#else - -#define GETJSAMPLE( value ) ( (int) ( value ) & 0xFF ) - -#endif /* CHAR_IS_UNSIGNED */ - - - -#endif /* HAVE_UNSIGNED_CHAR */ - - - -#define MAXJSAMPLE 255 - -#define CENTERJSAMPLE 128 - - - -#endif /* BITS_IN_JSAMPLE == 8 */ - - - - - -#if BITS_IN_JSAMPLE == 12 - -/* JSAMPLE should be the smallest type that will hold the values 0..4095. - - * On nearly all machines "short" will do nicely. - - */ - - - -typedef short JSAMPLE; - -#define GETJSAMPLE( value ) ( (int) ( value ) ) - - - -#define MAXJSAMPLE 4095 - -#define CENTERJSAMPLE 2048 - - - -#endif /* BITS_IN_JSAMPLE == 12 */ - - - - - -/* Representation of a DCT frequency coefficient. - - * This should be a signed value of at least 16 bits; "short" is usually OK. - - * Again, we allocate large arrays of these, but you can change to int - - * if you have memory to burn and "short" is really slow. - - */ - - - -typedef short JCOEF; - - - - - -/* Compressed datastreams are represented as arrays of JOCTET. - - * These must be EXACTLY 8 bits wide, at least once they are written to - - * external storage. Note that when using the stdio data source/destination - - * managers, this is also the data type passed to fread/fwrite. - - */ - - - -#ifdef HAVE_UNSIGNED_CHAR - - - -typedef unsigned char JOCTET; - -#define GETJOCTET( value ) ( value ) - - - -#else /* not HAVE_UNSIGNED_CHAR */ - - - -typedef char JOCTET; - -#ifdef CHAR_IS_UNSIGNED - -#define GETJOCTET( value ) ( value ) - -#else - -#define GETJOCTET( value ) ( ( value ) & 0xFF ) - -#endif /* CHAR_IS_UNSIGNED */ - - - -#endif /* HAVE_UNSIGNED_CHAR */ - - - - - -/* These typedefs are used for various table entries and so forth. - - * They must be at least as wide as specified; but making them too big - - * won't cost a huge amount of memory, so we don't provide special - - * extraction code like we did for JSAMPLE. (In other words, these - - * typedefs live at a different point on the speed/space tradeoff curve.) - - */ - - - -/* UINT8 must hold at least the values 0..255. */ - - - -#ifdef HAVE_UNSIGNED_CHAR - -typedef unsigned char UINT8; - -#else /* not HAVE_UNSIGNED_CHAR */ - -#ifdef CHAR_IS_UNSIGNED - -typedef char UINT8; - -#else /* not CHAR_IS_UNSIGNED */ - -typedef short UINT8; - -#endif /* CHAR_IS_UNSIGNED */ - -#endif /* HAVE_UNSIGNED_CHAR */ - - - -/* UINT16 must hold at least the values 0..65535. */ - - - -#ifdef HAVE_UNSIGNED_SHORT - -typedef unsigned short UINT16; - -#else /* not HAVE_UNSIGNED_SHORT */ - -typedef unsigned int UINT16; - -#endif /* HAVE_UNSIGNED_SHORT */ - - - -/* INT16 must hold at least the values -32768..32767. */ - - - -#ifndef XMD_H /* X11/xmd.h correctly defines INT16 */ - -typedef short INT16; - -#endif - - - -/* INT32 must hold at least signed 32-bit values. */ - - - -//#ifndef XMD_H /* X11/xmd.h correctly defines INT32 */ - -//typedef long INT32; - -//#endif - - - -/* Datatype used for image dimensions. The JPEG standard only supports - - * images up to 64K*64K due to 16-bit fields in SOF markers. Therefore - - * "unsigned int" is sufficient on all machines. However, if you need to - - * handle larger images and you don't mind deviating from the spec, you - - * can change this datatype. - - */ - - - -typedef unsigned int JDIMENSION; - - - -#define JPEG_MAX_DIMENSION 65500L /* a tad under 64K to prevent overflows */ - - - - - -/* These defines are used in all function definitions and extern declarations. - - * You could modify them if you need to change function linkage conventions. - - * Another application is to make all functions global for use with debuggers - - * or code profilers that require it. - - */ - - - -#define METHODDEF static /* a function called through method pointers */ - -#define LOCAL static /* a function used only in its module */ - -#define GLOBAL /* a function referenced thru EXTERNs */ - -#define EXTERN extern /* a reference to a GLOBAL function */ - - - - - -/* Here is the pseudo-keyword for declaring pointers that must be "far" - - * on 80x86 machines. Most of the specialized coding for 80x86 is handled - - * by just saying "FAR *" where such a pointer is needed. In a few places - - * explicit coding is needed; see uses of the NEED_FAR_POINTERS symbol. - - */ - - - -#ifdef NEED_FAR_POINTERS - -#undef FAR - -#define FAR far - -#else - -#undef FAR - -#define FAR - -#endif - - - - - -/* - - * On a few systems, type boolean and/or its values FALSE, TRUE may appear - - * in standard header files. Or you may have conflicts with application- - - * specific header files that you want to include together with these files. - - * Defining HAVE_BOOLEAN before including jpeglib.h should make it work. - - */ - - - -//#ifndef HAVE_BOOLEAN - -//typedef int boolean; - -//#endif - -#ifndef FALSE /* in case these macros already exist */ - -#define FALSE 0 /* values of boolean */ - -#endif - -#ifndef TRUE - -#define TRUE 1 - -#endif - - - - - -/* - - * The remaining options affect code selection within the JPEG library, - - * but they don't need to be visible to most applications using the library. - - * To minimize application namespace pollution, the symbols won't be - - * defined unless JPEG_INTERNALS or JPEG_INTERNAL_OPTIONS has been defined. - - */ - - - -#ifdef JPEG_INTERNALS - -#define JPEG_INTERNAL_OPTIONS - -#endif - - - -#ifdef JPEG_INTERNAL_OPTIONS - - - - - -/* - - * These defines indicate whether to include various optional functions. - - * Undefining some of these symbols will produce a smaller but less capable - - * library. Note that you can leave certain source files out of the - - * compilation/linking process if you've #undef'd the corresponding symbols. - - * (You may HAVE to do that if your compiler doesn't like null source files.) - - */ - - - -/* Arithmetic coding is unsupported for legal reasons. Complaints to IBM. */ - - - -/* Capability options common to encoder and decoder: */ - - - -#undef DCT_ISLOW_SUPPORTED /* slow but accurate integer algorithm */ - -#undef DCT_IFAST_SUPPORTED /* faster, less accurate integer method */ - -#define DCT_FLOAT_SUPPORTED /* floating-point: accurate, fast on fast HW */ - - - -/* Encoder capability options: */ - - - -#undef C_ARITH_CODING_SUPPORTED /* Arithmetic coding back end? */ - -#define C_MULTISCAN_FILES_SUPPORTED /* Multiple-scan JPEG files? */ - -#define C_PROGRESSIVE_SUPPORTED /* Progressive JPEG? (Requires MULTISCAN)*/ - -#define ENTROPY_OPT_SUPPORTED /* Optimization of entropy coding parms? */ - -/* Note: if you selected 12-bit data precision, it is dangerous to turn off - - * ENTROPY_OPT_SUPPORTED. The standard Huffman tables are only good for 8-bit - - * precision, so jchuff.c normally uses entropy optimization to compute - - * usable tables for higher precision. If you don't want to do optimization, - - * you'll have to supply different default Huffman tables. - - * The exact same statements apply for progressive JPEG: the default tables - - * don't work for progressive mode. (This may get fixed, however.) - - */ - -#define INPUT_SMOOTHING_SUPPORTED /* Input image smoothing option? */ - - - -/* Decoder capability options: */ - - - -#undef D_ARITH_CODING_SUPPORTED /* Arithmetic coding back end? */ - -#undef D_MULTISCAN_FILES_SUPPORTED /* Multiple-scan JPEG files? */ - -#undef D_PROGRESSIVE_SUPPORTED /* Progressive JPEG? (Requires MULTISCAN)*/ - -#undef BLOCK_SMOOTHING_SUPPORTED /* Block smoothing? (Progressive only) */ - -#undef IDCT_SCALING_SUPPORTED /* Output rescaling via IDCT? */ - -#undef UPSAMPLE_SCALING_SUPPORTED /* Output rescaling at upsample stage? */ - -#undef UPSAMPLE_MERGING_SUPPORTED /* Fast path for sloppy upsampling? */ - -#undef QUANT_1PASS_SUPPORTED /* 1-pass color quantization? */ - -#undef QUANT_2PASS_SUPPORTED /* 2-pass color quantization? */ - - - -/* more capability options later, no doubt */ - - - - - -/* - - * Ordering of RGB data in scanlines passed to or from the application. - - * If your application wants to deal with data in the order B,G,R, just - - * change these macros. You can also deal with formats such as R,G,B,X - - * (one extra byte per pixel) by changing RGB_PIXELSIZE. Note that changing - - * the offsets will also change the order in which colormap data is organized. - - * RESTRICTIONS: - - * 1. The sample applications cjpeg,djpeg do NOT support modified RGB formats. - - * 2. These macros only affect RGB<=>YCbCr color conversion, so they are not - - * useful if you are using JPEG color spaces other than YCbCr or grayscale. - - * 3. The color quantizer modules will not behave desirably if RGB_PIXELSIZE - - * is not 3 (they don't understand about dummy color components!). So you - - * can't use color quantization if you change that value. - - */ - - - -#define RGB_RED 0 /* Offset of Red in an RGB scanline element */ - -#define RGB_GREEN 1 /* Offset of Green */ - -#define RGB_BLUE 2 /* Offset of Blue */ - -// http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=900 -// ydnar: setting this fucks jpeg loading in q3map2, disabling "fix" (3) -#define RGB_PIXELSIZE 4 /* JSAMPLEs per RGB scanline element */ - - - - - -/* Definitions for speed-related optimizations. */ - - - - - -/* If your compiler supports inline functions, define INLINE - - * as the inline keyword; otherwise define it as empty. - - */ - - - -#ifndef INLINE - -#ifdef __GNUC__ /* for instance, GNU C knows about inline */ - -#define INLINE __inline__ - -#endif - -#ifndef INLINE - -#define INLINE /* default is to define it as empty */ - -#endif - -#endif - - - - - -/* On some machines (notably 68000 series) "int" is 32 bits, but multiplying - - * two 16-bit shorts is faster than multiplying two ints. Define MULTIPLIER - - * as short on such a machine. MULTIPLIER must be at least 16 bits wide. - - */ - - - -#ifndef MULTIPLIER - -#define MULTIPLIER int /* type for fastest integer multiply */ - -#endif - - - - - -/* FAST_FLOAT should be either float or double, whichever is done faster - - * by your compiler. (Note that this type is only used in the floating point - - * DCT routines, so it only matters if you've defined DCT_FLOAT_SUPPORTED.) - - * Typically, float is faster in ANSI C compilers, while double is faster in - - * pre-ANSI compilers (because they insist on converting to double anyway). - - * The code below therefore chooses float if we have ANSI-style prototypes. - - */ - - - -#ifndef FAST_FLOAT - -#ifdef HAVE_PROTOTYPES - -#define FAST_FLOAT float - -#else - -#define FAST_FLOAT double - -#endif - -#endif - - - -#endif /* JPEG_INTERNAL_OPTIONS */ diff --git a/tools/urt/libs/jpeg6/jpeg6.dsp b/tools/urt/libs/jpeg6/jpeg6.dsp deleted file mode 100644 index 99b4974..0000000 --- a/tools/urt/libs/jpeg6/jpeg6.dsp +++ /dev/null @@ -1,218 +0,0 @@ -# Microsoft Developer Studio Project File - Name="jpeg6" - Package Owner=<4> -# Microsoft Developer Studio Generated Build File, Format Version 6.00 -# ** DO NOT EDIT ** - -# TARGTYPE "Win32 (x86) Static Library" 0x0104 - -CFG=jpeg6 - Win32 Debug -!MESSAGE This is not a valid makefile. To build this project using NMAKE, -!MESSAGE use the Export Makefile command and run -!MESSAGE -!MESSAGE NMAKE /f "jpeg6.mak". -!MESSAGE -!MESSAGE You can specify a configuration when running NMAKE -!MESSAGE by defining the macro CFG on the command line. For example: -!MESSAGE -!MESSAGE NMAKE /f "jpeg6.mak" CFG="jpeg6 - Win32 Debug" -!MESSAGE -!MESSAGE Possible choices for configuration are: -!MESSAGE -!MESSAGE "jpeg6 - Win32 Release" (based on "Win32 (x86) Static Library") -!MESSAGE "jpeg6 - Win32 Debug" (based on "Win32 (x86) Static Library") -!MESSAGE - -# Begin Project -# PROP AllowPerConfigDependencies 0 -# PROP Scc_ProjName "jpeg6" -# PROP Scc_LocalPath "." -CPP=cl.exe -RSC=rc.exe - -!IF "$(CFG)" == "jpeg6 - Win32 Release" - -# PROP BASE Use_MFC 0 -# PROP BASE Use_Debug_Libraries 0 -# PROP BASE Output_Dir "Release" -# PROP BASE Intermediate_Dir "Release" -# PROP BASE Target_Dir "" -# PROP Use_MFC 0 -# PROP Use_Debug_Libraries 0 -# PROP Output_Dir "Release" -# PROP Intermediate_Dir "Release" -# PROP Target_Dir "" -MTL=midl.exe -F90=df.exe -# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /YX /FD /c -# ADD CPP /nologo /MD /W3 /O2 /I "../" /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /FR /FD /c -# SUBTRACT CPP /YX -# ADD BASE RSC /l 0x409 -# ADD RSC /l 0x409 -BSC32=bscmake.exe -# ADD BASE BSC32 /nologo -# ADD BSC32 /nologo -LIB32=link.exe -lib -# ADD BASE LIB32 /nologo -# ADD LIB32 /nologo - -!ELSEIF "$(CFG)" == "jpeg6 - Win32 Debug" - -# PROP BASE Use_MFC 0 -# PROP BASE Use_Debug_Libraries 1 -# PROP BASE Output_Dir "Debug" -# PROP BASE Intermediate_Dir "Debug" -# PROP BASE Target_Dir "" -# PROP Use_MFC 0 -# PROP Use_Debug_Libraries 1 -# PROP Output_Dir "Debug" -# PROP Intermediate_Dir "Debug" -# PROP Target_Dir "" -MTL=midl.exe -F90=df.exe -# ADD BASE CPP /nologo /W3 /GX /Z7 /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /YX /FD /c -# ADD CPP /nologo /MDd /W3 /Z7 /Od /I "../" /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /FD /c -# SUBTRACT CPP /YX -# ADD BASE RSC /l 0x409 -# ADD RSC /l 0x409 -BSC32=bscmake.exe -# ADD BASE BSC32 /nologo -# ADD BSC32 /nologo -LIB32=link.exe -lib -# ADD BASE LIB32 /nologo -# ADD LIB32 /nologo - -!ENDIF - -# Begin Target - -# Name "jpeg6 - Win32 Release" -# Name "jpeg6 - Win32 Debug" -# Begin Source File - -SOURCE=.\Jchuff.h -# End Source File -# Begin Source File - -SOURCE=.\JCOMAPI.cpp -# End Source File -# Begin Source File - -SOURCE=.\Jconfig.h -# End Source File -# Begin Source File - -SOURCE=.\JDAPIMIN.cpp -# End Source File -# Begin Source File - -SOURCE=.\JDAPISTD.cpp -# End Source File -# Begin Source File - -SOURCE=.\JDATASRC.cpp -# End Source File -# Begin Source File - -SOURCE=.\JDCOEFCT.cpp -# End Source File -# Begin Source File - -SOURCE=.\JDCOLOR.cpp -# End Source File -# Begin Source File - -SOURCE=.\Jdct.h -# End Source File -# Begin Source File - -SOURCE=.\JDDCTMGR.cpp -# End Source File -# Begin Source File - -SOURCE=.\JDHUFF.cpp -# End Source File -# Begin Source File - -SOURCE=.\Jdhuff.h -# End Source File -# Begin Source File - -SOURCE=.\JDINPUT.cpp -# End Source File -# Begin Source File - -SOURCE=.\JDMAINCT.cpp -# End Source File -# Begin Source File - -SOURCE=.\JDMARKER.cpp -# End Source File -# Begin Source File - -SOURCE=.\JDMASTER.cpp -# End Source File -# Begin Source File - -SOURCE=.\JDPOSTCT.cpp -# End Source File -# Begin Source File - -SOURCE=.\JDSAMPLE.cpp -# End Source File -# Begin Source File - -SOURCE=.\JDTRANS.cpp -# End Source File -# Begin Source File - -SOURCE=.\JERROR.cpp -# End Source File -# Begin Source File - -SOURCE=.\Jerror.h -# End Source File -# Begin Source File - -SOURCE=.\JFDCTFLT.cpp -# End Source File -# Begin Source File - -SOURCE=.\JIDCTFLT.cpp -# End Source File -# Begin Source File - -SOURCE=.\Jinclude.h -# End Source File -# Begin Source File - -SOURCE=.\JMEMMGR.cpp -# End Source File -# Begin Source File - -SOURCE=.\JMEMNOBS.cpp -# End Source File -# Begin Source File - -SOURCE=.\Jmemsys.h -# End Source File -# Begin Source File - -SOURCE=.\Jmorecfg.h -# End Source File -# Begin Source File - -SOURCE=.\Jpegint.h -# End Source File -# Begin Source File - -SOURCE=.\JPGLOAD.cpp -# End Source File -# Begin Source File - -SOURCE=.\JUTILS.cpp -# End Source File -# Begin Source File - -SOURCE=.\Jversion.h -# End Source File -# End Target -# End Project diff --git a/tools/urt/libs/jpeg6/jpeg6.vcproj b/tools/urt/libs/jpeg6/jpeg6.vcproj deleted file mode 100644 index a0d973f..0000000 --- a/tools/urt/libs/jpeg6/jpeg6.vcproj +++ /dev/null @@ -1,692 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/tools/urt/libs/jpeg6/jpegint.h b/tools/urt/libs/jpeg6/jpegint.h deleted file mode 100644 index 670c8bc..0000000 --- a/tools/urt/libs/jpeg6/jpegint.h +++ /dev/null @@ -1,775 +0,0 @@ -/* - - * jpegint.h - - * - - * Copyright (C) 1991-1995, Thomas G. Lane. - - * This file is part of the Independent JPEG Group's software. - - * For conditions of distribution and use, see the accompanying README file. - - * - - * This file provides common declarations for the various JPEG modules. - - * These declarations are considered internal to the JPEG library; most - - * applications using the library shouldn't need to include this file. - - */ - - - - - -/* Declarations for both compression & decompression */ - - - -typedef enum { /* Operating modes for buffer controllers */ - - JBUF_PASS_THRU, /* Plain stripwise operation */ - - /* Remaining modes require a full-image buffer to have been created */ - - JBUF_SAVE_SOURCE, /* Run source subobject only, save output */ - - JBUF_CRANK_DEST, /* Run dest subobject only, using saved data */ - - JBUF_SAVE_AND_PASS /* Run both subobjects, save output */ - -} J_BUF_MODE; - - - -/* Values of global_state field (jdapi.c has some dependencies on ordering!) */ - -#define CSTATE_START 100 /* after create_compress */ - -#define CSTATE_SCANNING 101 /* start_compress done, write_scanlines OK */ - -#define CSTATE_RAW_OK 102 /* start_compress done, write_raw_data OK */ - -#define CSTATE_WRCOEFS 103 /* jpeg_write_coefficients done */ - -#define DSTATE_START 200 /* after create_decompress */ - -#define DSTATE_INHEADER 201 /* reading header markers, no SOS yet */ - -#define DSTATE_READY 202 /* found SOS, ready for start_decompress */ - -#define DSTATE_PRELOAD 203 /* reading multiscan file in start_decompress*/ - -#define DSTATE_PRESCAN 204 /* performing dummy pass for 2-pass quant */ - -#define DSTATE_SCANNING 205 /* start_decompress done, read_scanlines OK */ - -#define DSTATE_RAW_OK 206 /* start_decompress done, read_raw_data OK */ - -#define DSTATE_BUFIMAGE 207 /* expecting jpeg_start_output */ - -#define DSTATE_BUFPOST 208 /* looking for SOS/EOI in jpeg_finish_output */ - -#define DSTATE_RDCOEFS 209 /* reading file in jpeg_read_coefficients */ - -#define DSTATE_STOPPING 210 /* looking for EOI in jpeg_finish_decompress */ - - - - - -/* Declarations for compression modules */ - - - -/* Master control module */ - -struct jpeg_comp_master { - - JMETHOD( void, prepare_for_pass, (j_compress_ptr cinfo) ); - - JMETHOD( void, pass_startup, (j_compress_ptr cinfo) ); - - JMETHOD( void, finish_pass, (j_compress_ptr cinfo) ); - - - - /* State variables made visible to other modules */ - - boolean call_pass_startup; /* True if pass_startup must be called */ - - boolean is_last_pass; /* True during last pass */ - -}; - - - -/* Main buffer control (downsampled-data buffer) */ - -struct jpeg_c_main_controller { - - JMETHOD( void, start_pass, ( j_compress_ptr cinfo, J_BUF_MODE pass_mode ) ); - - JMETHOD( void, process_data, ( j_compress_ptr cinfo, - - JSAMPARRAY input_buf, JDIMENSION * in_row_ctr, - - JDIMENSION in_rows_avail ) ); - -}; - - - -/* Compression preprocessing (downsampling input buffer control) */ - -struct jpeg_c_prep_controller { - - JMETHOD( void, start_pass, ( j_compress_ptr cinfo, J_BUF_MODE pass_mode ) ); - - JMETHOD( void, pre_process_data, ( j_compress_ptr cinfo, - - JSAMPARRAY input_buf, - - JDIMENSION * in_row_ctr, - - JDIMENSION in_rows_avail, - - JSAMPIMAGE output_buf, - - JDIMENSION * out_row_group_ctr, - - JDIMENSION out_row_groups_avail ) ); - -}; - - - -/* Coefficient buffer control */ - -struct jpeg_c_coef_controller { - - JMETHOD( void, start_pass, ( j_compress_ptr cinfo, J_BUF_MODE pass_mode ) ); - - JMETHOD( boolean, compress_data, ( j_compress_ptr cinfo, - - JSAMPIMAGE input_buf ) ); - -}; - - - -/* Colorspace conversion */ - -struct jpeg_color_converter { - - JMETHOD( void, start_pass, (j_compress_ptr cinfo) ); - - JMETHOD( void, color_convert, ( j_compress_ptr cinfo, - - JSAMPARRAY input_buf, JSAMPIMAGE output_buf, - - JDIMENSION output_row, int num_rows ) ); - -}; - - - -/* Downsampling */ - -struct jpeg_downsampler { - - JMETHOD( void, start_pass, (j_compress_ptr cinfo) ); - - JMETHOD( void, downsample, ( j_compress_ptr cinfo, - - JSAMPIMAGE input_buf, JDIMENSION in_row_index, - - JSAMPIMAGE output_buf, - - JDIMENSION out_row_group_index ) ); - - - - boolean need_context_rows; /* TRUE if need rows above & below */ - -}; - - - -/* Forward DCT (also controls coefficient quantization) */ - -struct jpeg_forward_dct { - - JMETHOD( void, start_pass, (j_compress_ptr cinfo) ); - - /* perhaps this should be an array??? */ - - JMETHOD( void, forward_DCT, ( j_compress_ptr cinfo, - - jpeg_component_info * compptr, - - JSAMPARRAY sample_data, JBLOCKROW coef_blocks, - - JDIMENSION start_row, JDIMENSION start_col, - - JDIMENSION num_blocks ) ); - -}; - - - -/* Entropy encoding */ - -struct jpeg_entropy_encoder { - - JMETHOD( void, start_pass, ( j_compress_ptr cinfo, boolean gather_statistics ) ); - - JMETHOD( boolean, encode_mcu, ( j_compress_ptr cinfo, JBLOCKROW * MCU_data ) ); - - JMETHOD( void, finish_pass, (j_compress_ptr cinfo) ); - -}; - - - -/* Marker writing */ - -struct jpeg_marker_writer { - - /* write_any_marker is exported for use by applications */ - - /* Probably only COM and APPn markers should be written */ - - JMETHOD( void, write_any_marker, ( j_compress_ptr cinfo, int marker, - - const JOCTET * dataptr, unsigned int datalen ) ); - - JMETHOD( void, write_file_header, (j_compress_ptr cinfo) ); - - JMETHOD( void, write_frame_header, (j_compress_ptr cinfo) ); - - JMETHOD( void, write_scan_header, (j_compress_ptr cinfo) ); - - JMETHOD( void, write_file_trailer, (j_compress_ptr cinfo) ); - - JMETHOD( void, write_tables_only, (j_compress_ptr cinfo) ); - -}; - - - - - -/* Declarations for decompression modules */ - - - -/* Master control module */ - -struct jpeg_decomp_master { - - JMETHOD( void, prepare_for_output_pass, (j_decompress_ptr cinfo) ); - - JMETHOD( void, finish_output_pass, (j_decompress_ptr cinfo) ); - - - - /* State variables made visible to other modules */ - - boolean is_dummy_pass; /* True during 1st pass for 2-pass quant */ - -}; - - - -/* Input control module */ - -struct jpeg_input_controller { - - JMETHOD( int, consume_input, (j_decompress_ptr cinfo) ); - - JMETHOD( void, reset_input_controller, (j_decompress_ptr cinfo) ); - - JMETHOD( void, start_input_pass, (j_decompress_ptr cinfo) ); - - JMETHOD( void, finish_input_pass, (j_decompress_ptr cinfo) ); - - - - /* State variables made visible to other modules */ - - boolean has_multiple_scans; /* True if file has multiple scans */ - - boolean eoi_reached; /* True when EOI has been consumed */ - -}; - - - -/* Main buffer control (downsampled-data buffer) */ - -struct jpeg_d_main_controller { - - JMETHOD( void, start_pass, ( j_decompress_ptr cinfo, J_BUF_MODE pass_mode ) ); - - JMETHOD( void, process_data, ( j_decompress_ptr cinfo, - - JSAMPARRAY output_buf, JDIMENSION * out_row_ctr, - - JDIMENSION out_rows_avail ) ); - -}; - - - -/* Coefficient buffer control */ - -struct jpeg_d_coef_controller { - - JMETHOD( void, start_input_pass, (j_decompress_ptr cinfo) ); - - JMETHOD( int, consume_data, (j_decompress_ptr cinfo) ); - - JMETHOD( void, start_output_pass, (j_decompress_ptr cinfo) ); - - JMETHOD( int, decompress_data, ( j_decompress_ptr cinfo, - - JSAMPIMAGE output_buf ) ); - - /* Pointer to array of coefficient virtual arrays, or NULL if none */ - - jvirt_barray_ptr *coef_arrays; - -}; - - - -/* Decompression postprocessing (color quantization buffer control) */ - -struct jpeg_d_post_controller { - - JMETHOD( void, start_pass, ( j_decompress_ptr cinfo, J_BUF_MODE pass_mode ) ); - - JMETHOD( void, post_process_data, ( j_decompress_ptr cinfo, - - JSAMPIMAGE input_buf, - - JDIMENSION * in_row_group_ctr, - - JDIMENSION in_row_groups_avail, - - JSAMPARRAY output_buf, - - JDIMENSION * out_row_ctr, - - JDIMENSION out_rows_avail ) ); - -}; - - - -/* Marker reading & parsing */ - -struct jpeg_marker_reader { - - JMETHOD( void, reset_marker_reader, (j_decompress_ptr cinfo) ); - - /* Read markers until SOS or EOI. - - * Returns same codes as are defined for jpeg_consume_input: - - * JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI. - - */ - - JMETHOD( int, read_markers, (j_decompress_ptr cinfo) ); - - /* Read a restart marker --- exported for use by entropy decoder only */ - - jpeg_marker_parser_method read_restart_marker; - - /* Application-overridable marker processing methods */ - - jpeg_marker_parser_method process_COM; - - jpeg_marker_parser_method process_APPn[16]; - - - - /* State of marker reader --- nominally internal, but applications - - * supplying COM or APPn handlers might like to know the state. - - */ - - boolean saw_SOI; /* found SOI? */ - - boolean saw_SOF; /* found SOF? */ - - int next_restart_num; /* next restart number expected (0-7) */ - - unsigned int discarded_bytes; /* # of bytes skipped looking for a marker */ - -}; - - - -/* Entropy decoding */ - -struct jpeg_entropy_decoder { - - JMETHOD( void, start_pass, (j_decompress_ptr cinfo) ); - - JMETHOD( boolean, decode_mcu, ( j_decompress_ptr cinfo, - - JBLOCKROW * MCU_data ) ); - -}; - - - -/* Inverse DCT (also performs dequantization) */ - -typedef JMETHOD ( void, inverse_DCT_method_ptr, - - ( j_decompress_ptr cinfo, jpeg_component_info * compptr, - - JCOEFPTR coef_block, - - JSAMPARRAY output_buf, JDIMENSION output_col ) ); - - - -struct jpeg_inverse_dct { - - JMETHOD( void, start_pass, (j_decompress_ptr cinfo) ); - - /* It is useful to allow each component to have a separate IDCT method. */ - - inverse_DCT_method_ptr inverse_DCT[MAX_COMPONENTS]; - -}; - - - -/* Upsampling (note that upsampler must also call color converter) */ - -struct jpeg_upsampler { - - JMETHOD( void, start_pass, (j_decompress_ptr cinfo) ); - - JMETHOD( void, upsample, ( j_decompress_ptr cinfo, - - JSAMPIMAGE input_buf, - - JDIMENSION * in_row_group_ctr, - - JDIMENSION in_row_groups_avail, - - JSAMPARRAY output_buf, - - JDIMENSION * out_row_ctr, - - JDIMENSION out_rows_avail ) ); - - - - boolean need_context_rows; /* TRUE if need rows above & below */ - -}; - - - -/* Colorspace conversion */ - -struct jpeg_color_deconverter { - - JMETHOD( void, start_pass, (j_decompress_ptr cinfo) ); - - JMETHOD( void, color_convert, ( j_decompress_ptr cinfo, - - JSAMPIMAGE input_buf, JDIMENSION input_row, - - JSAMPARRAY output_buf, int num_rows ) ); - -}; - - - -/* Color quantization or color precision reduction */ - -struct jpeg_color_quantizer { - - JMETHOD( void, start_pass, ( j_decompress_ptr cinfo, boolean is_pre_scan ) ); - - JMETHOD( void, color_quantize, ( j_decompress_ptr cinfo, - - JSAMPARRAY input_buf, JSAMPARRAY output_buf, - - int num_rows ) ); - - JMETHOD( void, finish_pass, (j_decompress_ptr cinfo) ); - - JMETHOD( void, new_color_map, (j_decompress_ptr cinfo) ); - -}; - - - - - -/* Miscellaneous useful macros */ - - - -#undef MAX - -#define MAX( a,b ) ( ( a ) > ( b ) ? ( a ) : ( b ) ) - -#undef MIN - -#define MIN( a,b ) ( ( a ) < ( b ) ? ( a ) : ( b ) ) - - - - - -/* We assume that right shift corresponds to signed division by 2 with - - * rounding towards minus infinity. This is correct for typical "arithmetic - - * shift" instructions that shift in copies of the sign bit. But some - - * C compilers implement >> with an unsigned shift. For these machines you - - * must define RIGHT_SHIFT_IS_UNSIGNED. - - * RIGHT_SHIFT provides a proper signed right shift of an INT32 quantity. - - * It is only applied with constant shift counts. SHIFT_TEMPS must be - - * included in the variables of any routine using RIGHT_SHIFT. - - */ - - - -#ifdef RIGHT_SHIFT_IS_UNSIGNED - -#define SHIFT_TEMPS INT32 shift_temp; - -#define RIGHT_SHIFT( x,shft ) \ - -( ( shift_temp = ( x ) ) < 0 ? \ - - ( shift_temp >> ( shft ) ) | ( ( ~( (INT32) 0 ) ) << ( 32 - ( shft ) ) ) : \ - - ( shift_temp >> ( shft ) ) ) - -#else - -#define SHIFT_TEMPS - -#define RIGHT_SHIFT( x,shft ) ( ( x ) >> ( shft ) ) - -#endif - - - - - -/* Short forms of external names for systems with brain-damaged linkers. */ - - - -#ifdef NEED_SHORT_EXTERNAL_NAMES - -#define jinit_compress_master jICompress - -#define jinit_c_master_control jICMaster - -#define jinit_c_main_controller jICMainC - -#define jinit_c_prep_controller jICPrepC - -#define jinit_c_coef_controller jICCoefC - -#define jinit_color_converter jICColor - -#define jinit_downsampler jIDownsampler - -#define jinit_forward_dct jIFDCT - -#define jinit_huff_encoder jIHEncoder - -#define jinit_phuff_encoder jIPHEncoder - -#define jinit_marker_writer jIMWriter - -#define jinit_master_decompress jIDMaster - -#define jinit_d_main_controller jIDMainC - -#define jinit_d_coef_controller jIDCoefC - -#define jinit_d_post_controller jIDPostC - -#define jinit_input_controller jIInCtlr - -#define jinit_marker_reader jIMReader - -#define jinit_huff_decoder jIHDecoder - -#define jinit_phuff_decoder jIPHDecoder - -#define jinit_inverse_dct jIIDCT - -#define jinit_upsampler jIUpsampler - -#define jinit_color_deconverter jIDColor - -#define jinit_1pass_quantizer jI1Quant - -#define jinit_2pass_quantizer jI2Quant - -#define jinit_merged_upsampler jIMUpsampler - -#define jinit_memory_mgr jIMemMgr - -#define jdiv_round_up jDivRound - -#define jround_up jRound - -#define jcopy_sample_rows jCopySamples - -#define jcopy_block_row jCopyBlocks - -#define jzero_far jZeroFar - -#define jpeg_zigzag_order jZIGTable - -#define jpeg_natural_order jZAGTable - -#endif /* NEED_SHORT_EXTERNAL_NAMES */ - - - - - -/* Compression module initialization routines */ - -EXTERN void jinit_compress_master JPP( (j_compress_ptr cinfo) ); - -EXTERN void jinit_c_master_control JPP( ( j_compress_ptr cinfo, - - boolean transcode_only ) ); - -EXTERN void jinit_c_main_controller JPP( ( j_compress_ptr cinfo, - - boolean need_full_buffer ) ); - -EXTERN void jinit_c_prep_controller JPP( ( j_compress_ptr cinfo, - - boolean need_full_buffer ) ); - -EXTERN void jinit_c_coef_controller JPP( ( j_compress_ptr cinfo, - - boolean need_full_buffer ) ); - -EXTERN void jinit_color_converter JPP( (j_compress_ptr cinfo) ); - -EXTERN void jinit_downsampler JPP( (j_compress_ptr cinfo) ); - -EXTERN void jinit_forward_dct JPP( (j_compress_ptr cinfo) ); - -EXTERN void jinit_huff_encoder JPP( (j_compress_ptr cinfo) ); - -EXTERN void jinit_phuff_encoder JPP( (j_compress_ptr cinfo) ); - -EXTERN void jinit_marker_writer JPP( (j_compress_ptr cinfo) ); - -/* Decompression module initialization routines */ - -EXTERN void jinit_master_decompress JPP( (j_decompress_ptr cinfo) ); - -EXTERN void jinit_d_main_controller JPP( ( j_decompress_ptr cinfo, - - boolean need_full_buffer ) ); - -EXTERN void jinit_d_coef_controller JPP( ( j_decompress_ptr cinfo, - - boolean need_full_buffer ) ); - -EXTERN void jinit_d_post_controller JPP( ( j_decompress_ptr cinfo, - - boolean need_full_buffer ) ); - -EXTERN void jinit_input_controller JPP( (j_decompress_ptr cinfo) ); - -EXTERN void jinit_marker_reader JPP( (j_decompress_ptr cinfo) ); - -EXTERN void jinit_huff_decoder JPP( (j_decompress_ptr cinfo) ); - -EXTERN void jinit_phuff_decoder JPP( (j_decompress_ptr cinfo) ); - -EXTERN void jinit_inverse_dct JPP( (j_decompress_ptr cinfo) ); - -EXTERN void jinit_upsampler JPP( (j_decompress_ptr cinfo) ); - -EXTERN void jinit_color_deconverter JPP( (j_decompress_ptr cinfo) ); - -EXTERN void jinit_1pass_quantizer JPP( (j_decompress_ptr cinfo) ); - -EXTERN void jinit_2pass_quantizer JPP( (j_decompress_ptr cinfo) ); - -EXTERN void jinit_merged_upsampler JPP( (j_decompress_ptr cinfo) ); - -/* Memory manager initialization */ - -EXTERN void jinit_memory_mgr JPP( (j_common_ptr cinfo) ); - - - -/* Utility routines in jutils.c */ - -EXTERN long jdiv_round_up JPP( ( long a, long b ) ); - -EXTERN long jround_up JPP( ( long a, long b ) ); - -EXTERN void jcopy_sample_rows JPP( ( JSAMPARRAY input_array, int source_row, - - JSAMPARRAY output_array, int dest_row, - - int num_rows, JDIMENSION num_cols ) ); - -EXTERN void jcopy_block_row JPP( ( JBLOCKROW input_row, JBLOCKROW output_row, - - JDIMENSION num_blocks ) ); - -EXTERN void jzero_far JPP( ( void FAR * target, size_t bytestozero ) ); - -/* Constant tables in jutils.c */ - -extern const int jpeg_zigzag_order[]; /* natural coef order to zigzag order */ - -extern const int jpeg_natural_order[]; /* zigzag coef order to natural order */ - - - -/* Suppress undefined-structure complaints if necessary. */ - - - -#ifdef INCOMPLETE_TYPES_BROKEN - -#ifndef AM_MEMORY_MANAGER /* only jmemmgr.c defines these */ - -struct jvirt_sarray_control { long dummy; }; - -struct jvirt_barray_control { long dummy; }; - -#endif - -#endif /* INCOMPLETE_TYPES_BROKEN */ diff --git a/tools/urt/libs/jpeg6/jpgload.cpp b/tools/urt/libs/jpeg6/jpgload.cpp deleted file mode 100644 index a2eb1a9..0000000 --- a/tools/urt/libs/jpeg6/jpgload.cpp +++ /dev/null @@ -1,162 +0,0 @@ - - -#include "radiant_jpeglib.h" -#include "jerror.h" -#include - -GLOBAL int LoadJPGBuff( unsigned char *fbuffer, int bufsize, unsigned char **pic, int *width, int *height ){ - - /* This struct contains the JPEG decompression parameters and pointers to - * working space (which is allocated as needed by the JPEG library). - */ - struct jpeg_decompress_struct cinfo; - /* We use our private extension JPEG error handler. - * Note that this struct must live as long as the main JPEG parameter - * struct, to avoid dangling-pointer problems. - */ - /* This struct represents a JPEG error handler. It is declared separately - * because applications often want to supply a specialized error handler - * (see the second half of this file for an example). But here we just - * take the easy way out and use the standard error handler, which will - * print a message on stderr and call exit() if compression fails. - * Note that this struct must live as long as the main JPEG parameter - * struct, to avoid dangling-pointer problems. - */ - - struct jpeg_error_mgr jerr; - /* More stuff */ - JSAMPARRAY buffer; /* Output row buffer */ - int row_stride; /* physical row width in output buffer */ - unsigned char *out, *bbuf; - int nSize; - int jmpret; - - // Rad additions: initialize the longjmp buffer - jmpret = setjmp( rad_loadfailed ); - if ( jmpret != 0 ) { - *pic = (unsigned char *)rad_errormsg; - return -1; - } - - /* Step 1: allocate and initialize JPEG decompression object */ - - /* We have to set up the error handler first, in case the initialization - * step fails. (Unlikely, but it could happen if you are out of memory.) - * This routine fills in the contents of struct jerr, and returns jerr's - * address which we place into the link field in cinfo. - */ - cinfo.err = jpeg_std_error( &jerr ); - - /* Now we can initialize the JPEG decompression object. */ - jpeg_create_decompress( &cinfo ); - - /* Step 2: specify data source (eg, a file) */ - - jpeg_stdio_src( &cinfo, fbuffer, bufsize ); - - /* Step 3: read file parameters with jpeg_read_header() */ - - (void) jpeg_read_header( &cinfo, TRUE ); - /* We can ignore the return value from jpeg_read_header since - * (a) suspension is not possible with the stdio data source, and - * (b) we passed TRUE to reject a tables-only JPEG file as an error. - * See libjpeg.doc for more info. - */ - - /* Step 4: set parameters for decompression */ - - /* In this example, we don't need to change any of the defaults set by - * jpeg_read_header(), so we do nothing here. - */ - - /* Step 5: Start decompressor */ - - (void) jpeg_start_decompress( &cinfo ); - /* We can ignore the return value since suspension is not possible - * with the stdio data source. - */ - - /* ydnar: radiant only handles RGB, non-progressive format jpegs */ - if ( cinfo.output_components != 4 ) { - *pic = const_cast( reinterpret_cast( "Non-RGB JPEG encountered (unsupported)" ) ); - return -1; - } - if ( cinfo.progressive_mode ) { - *pic = const_cast( reinterpret_cast( "Progressive JPEG encountered (unsupported)" ) ); - return -1; - } - - /* We may need to do some setup of our own at this point before reading - * the data. After jpeg_start_decompress() we have the correct scaled - * output image dimensions available, as well as the output colormap - * if we asked for color quantization. - * In this example, we need to make an output work buffer of the right size. - */ - - /* JSAMPLEs per row in output buffer */ - row_stride = cinfo.output_width * cinfo.output_components; - nSize = cinfo.output_width * cinfo.output_height * cinfo.output_components; - - out = reinterpret_cast( malloc( nSize + 1 ) ); - memset( out, 255, nSize + 1 ); - - *pic = out; - *width = cinfo.output_width; - *height = cinfo.output_height; - - /* Step 6: while (scan lines remain to be read) */ - /* jpeg_read_scanlines(...); */ - - /* Here we use the library's state variable cinfo.output_scanline as the - * loop counter, so that we don't have to keep track ourselves. - */ - while ( cinfo.output_scanline < cinfo.output_height ) - { - /* jpeg_read_scanlines expects an array of pointers to scanlines. - * Here the array is only one element long, but you could ask for - * more than one scanline at a time if that's more convenient. - */ - bbuf = out + row_stride * cinfo.output_scanline; - buffer = &bbuf; - (void) jpeg_read_scanlines( &cinfo, buffer, 1 ); - } - - // clear all the alphas to 255 - { - int i, j; - unsigned char *buf; - - buf = *pic; - - j = cinfo.output_width * cinfo.output_height * 4; - for ( i = 3 ; i < j ; i += 4 ) { - buf[i] = 255; - } - } - - /* Step 7: Finish decompression */ - - (void) jpeg_finish_decompress( &cinfo ); - /* We can ignore the return value since suspension is not possible - * with the stdio data source. - */ - - /* Step 8: Release JPEG decompression object */ - - /* This is an important step since it will release a good deal of memory. */ - jpeg_destroy_decompress( &cinfo ); - - /* After finish_decompress, we can close the input file. - * Here we postpone it until after no more JPEG errors are possible, - * so as to simplify the setjmp error logic above. (Actually, I don't - * think that jpeg_destroy can do an error exit, but why assume anything...) - */ - //free (fbuffer); - - /* At this point you may want to check to see whether any corrupt-data - * warnings occurred (test whether jerr.pub.num_warnings is nonzero). - */ - - /* And we're done! */ - return 0; -} diff --git a/tools/urt/libs/jpeg6/jutils.cpp b/tools/urt/libs/jpeg6/jutils.cpp deleted file mode 100644 index e879d6f..0000000 --- a/tools/urt/libs/jpeg6/jutils.cpp +++ /dev/null @@ -1,331 +0,0 @@ -/* - - * jutils.c - - * - - * Copyright (C) 1991-1995, Thomas G. Lane. - - * This file is part of the Independent JPEG Group's software. - - * For conditions of distribution and use, see the accompanying README file. - - * - - * This file contains tables and miscellaneous utility routines needed - - * for both compression and decompression. - - * Note we prefix all global names with "j" to minimize conflicts with - - * a surrounding application. - - */ - - - -#define JPEG_INTERNALS - -#include "jinclude.h" - -#include "radiant_jpeglib.h" - - - - - -/* - - * jpeg_zigzag_order[i] is the zigzag-order position of the i'th element - - * of a DCT block read in natural order (left to right, top to bottom). - - */ - - - -const int jpeg_zigzag_order[DCTSIZE2] = { - - 0, 1, 5, 6, 14, 15, 27, 28, - - 2, 4, 7, 13, 16, 26, 29, 42, - - 3, 8, 12, 17, 25, 30, 41, 43, - - 9, 11, 18, 24, 31, 40, 44, 53, - - 10, 19, 23, 32, 39, 45, 52, 54, - - 20, 22, 33, 38, 46, 51, 55, 60, - - 21, 34, 37, 47, 50, 56, 59, 61, - - 35, 36, 48, 49, 57, 58, 62, 63 - -}; - - - -/* - - * jpeg_natural_order[i] is the natural-order position of the i'th element - - * of zigzag order. - - * - - * When reading corrupted data, the Huffman decoders could attempt - - * to reference an entry beyond the end of this array (if the decoded - - * zero run length reaches past the end of the block). To prevent - - * wild stores without adding an inner-loop test, we put some extra - - * "63"s after the real entries. This will cause the extra coefficient - - * to be stored in location 63 of the block, not somewhere random. - - * The worst case would be a run-length of 15, which means we need 16 - - * fake entries. - - */ - - - -const int jpeg_natural_order[DCTSIZE2 + 16] = { - - 0, 1, 8, 16, 9, 2, 3, 10, - - 17, 24, 32, 25, 18, 11, 4, 5, - - 12, 19, 26, 33, 40, 48, 41, 34, - - 27, 20, 13, 6, 7, 14, 21, 28, - - 35, 42, 49, 56, 57, 50, 43, 36, - - 29, 22, 15, 23, 30, 37, 44, 51, - - 58, 59, 52, 45, 38, 31, 39, 46, - - 53, 60, 61, 54, 47, 55, 62, 63, - - 63, 63, 63, 63, 63, 63, 63, 63, /* extra entries for safety in decoder */ - - 63, 63, 63, 63, 63, 63, 63, 63 - -}; - - - - - -/* - - * Arithmetic utilities - - */ - - - -GLOBAL long - -jdiv_round_up( long a, long b ){ -/* Compute a/b rounded up to next integer, ie, ceil(a/b) */ -/* Assumes a >= 0, b > 0 */ - - return ( a + b - 1L ) / b; - -} - - - - - -GLOBAL long - -jround_up( long a, long b ){ -/* Compute a rounded up to next multiple of b, ie, ceil(a/b)*b */ -/* Assumes a >= 0, b > 0 */ - - a += b - 1L; - - return a - ( a % b ); - -} - - - - - -/* On normal machines we can apply MEMCOPY() and MEMZERO() to sample arrays - - * and coefficient-block arrays. This won't work on 80x86 because the arrays - - * are FAR and we're assuming a small-pointer memory model. However, some - - * DOS compilers provide far-pointer versions of memcpy() and memset() even - - * in the small-model libraries. These will be used if USE_FMEM is defined. - - * Otherwise, the routines below do it the hard way. (The performance cost - - * is not all that great, because these routines aren't very heavily used.) - - */ - - - -#ifndef NEED_FAR_POINTERS /* normal case, same as regular macros */ - -#define FMEMCOPY( dest,src,size ) MEMCOPY( dest,src,size ) - -#define FMEMZERO( target,size ) MEMZERO( target,size ) - -#else /* 80x86 case, define if we can */ - -#ifdef USE_FMEM - -#define FMEMCOPY( dest,src,size ) _fmemcpy( (void FAR *)( dest ), (const void FAR *)( src ), (size_t)( size ) ) - -#define FMEMZERO( target,size ) _fmemset( (void FAR *)( target ), 0, (size_t)( size ) ) - -#endif - -#endif - - - - - -GLOBAL void - -jcopy_sample_rows( JSAMPARRAY input_array, int source_row, - - JSAMPARRAY output_array, int dest_row, - - int num_rows, JDIMENSION num_cols ){ -/* Copy some rows of samples from one place to another. - - * num_rows rows are copied from input_array[source_row++] - - * to output_array[dest_row++]; these areas may overlap for duplication. - - * The source and destination arrays must be at least as wide as num_cols. - - */ - - register JSAMPROW inptr, outptr; - -#ifdef FMEMCOPY - - register size_t count = (size_t) ( num_cols * SIZEOF( JSAMPLE ) ); - -#else - - register JDIMENSION count; - -#endif - - register int row; - - - - input_array += source_row; - - output_array += dest_row; - - - - for ( row = num_rows; row > 0; row-- ) { - - inptr = *input_array++; - - outptr = *output_array++; - -#ifdef FMEMCOPY - - FMEMCOPY( outptr, inptr, count ); - -#else - - for ( count = num_cols; count > 0; count-- ) - - *outptr++ = *inptr++; /* needn't bother with GETJSAMPLE() here */ - -#endif - - } - -} - - - - - -GLOBAL void - -jcopy_block_row( JBLOCKROW input_row, JBLOCKROW output_row, - - JDIMENSION num_blocks ){ -/* Copy a row of coefficient blocks from one place to another. */ - -#ifdef FMEMCOPY - - FMEMCOPY( output_row, input_row, num_blocks * ( DCTSIZE2 * SIZEOF( JCOEF ) ) ); - -#else - - register JCOEFPTR inptr, outptr; - - register long count; - - - - inptr = (JCOEFPTR) input_row; - - outptr = (JCOEFPTR) output_row; - - for ( count = (long) num_blocks * DCTSIZE2; count > 0; count-- ) { - - *outptr++ = *inptr++; - - } - -#endif - -} - - - - - -GLOBAL void - -jzero_far( void FAR * target, size_t bytestozero ){ -/* Zero out a chunk of FAR memory. */ -/* This might be sample-array data, block-array data, or alloc_large data. */ - -#ifdef FMEMZERO - - FMEMZERO( target, bytestozero ); - -#else - - register char FAR * ptr = (char FAR *) target; - - register size_t count; - - - - for ( count = bytestozero; count > 0; count-- ) { - - *ptr++ = 0; - - } - -#endif - -} diff --git a/tools/urt/libs/jpeg6/jversion.h b/tools/urt/libs/jpeg6/jversion.h deleted file mode 100644 index 1a2a6af..0000000 --- a/tools/urt/libs/jpeg6/jversion.h +++ /dev/null @@ -1,27 +0,0 @@ -/* - - * jversion.h - - * - - * Copyright (C) 1991-1995, Thomas G. Lane. - - * This file is part of the Independent JPEG Group's software. - - * For conditions of distribution and use, see the accompanying README file. - - * - - * This file contains software version identification. - - */ - - - - - -#define JVERSION "6 2-Aug-95" - - - -#define JCOPYRIGHT "Copyright (C) 1995, Thomas G. Lane" diff --git a/tools/urt/libs/jpeglib.h b/tools/urt/libs/jpeglib.h deleted file mode 100644 index 62562bd..0000000 --- a/tools/urt/libs/jpeglib.h +++ /dev/null @@ -1,1123 +0,0 @@ -/* - Copyright (C) 1999-2007 id Software, Inc. and contributors. - For a list of contributors, see the accompanying CONTRIBUTORS file. - - This file is part of GtkRadiant. - - GtkRadiant is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - GtkRadiant is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with GtkRadiant; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - */ - -/* - * jpeglib.h - * - * Copyright (C) 1991-1995, Thomas G. Lane. - * This file is part of the Independent JPEG Group's software. - * For conditions of distribution and use, see the accompanying README file. - * - * This file defines the application interface for the JPEG library. - * Most applications using the library need only include this file, - * and perhaps jerror.h if they want to know the exact error codes. - */ - -#ifndef JPEGLIB_H -#define JPEGLIB_H - -#ifdef __cplusplus -extern "C" -{ -#endif - -// LZ: linux stuff -#if defined ( __linux__ ) || defined ( __APPLE__ ) - -#include -#include - -#ifndef boolean -#ifdef __cplusplus -#define boolean bool -#else -typedef int boolean; -#endif -#endif - -#endif - -#ifdef __MACOS__ - -// JDC: stuff to make mac version compile -#define boolean qboolean -#define register -#define INT32 int - -#endif - -// rad additions -// 11.29.99 - -//#include "cmdlib.h" -#ifdef _WIN32 -#include "windows.h" -#include "stdio.h" -#endif - -#ifndef INT32 -#define INT32 int -#endif - -// TTimo: if LoadJPGBuff returns -1, *pic is the error message -extern int LoadJPGBuff( unsigned char *fbuffer, int bufsize, unsigned char **pic, int *width, int *height ); -// rad end - - -/* - * First we include the configuration files that record how this - * installation of the JPEG library is set up. jconfig.h can be - * generated automatically for many systems. jmorecfg.h contains - * manual configuration options that most people need not worry about. - */ - -#ifndef JCONFIG_INCLUDED /* in case jinclude.h already did */ -#include "jpeg6/jconfig.h" /* widely used configuration options */ -#endif -#include "jpeg6/jmorecfg.h" /* seldom changed options */ - - -/* Version ID for the JPEG library. - * Might be useful for tests like "#if JPEG_LIB_VERSION >= 60". - */ - -#define JPEG_LIB_VERSION 60 /* Version 6 */ - - -/* Various constants determining the sizes of things. - * All of these are specified by the JPEG standard, so don't change them - * if you want to be compatible. - */ - -#define DCTSIZE 8 /* The basic DCT block is 8x8 samples */ -#define DCTSIZE2 64 /* DCTSIZE squared; # of elements in a block */ -#define NUM_QUANT_TBLS 4 /* Quantization tables are numbered 0..3 */ -#define NUM_HUFF_TBLS 4 /* Huffman tables are numbered 0..3 */ -#define NUM_ARITH_TBLS 16 /* Arith-coding tables are numbered 0..15 */ -#define MAX_COMPS_IN_SCAN 4 /* JPEG limit on # of components in one scan */ -#define MAX_SAMP_FACTOR 4 /* JPEG limit on sampling factors */ -/* Unfortunately, some bozo at Adobe saw no reason to be bound by the standard; - * the PostScript DCT filter can emit files with many more than 10 blocks/MCU. - * If you happen to run across such a file, you can up D_MAX_BLOCKS_IN_MCU - * to handle it. We even let you do this from the jconfig.h file. However, - * we strongly discourage changing C_MAX_BLOCKS_IN_MCU; just because Adobe - * sometimes emits noncompliant files doesn't mean you should too. - */ -#define C_MAX_BLOCKS_IN_MCU 10 /* compressor's limit on blocks per MCU */ -#ifndef D_MAX_BLOCKS_IN_MCU -#define D_MAX_BLOCKS_IN_MCU 10 /* decompressor's limit on blocks per MCU */ -#endif - - -/* This macro is used to declare a "method", that is, a function pointer. - * We want to supply prototype parameters if the compiler can cope. - * Note that the arglist parameter must be parenthesized! - */ - -#ifdef HAVE_PROTOTYPES -#define JMETHOD( type,methodname,arglist ) type( *methodname ) arglist -#else -#define JMETHOD( type,methodname,arglist ) type ( *methodname )() -#endif - - -/* Data structures for images (arrays of samples and of DCT coefficients). - * On 80x86 machines, the image arrays are too big for near pointers, - * but the pointer arrays can fit in near memory. - */ - -typedef JSAMPLE FAR *JSAMPROW; /* ptr to one image row of pixel samples. */ -typedef JSAMPROW *JSAMPARRAY; /* ptr to some rows (a 2-D sample array) */ -typedef JSAMPARRAY *JSAMPIMAGE; /* a 3-D sample array: top index is color */ - -typedef JCOEF JBLOCK[DCTSIZE2]; /* one block of coefficients */ -typedef JBLOCK FAR *JBLOCKROW; /* pointer to one row of coefficient blocks */ -typedef JBLOCKROW *JBLOCKARRAY; /* a 2-D array of coefficient blocks */ -typedef JBLOCKARRAY *JBLOCKIMAGE; /* a 3-D array of coefficient blocks */ - -typedef JCOEF FAR *JCOEFPTR; /* useful in a couple of places */ - - -/* Types for JPEG compression parameters and working tables. */ - - -/* DCT coefficient quantization tables. */ - -typedef struct { - /* This field directly represents the contents of a JPEG DQT marker. - * Note: the values are always given in zigzag order. - */ - UINT16 quantval[DCTSIZE2]; /* quantization step for each coefficient */ - /* This field is used only during compression. It's initialized FALSE when - * the table is created, and set TRUE when it's been output to the file. - * You could suppress output of a table by setting this to TRUE. - * (See jpeg_suppress_tables for an example.) - */ - boolean sent_table; /* TRUE when table has been output */ -} JQUANT_TBL; - - -/* Huffman coding tables. */ - -typedef struct { - /* These two fields directly represent the contents of a JPEG DHT marker */ - UINT8 bits[17]; /* bits[k] = # of symbols with codes of */ - /* length k bits; bits[0] is unused */ - UINT8 huffval[256]; /* The symbols, in order of incr code length */ - /* This field is used only during compression. It's initialized FALSE when - * the table is created, and set TRUE when it's been output to the file. - * You could suppress output of a table by setting this to TRUE. - * (See jpeg_suppress_tables for an example.) - */ - boolean sent_table; /* TRUE when table has been output */ -} JHUFF_TBL; - - -/* Basic info about one component (color channel). */ - -typedef struct { - /* These values are fixed over the whole image. */ - /* For compression, they must be supplied by parameter setup; */ - /* for decompression, they are read from the SOF marker. */ - int component_id; /* identifier for this component (0..255) */ - int component_index; /* its index in SOF or cinfo->comp_info[] */ - int h_samp_factor; /* horizontal sampling factor (1..4) */ - int v_samp_factor; /* vertical sampling factor (1..4) */ - int quant_tbl_no; /* quantization table selector (0..3) */ - /* These values may vary between scans. */ - /* For compression, they must be supplied by parameter setup; */ - /* for decompression, they are read from the SOS marker. */ - /* The decompressor output side may not use these variables. */ - int dc_tbl_no; /* DC entropy table selector (0..3) */ - int ac_tbl_no; /* AC entropy table selector (0..3) */ - - /* Remaining fields should be treated as private by applications. */ - - /* These values are computed during compression or decompression startup: */ - /* Component's size in DCT blocks. - * Any dummy blocks added to complete an MCU are not counted; therefore - * these values do not depend on whether a scan is interleaved or not. - */ - JDIMENSION width_in_blocks; - JDIMENSION height_in_blocks; - /* Size of a DCT block in samples. Always DCTSIZE for compression. - * For decompression this is the size of the output from one DCT block, - * reflecting any scaling we choose to apply during the IDCT step. - * Values of 1,2,4,8 are likely to be supported. Note that different - * components may receive different IDCT scalings. - */ - int DCT_scaled_size; - /* The downsampled dimensions are the component's actual, unpadded number - * of samples at the main buffer (preprocessing/compression interface), thus - * downsampled_width = ceil(image_width * Hi/Hmax) - * and similarly for height. For decompression, IDCT scaling is included, so - * downsampled_width = ceil(image_width * Hi/Hmax * DCT_scaled_size/DCTSIZE) - */ - JDIMENSION downsampled_width; /* actual width in samples */ - JDIMENSION downsampled_height; /* actual height in samples */ - /* This flag is used only for decompression. In cases where some of the - * components will be ignored (eg grayscale output from YCbCr image), - * we can skip most computations for the unused components. - */ - boolean component_needed; /* do we need the value of this component? */ - - /* These values are computed before starting a scan of the component. */ - /* The decompressor output side may not use these variables. */ - int MCU_width; /* number of blocks per MCU, horizontally */ - int MCU_height; /* number of blocks per MCU, vertically */ - int MCU_blocks; /* MCU_width * MCU_height */ - int MCU_sample_width; /* MCU width in samples, MCU_width*DCT_scaled_size */ - int last_col_width; /* # of non-dummy blocks across in last MCU */ - int last_row_height; /* # of non-dummy blocks down in last MCU */ - - /* Saved quantization table for component; NULL if none yet saved. - * See jdinput.c comments about the need for this information. - * This field is not currently used by the compressor. - */ - JQUANT_TBL * quant_table; - - /* Private per-component storage for DCT or IDCT subsystem. */ - void * dct_table; -} jpeg_component_info; - - -/* The script for encoding a multiple-scan file is an array of these: */ - -typedef struct { - int comps_in_scan; /* number of components encoded in this scan */ - int component_index[MAX_COMPS_IN_SCAN]; /* their SOF/comp_info[] indexes */ - int Ss, Se; /* progressive JPEG spectral selection parms */ - int Ah, Al; /* progressive JPEG successive approx. parms */ -} jpeg_scan_info; - - -/* Known color spaces. */ - -typedef enum { - JCS_UNKNOWN, /* error/unspecified */ - JCS_GRAYSCALE, /* monochrome */ - JCS_RGB, /* red/green/blue */ - JCS_YCbCr, /* Y/Cb/Cr (also known as YUV) */ - JCS_CMYK, /* C/M/Y/K */ - JCS_YCCK /* Y/Cb/Cr/K */ -} J_COLOR_SPACE; - -/* DCT/IDCT algorithm options. */ - -typedef enum { - JDCT_ISLOW, /* slow but accurate integer algorithm */ - JDCT_IFAST, /* faster, less accurate integer method */ - JDCT_FLOAT /* floating-point: accurate, fast on fast HW */ -} J_DCT_METHOD; - -#ifndef JDCT_DEFAULT /* may be overridden in jconfig.h */ -#define JDCT_DEFAULT JDCT_ISLOW -#endif -#ifndef JDCT_FASTEST /* may be overridden in jconfig.h */ -#define JDCT_FASTEST JDCT_IFAST -#endif - -/* Dithering options for decompression. */ - -typedef enum { - JDITHER_NONE, /* no dithering */ - JDITHER_ORDERED, /* simple ordered dither */ - JDITHER_FS /* Floyd-Steinberg error diffusion dither */ -} J_DITHER_MODE; - - -/* Common fields between JPEG compression and decompression master structs. */ - -#define jpeg_common_fields \ - struct jpeg_error_mgr * err; /* Error handler module */ \ - struct jpeg_memory_mgr * mem; /* Memory manager module */ \ - struct jpeg_progress_mgr * progress; /* Progress monitor, or NULL if none */ \ - boolean is_decompressor; /* so common code can tell which is which */ \ - int global_state /* for checking call sequence validity */ - -/* Routines that are to be used by both halves of the library are declared - * to receive a pointer to this structure. There are no actual instances of - * jpeg_common_struct, only of jpeg_compress_struct and jpeg_decompress_struct. - */ -struct jpeg_common_struct { - jpeg_common_fields; /* Fields common to both master struct types */ - /* Additional fields follow in an actual jpeg_compress_struct or - * jpeg_decompress_struct. All three structs must agree on these - * initial fields! (This would be a lot cleaner in C++.) - */ -}; - -typedef struct jpeg_common_struct * j_common_ptr; -typedef struct jpeg_compress_struct * j_compress_ptr; -typedef struct jpeg_decompress_struct * j_decompress_ptr; - - -/* Master record for a compression instance */ - -struct jpeg_compress_struct { - jpeg_common_fields; /* Fields shared with jpeg_decompress_struct */ - - /* Destination for compressed data */ - struct jpeg_destination_mgr * dest; - - /* Description of source image --- these fields must be filled in by - * outer application before starting compression. in_color_space must - * be correct before you can even call jpeg_set_defaults(). - */ - - JDIMENSION image_width; /* input image width */ - JDIMENSION image_height; /* input image height */ - int input_components; /* # of color components in input image */ - J_COLOR_SPACE in_color_space; /* colorspace of input image */ - - double input_gamma; /* image gamma of input image */ - - /* Compression parameters --- these fields must be set before calling - * jpeg_start_compress(). We recommend calling jpeg_set_defaults() to - * initialize everything to reasonable defaults, then changing anything - * the application specifically wants to change. That way you won't get - * burnt when new parameters are added. Also note that there are several - * helper routines to simplify changing parameters. - */ - - int data_precision; /* bits of precision in image data */ - - int num_components; /* # of color components in JPEG image */ - J_COLOR_SPACE jpeg_color_space; /* colorspace of JPEG image */ - - jpeg_component_info * comp_info; - /* comp_info[i] describes component that appears i'th in SOF */ - - JQUANT_TBL * quant_tbl_ptrs[NUM_QUANT_TBLS]; - /* ptrs to coefficient quantization tables, or NULL if not defined */ - - JHUFF_TBL * dc_huff_tbl_ptrs[NUM_HUFF_TBLS]; - JHUFF_TBL * ac_huff_tbl_ptrs[NUM_HUFF_TBLS]; - /* ptrs to Huffman coding tables, or NULL if not defined */ - - UINT8 arith_dc_L[NUM_ARITH_TBLS]; /* L values for DC arith-coding tables */ - UINT8 arith_dc_U[NUM_ARITH_TBLS]; /* U values for DC arith-coding tables */ - UINT8 arith_ac_K[NUM_ARITH_TBLS]; /* Kx values for AC arith-coding tables */ - - int num_scans; /* # of entries in scan_info array */ - const jpeg_scan_info * scan_info; /* script for multi-scan file, or NULL */ - /* The default value of scan_info is NULL, which causes a single-scan - * sequential JPEG file to be emitted. To create a multi-scan file, - * set num_scans and scan_info to point to an array of scan definitions. - */ - - boolean raw_data_in; /* TRUE=caller supplies downsampled data */ - boolean arith_code; /* TRUE=arithmetic coding, FALSE=Huffman */ - boolean optimize_coding; /* TRUE=optimize entropy encoding parms */ - boolean CCIR601_sampling; /* TRUE=first samples are cosited */ - int smoothing_factor; /* 1..100, or 0 for no input smoothing */ - J_DCT_METHOD dct_method; /* DCT algorithm selector */ - - /* The restart interval can be specified in absolute MCUs by setting - * restart_interval, or in MCU rows by setting restart_in_rows - * (in which case the correct restart_interval will be figured - * for each scan). - */ - unsigned int restart_interval; /* MCUs per restart, or 0 for no restart */ - int restart_in_rows; /* if > 0, MCU rows per restart interval */ - - /* Parameters controlling emission of special markers. */ - - boolean write_JFIF_header; /* should a JFIF marker be written? */ - /* These three values are not used by the JPEG code, merely copied */ - /* into the JFIF APP0 marker. density_unit can be 0 for unknown, */ - /* 1 for dots/inch, or 2 for dots/cm. Note that the pixel aspect */ - /* ratio is defined by X_density/Y_density even when density_unit=0. */ - UINT8 density_unit; /* JFIF code for pixel size units */ - UINT16 X_density; /* Horizontal pixel density */ - UINT16 Y_density; /* Vertical pixel density */ - boolean write_Adobe_marker; /* should an Adobe marker be written? */ - - /* State variable: index of next scanline to be written to - * jpeg_write_scanlines(). Application may use this to control its - * processing loop, e.g., "while (next_scanline < image_height)". - */ - - JDIMENSION next_scanline; /* 0 .. image_height-1 */ - - /* Remaining fields are known throughout compressor, but generally - * should not be touched by a surrounding application. - */ - - /* - * These fields are computed during compression startup - */ - boolean progressive_mode; /* TRUE if scan script uses progressive mode */ - int max_h_samp_factor; /* largest h_samp_factor */ - int max_v_samp_factor; /* largest v_samp_factor */ - - JDIMENSION total_iMCU_rows; /* # of iMCU rows to be input to coef ctlr */ - /* The coefficient controller receives data in units of MCU rows as defined - * for fully interleaved scans (whether the JPEG file is interleaved or not). - * There are v_samp_factor * DCTSIZE sample rows of each component in an - * "iMCU" (interleaved MCU) row. - */ - - /* - * These fields are valid during any one scan. - * They describe the components and MCUs actually appearing in the scan. - */ - int comps_in_scan; /* # of JPEG components in this scan */ - jpeg_component_info * cur_comp_info[MAX_COMPS_IN_SCAN]; - /* *cur_comp_info[i] describes component that appears i'th in SOS */ - - JDIMENSION MCUs_per_row; /* # of MCUs across the image */ - JDIMENSION MCU_rows_in_scan; /* # of MCU rows in the image */ - - int blocks_in_MCU; /* # of DCT blocks per MCU */ - int MCU_membership[C_MAX_BLOCKS_IN_MCU]; - /* MCU_membership[i] is index in cur_comp_info of component owning */ - /* i'th block in an MCU */ - - int Ss, Se, Ah, Al; /* progressive JPEG parameters for scan */ - - /* - * Links to compression subobjects (methods and private variables of modules) - */ - struct jpeg_comp_master * master; - struct jpeg_c_main_controller * main; - struct jpeg_c_prep_controller * prep; - struct jpeg_c_coef_controller * coef; - struct jpeg_marker_writer * marker; - struct jpeg_color_converter * cconvert; - struct jpeg_downsampler * downsample; - struct jpeg_forward_dct * fdct; - struct jpeg_entropy_encoder * entropy; -}; - - -/* Master record for a decompression instance */ - -struct jpeg_decompress_struct { - jpeg_common_fields; /* Fields shared with jpeg_compress_struct */ - - /* Source of compressed data */ - struct jpeg_source_mgr * src; - - /* Basic description of image --- filled in by jpeg_read_header(). */ - /* Application may inspect these values to decide how to process image. */ - - JDIMENSION image_width; /* nominal image width (from SOF marker) */ - JDIMENSION image_height; /* nominal image height */ - int num_components; /* # of color components in JPEG image */ - J_COLOR_SPACE jpeg_color_space; /* colorspace of JPEG image */ - - /* Decompression processing parameters --- these fields must be set before - * calling jpeg_start_decompress(). Note that jpeg_read_header() initializes - * them to default values. - */ - - J_COLOR_SPACE out_color_space; /* colorspace for output */ - - unsigned int scale_num, scale_denom; /* fraction by which to scale image */ - - double output_gamma; /* image gamma wanted in output */ - - boolean buffered_image; /* TRUE=multiple output passes */ - boolean raw_data_out; /* TRUE=downsampled data wanted */ - - J_DCT_METHOD dct_method; /* IDCT algorithm selector */ - boolean do_fancy_upsampling; /* TRUE=apply fancy upsampling */ - boolean do_block_smoothing; /* TRUE=apply interblock smoothing */ - - boolean quantize_colors; /* TRUE=colormapped output wanted */ - /* the following are ignored if not quantize_colors: */ - J_DITHER_MODE dither_mode; /* type of color dithering to use */ - boolean two_pass_quantize; /* TRUE=use two-pass color quantization */ - int desired_number_of_colors; /* max # colors to use in created colormap */ - /* these are significant only in buffered-image mode: */ - boolean enable_1pass_quant; /* enable future use of 1-pass quantizer */ - boolean enable_external_quant; /* enable future use of external colormap */ - boolean enable_2pass_quant; /* enable future use of 2-pass quantizer */ - - /* Description of actual output image that will be returned to application. - * These fields are computed by jpeg_start_decompress(). - * You can also use jpeg_calc_output_dimensions() to determine these values - * in advance of calling jpeg_start_decompress(). - */ - - JDIMENSION output_width; /* scaled image width */ - JDIMENSION output_height; /* scaled image height */ - int out_color_components; /* # of color components in out_color_space */ - int output_components; /* # of color components returned */ - /* output_components is 1 (a colormap index) when quantizing colors; - * otherwise it equals out_color_components. - */ - int rec_outbuf_height; /* min recommended height of scanline buffer */ - /* If the buffer passed to jpeg_read_scanlines() is less than this many rows - * high, space and time will be wasted due to unnecessary data copying. - * Usually rec_outbuf_height will be 1 or 2, at most 4. - */ - - /* When quantizing colors, the output colormap is described by these fields. - * The application can supply a colormap by setting colormap non-NULL before - * calling jpeg_start_decompress; otherwise a colormap is created during - * jpeg_start_decompress or jpeg_start_output. - * The map has out_color_components rows and actual_number_of_colors columns. - */ - int actual_number_of_colors; /* number of entries in use */ - JSAMPARRAY colormap; /* The color map as a 2-D pixel array */ - - /* State variables: these variables indicate the progress of decompression. - * The application may examine these but must not modify them. - */ - - /* Row index of next scanline to be read from jpeg_read_scanlines(). - * Application may use this to control its processing loop, e.g., - * "while (output_scanline < output_height)". - */ - JDIMENSION output_scanline; /* 0 .. output_height-1 */ - - /* Current input scan number and number of iMCU rows completed in scan. - * These indicate the progress of the decompressor input side. - */ - int input_scan_number; /* Number of SOS markers seen so far */ - JDIMENSION input_iMCU_row; /* Number of iMCU rows completed */ - - /* The "output scan number" is the notional scan being displayed by the - * output side. The decompressor will not allow output scan/row number - * to get ahead of input scan/row, but it can fall arbitrarily far behind. - */ - int output_scan_number; /* Nominal scan number being displayed */ - JDIMENSION output_iMCU_row; /* Number of iMCU rows read */ - - /* Current progression status. coef_bits[c][i] indicates the precision - * with which component c's DCT coefficient i (in zigzag order) is known. - * It is -1 when no data has yet been received, otherwise it is the point - * transform (shift) value for the most recent scan of the coefficient - * (thus, 0 at completion of the progression). - * This pointer is NULL when reading a non-progressive file. - */ - int (*coef_bits)[DCTSIZE2]; /* -1 or current Al value for each coef */ - - /* Internal JPEG parameters --- the application usually need not look at - * these fields. Note that the decompressor output side may not use - * any parameters that can change between scans. - */ - - /* Quantization and Huffman tables are carried forward across input - * datastreams when processing abbreviated JPEG datastreams. - */ - - JQUANT_TBL * quant_tbl_ptrs[NUM_QUANT_TBLS]; - /* ptrs to coefficient quantization tables, or NULL if not defined */ - - JHUFF_TBL * dc_huff_tbl_ptrs[NUM_HUFF_TBLS]; - JHUFF_TBL * ac_huff_tbl_ptrs[NUM_HUFF_TBLS]; - /* ptrs to Huffman coding tables, or NULL if not defined */ - - /* These parameters are never carried across datastreams, since they - * are given in SOF/SOS markers or defined to be reset by SOI. - */ - - int data_precision; /* bits of precision in image data */ - - jpeg_component_info * comp_info; - /* comp_info[i] describes component that appears i'th in SOF */ - - boolean progressive_mode; /* TRUE if SOFn specifies progressive mode */ - boolean arith_code; /* TRUE=arithmetic coding, FALSE=Huffman */ - - UINT8 arith_dc_L[NUM_ARITH_TBLS]; /* L values for DC arith-coding tables */ - UINT8 arith_dc_U[NUM_ARITH_TBLS]; /* U values for DC arith-coding tables */ - UINT8 arith_ac_K[NUM_ARITH_TBLS]; /* Kx values for AC arith-coding tables */ - - unsigned int restart_interval; /* MCUs per restart interval, or 0 for no restart */ - - /* These fields record data obtained from optional markers recognized by - * the JPEG library. - */ - boolean saw_JFIF_marker; /* TRUE iff a JFIF APP0 marker was found */ - /* Data copied from JFIF marker: */ - UINT8 density_unit; /* JFIF code for pixel size units */ - UINT16 X_density; /* Horizontal pixel density */ - UINT16 Y_density; /* Vertical pixel density */ - boolean saw_Adobe_marker; /* TRUE iff an Adobe APP14 marker was found */ - UINT8 Adobe_transform; /* Color transform code from Adobe marker */ - - boolean CCIR601_sampling; /* TRUE=first samples are cosited */ - - /* Remaining fields are known throughout decompressor, but generally - * should not be touched by a surrounding application. - */ - - /* - * These fields are computed during decompression startup - */ - int max_h_samp_factor; /* largest h_samp_factor */ - int max_v_samp_factor; /* largest v_samp_factor */ - - int min_DCT_scaled_size; /* smallest DCT_scaled_size of any component */ - - JDIMENSION total_iMCU_rows; /* # of iMCU rows in image */ - /* The coefficient controller's input and output progress is measured in - * units of "iMCU" (interleaved MCU) rows. These are the same as MCU rows - * in fully interleaved JPEG scans, but are used whether the scan is - * interleaved or not. We define an iMCU row as v_samp_factor DCT block - * rows of each component. Therefore, the IDCT output contains - * v_samp_factor*DCT_scaled_size sample rows of a component per iMCU row. - */ - - JSAMPLE * sample_range_limit; /* table for fast range-limiting */ - - /* - * These fields are valid during any one scan. - * They describe the components and MCUs actually appearing in the scan. - * Note that the decompressor output side must not use these fields. - */ - int comps_in_scan; /* # of JPEG components in this scan */ - jpeg_component_info * cur_comp_info[MAX_COMPS_IN_SCAN]; - /* *cur_comp_info[i] describes component that appears i'th in SOS */ - - JDIMENSION MCUs_per_row; /* # of MCUs across the image */ - JDIMENSION MCU_rows_in_scan; /* # of MCU rows in the image */ - - int blocks_in_MCU; /* # of DCT blocks per MCU */ - int MCU_membership[D_MAX_BLOCKS_IN_MCU]; - /* MCU_membership[i] is index in cur_comp_info of component owning */ - /* i'th block in an MCU */ - - int Ss, Se, Ah, Al; /* progressive JPEG parameters for scan */ - - /* This field is shared between entropy decoder and marker parser. - * It is either zero or the code of a JPEG marker that has been - * read from the data source, but has not yet been processed. - */ - int unread_marker; - - /* - * Links to decompression subobjects (methods, private variables of modules) - */ - struct jpeg_decomp_master * master; - struct jpeg_d_main_controller * main; - struct jpeg_d_coef_controller * coef; - struct jpeg_d_post_controller * post; - struct jpeg_input_controller * inputctl; - struct jpeg_marker_reader * marker; - struct jpeg_entropy_decoder * entropy; - struct jpeg_inverse_dct * idct; - struct jpeg_upsampler * upsample; - struct jpeg_color_deconverter * cconvert; - struct jpeg_color_quantizer * cquantize; -}; - - -/* "Object" declarations for JPEG modules that may be supplied or called - * directly by the surrounding application. - * As with all objects in the JPEG library, these structs only define the - * publicly visible methods and state variables of a module. Additional - * private fields may exist after the public ones. - */ - - -/* Error handler object */ - -struct jpeg_error_mgr { - /* Error exit handler: does not return to caller */ - JMETHOD( void, error_exit, (j_common_ptr cinfo) ); - /* Conditionally emit a trace or warning message */ - JMETHOD( void, emit_message, ( j_common_ptr cinfo, int msg_level ) ); - /* Routine that actually outputs a trace or error message */ - JMETHOD( void, output_message, (j_common_ptr cinfo) ); - /* Format a message string for the most recent JPEG error or message */ - JMETHOD( void, format_message, ( j_common_ptr cinfo, char * buffer ) ); -#define JMSG_LENGTH_MAX 200 /* recommended size of format_message buffer */ - /* Reset error state variables at start of a new image */ - JMETHOD( void, reset_error_mgr, (j_common_ptr cinfo) ); - - /* The message ID code and any parameters are saved here. - * A message can have one string parameter or up to 8 int parameters. - */ - int msg_code; -#define JMSG_STR_PARM_MAX 80 - union { - int i[8]; - char s[JMSG_STR_PARM_MAX]; - } msg_parm; - - /* Standard state variables for error facility */ - - int trace_level; /* max msg_level that will be displayed */ - - /* For recoverable corrupt-data errors, we emit a warning message, - * but keep going unless emit_message chooses to abort. emit_message - * should count warnings in num_warnings. The surrounding application - * can check for bad data by seeing if num_warnings is nonzero at the - * end of processing. - */ - long num_warnings; /* number of corrupt-data warnings */ - - /* These fields point to the table(s) of error message strings. - * An application can change the table pointer to switch to a different - * message list (typically, to change the language in which errors are - * reported). Some applications may wish to add additional error codes - * that will be handled by the JPEG library error mechanism; the second - * table pointer is used for this purpose. - * - * First table includes all errors generated by JPEG library itself. - * Error code 0 is reserved for a "no such error string" message. - */ - const char * const * jpeg_message_table; /* Library errors */ - int last_jpeg_message; /* Table contains strings 0..last_jpeg_message */ - /* Second table can be added by application (see cjpeg/djpeg for example). - * It contains strings numbered first_addon_message..last_addon_message. - */ - const char * const * addon_message_table; /* Non-library errors */ - int first_addon_message; /* code for first string in addon table */ - int last_addon_message; /* code for last string in addon table */ -}; - - -/* Progress monitor object */ - -struct jpeg_progress_mgr { - JMETHOD( void, progress_monitor, (j_common_ptr cinfo) ); - - long pass_counter; /* work units completed in this pass */ - long pass_limit; /* total number of work units in this pass */ - int completed_passes; /* passes completed so far */ - int total_passes; /* total number of passes expected */ -}; - - -/* Data destination object for compression */ - -struct jpeg_destination_mgr { - JOCTET * next_output_byte; /* => next byte to write in buffer */ - size_t free_in_buffer; /* # of byte spaces remaining in buffer */ - - JMETHOD( void, init_destination, (j_compress_ptr cinfo) ); - JMETHOD( boolean, empty_output_buffer, (j_compress_ptr cinfo) ); - JMETHOD( void, term_destination, (j_compress_ptr cinfo) ); -}; - - -/* Data source object for decompression */ - -struct jpeg_source_mgr { - const JOCTET * next_input_byte; /* => next byte to read from buffer */ - size_t bytes_in_buffer; /* # of bytes remaining in buffer */ - - JMETHOD( void, init_source, (j_decompress_ptr cinfo) ); - JMETHOD( boolean, fill_input_buffer, (j_decompress_ptr cinfo) ); - JMETHOD( void, skip_input_data, ( j_decompress_ptr cinfo, long num_bytes ) ); - JMETHOD( boolean, resync_to_restart, ( j_decompress_ptr cinfo, int desired ) ); - JMETHOD( void, term_source, (j_decompress_ptr cinfo) ); -}; - - -/* Memory manager object. - * Allocates "small" objects (a few K total), "large" objects (tens of K), - * and "really big" objects (virtual arrays with backing store if needed). - * The memory manager does not allow individual objects to be freed; rather, - * each created object is assigned to a pool, and whole pools can be freed - * at once. This is faster and more convenient than remembering exactly what - * to free, especially where malloc()/free() are not too speedy. - * NB: alloc routines never return NULL. They exit to error_exit if not - * successful. - */ - -#define JPOOL_PERMANENT 0 /* lasts until master record is destroyed */ -#define JPOOL_IMAGE 1 /* lasts until done with image/datastream */ -#define JPOOL_NUMPOOLS 2 - -typedef struct jvirt_sarray_control * jvirt_sarray_ptr; -typedef struct jvirt_barray_control * jvirt_barray_ptr; - - -struct jpeg_memory_mgr { - /* Method pointers */ - JMETHOD( void *, alloc_small, ( j_common_ptr cinfo, int pool_id, - size_t sizeofobject ) ); - JMETHOD( void FAR *, alloc_large, ( j_common_ptr cinfo, int pool_id, - size_t sizeofobject ) ); - JMETHOD( JSAMPARRAY, alloc_sarray, ( j_common_ptr cinfo, int pool_id, - JDIMENSION samplesperrow, - JDIMENSION numrows ) ); - JMETHOD( JBLOCKARRAY, alloc_barray, ( j_common_ptr cinfo, int pool_id, - JDIMENSION blocksperrow, - JDIMENSION numrows ) ); - JMETHOD( jvirt_sarray_ptr, request_virt_sarray, ( j_common_ptr cinfo, - int pool_id, - boolean pre_zero, - JDIMENSION samplesperrow, - JDIMENSION numrows, - JDIMENSION maxaccess ) ); - JMETHOD( jvirt_barray_ptr, request_virt_barray, ( j_common_ptr cinfo, - int pool_id, - boolean pre_zero, - JDIMENSION blocksperrow, - JDIMENSION numrows, - JDIMENSION maxaccess ) ); - JMETHOD( void, realize_virt_arrays, (j_common_ptr cinfo) ); - JMETHOD( JSAMPARRAY, access_virt_sarray, ( j_common_ptr cinfo, - jvirt_sarray_ptr ptr, - JDIMENSION start_row, - JDIMENSION num_rows, - boolean writable ) ); - JMETHOD( JBLOCKARRAY, access_virt_barray, ( j_common_ptr cinfo, - jvirt_barray_ptr ptr, - JDIMENSION start_row, - JDIMENSION num_rows, - boolean writable ) ); - JMETHOD( void, free_pool, ( j_common_ptr cinfo, int pool_id ) ); - JMETHOD( void, self_destruct, (j_common_ptr cinfo) ); - - /* Limit on memory allocation for this JPEG object. (Note that this is - * merely advisory, not a guaranteed maximum; it only affects the space - * used for virtual-array buffers.) May be changed by outer application - * after creating the JPEG object. - */ - long max_memory_to_use; -}; - - -/* Routine signature for application-supplied marker processing methods. - * Need not pass marker code since it is stored in cinfo->unread_marker. - */ -typedef JMETHOD ( boolean, jpeg_marker_parser_method, ( j_decompress_ptr cinfo ) ); - - -/* Declarations for routines called by application. - * The JPP macro hides prototype parameters from compilers that can't cope. - * Note JPP requires double parentheses. - */ - -#ifdef HAVE_PROTOTYPES -#define JPP( arglist ) arglist -#else -#define JPP( arglist ) ( ) -#endif - - -/* Short forms of external names for systems with brain-damaged linkers. - * We shorten external names to be unique in the first six letters, which - * is good enough for all known systems. - * (If your compiler itself needs names to be unique in less than 15 - * characters, you are out of luck. Get a better compiler.) - */ - -#ifdef NEED_SHORT_EXTERNAL_NAMES -#define jpeg_std_error jStdError -#define jpeg_create_compress jCreaCompress -#define jpeg_create_decompress jCreaDecompress -#define jpeg_destroy_compress jDestCompress -#define jpeg_destroy_decompress jDestDecompress -#define jpeg_stdio_dest jStdDest -#define jpeg_stdio_src jStdSrc -#define jpeg_set_defaults jSetDefaults -#define jpeg_set_colorspace jSetColorspace -#define jpeg_default_colorspace jDefColorspace -#define jpeg_set_quality jSetQuality -#define jpeg_set_linear_quality jSetLQuality -#define jpeg_add_quant_table jAddQuantTable -#define jpeg_quality_scaling jQualityScaling -#define jpeg_simple_progression jSimProgress -#define jpeg_suppress_tables jSuppressTables -#define jpeg_alloc_quant_table jAlcQTable -#define jpeg_alloc_huff_table jAlcHTable -#define jpeg_start_compress jStrtCompress -#define jpeg_write_scanlines jWrtScanlines -#define jpeg_finish_compress jFinCompress -#define jpeg_write_raw_data jWrtRawData -#define jpeg_write_marker jWrtMarker -#define jpeg_write_tables jWrtTables -#define jpeg_read_header jReadHeader -#define jpeg_start_decompress jStrtDecompress -#define jpeg_read_scanlines jReadScanlines -#define jpeg_finish_decompress jFinDecompress -#define jpeg_read_raw_data jReadRawData -#define jpeg_has_multiple_scans jHasMultScn -#define jpeg_start_output jStrtOutput -#define jpeg_finish_output jFinOutput -#define jpeg_input_complete jInComplete -#define jpeg_new_colormap jNewCMap -#define jpeg_consume_input jConsumeInput -#define jpeg_calc_output_dimensions jCalcDimensions -#define jpeg_set_marker_processor jSetMarker -#define jpeg_read_coefficients jReadCoefs -#define jpeg_write_coefficients jWrtCoefs -#define jpeg_copy_critical_parameters jCopyCrit -#define jpeg_abort_compress jAbrtCompress -#define jpeg_abort_decompress jAbrtDecompress -#define jpeg_abort jAbort -#define jpeg_destroy jDestroy -#define jpeg_resync_to_restart jResyncRestart -#endif /* NEED_SHORT_EXTERNAL_NAMES */ - - -/* Default error-management setup */ -EXTERN struct jpeg_error_mgr *jpeg_std_error JPP( (struct jpeg_error_mgr *err) ); - -/* Initialization and destruction of JPEG compression objects */ -/* NB: you must set up the error-manager BEFORE calling jpeg_create_xxx */ -EXTERN void jpeg_create_compress JPP( (j_compress_ptr cinfo) ); -EXTERN void jpeg_create_decompress JPP( (j_decompress_ptr cinfo) ); -EXTERN void jpeg_destroy_compress JPP( (j_compress_ptr cinfo) ); -EXTERN void jpeg_destroy_decompress JPP( (j_decompress_ptr cinfo) ); - -/* Standard data source and destination managers: stdio streams. */ -/* Caller is responsible for opening the file before and closing after. */ -EXTERN void jpeg_stdio_dest JPP( ( j_compress_ptr cinfo, FILE * outfile ) ); -EXTERN void jpeg_stdio_src JPP( ( j_decompress_ptr cinfo, unsigned char *infile, int bufsize ) ); - -/* Default parameter setup for compression */ -EXTERN void jpeg_set_defaults JPP( (j_compress_ptr cinfo) ); -/* Compression parameter setup aids */ -EXTERN void jpeg_set_colorspace JPP( ( j_compress_ptr cinfo, - J_COLOR_SPACE colorspace ) ); -EXTERN void jpeg_default_colorspace JPP( (j_compress_ptr cinfo) ); -EXTERN void jpeg_set_quality JPP( ( j_compress_ptr cinfo, int quality, - boolean force_baseline ) ); -EXTERN void jpeg_set_linear_quality JPP( ( j_compress_ptr cinfo, - int scale_factor, - boolean force_baseline ) ); -EXTERN void jpeg_add_quant_table JPP( ( j_compress_ptr cinfo, int which_tbl, - const unsigned int *basic_table, - int scale_factor, - boolean force_baseline ) ); -EXTERN int jpeg_quality_scaling JPP( (int quality) ); -EXTERN void jpeg_simple_progression JPP( (j_compress_ptr cinfo) ); -EXTERN void jpeg_suppress_tables JPP( ( j_compress_ptr cinfo, - boolean suppress ) ); -EXTERN JQUANT_TBL * jpeg_alloc_quant_table JPP( (j_common_ptr cinfo) ); -EXTERN JHUFF_TBL * jpeg_alloc_huff_table JPP( (j_common_ptr cinfo) ); - -/* Main entry points for compression */ -EXTERN void jpeg_start_compress JPP( ( j_compress_ptr cinfo, - boolean write_all_tables ) ); -EXTERN JDIMENSION jpeg_write_scanlines JPP( ( j_compress_ptr cinfo, - JSAMPARRAY scanlines, - JDIMENSION num_lines ) ); -EXTERN void jpeg_finish_compress JPP( (j_compress_ptr cinfo) ); - -/* Replaces jpeg_write_scanlines when writing raw downsampled data. */ -EXTERN JDIMENSION jpeg_write_raw_data JPP( ( j_compress_ptr cinfo, - JSAMPIMAGE data, - JDIMENSION num_lines ) ); - -/* Write a special marker. See libjpeg.doc concerning safe usage. */ -EXTERN void jpeg_write_marker JPP( ( j_compress_ptr cinfo, int marker, - const JOCTET * dataptr, unsigned int datalen ) ); - -/* Alternate compression function: just write an abbreviated table file */ -EXTERN void jpeg_write_tables JPP( (j_compress_ptr cinfo) ); - -/* Decompression startup: read start of JPEG datastream to see what's there */ -EXTERN int jpeg_read_header JPP( ( j_decompress_ptr cinfo, - boolean require_image ) ); -/* Return value is one of: */ -#define JPEG_SUSPENDED 0 /* Suspended due to lack of input data */ -#define JPEG_HEADER_OK 1 /* Found valid image datastream */ -#define JPEG_HEADER_TABLES_ONLY 2 /* Found valid table-specs-only datastream */ -/* If you pass require_image = TRUE (normal case), you need not check for - * a TABLES_ONLY return code; an abbreviated file will cause an error exit. - * JPEG_SUSPENDED is only possible if you use a data source module that can - * give a suspension return (the stdio source module doesn't). - */ - -/* Main entry points for decompression */ -EXTERN boolean jpeg_start_decompress JPP( (j_decompress_ptr cinfo) ); -EXTERN JDIMENSION jpeg_read_scanlines JPP( ( j_decompress_ptr cinfo, - JSAMPARRAY scanlines, - JDIMENSION max_lines ) ); -EXTERN boolean jpeg_finish_decompress JPP( (j_decompress_ptr cinfo) ); - -/* Replaces jpeg_read_scanlines when reading raw downsampled data. */ -EXTERN JDIMENSION jpeg_read_raw_data JPP( ( j_decompress_ptr cinfo, - JSAMPIMAGE data, - JDIMENSION max_lines ) ); - -/* Additional entry points for buffered-image mode. */ -EXTERN boolean jpeg_has_multiple_scans JPP( (j_decompress_ptr cinfo) ); -EXTERN boolean jpeg_start_output JPP( ( j_decompress_ptr cinfo, - int scan_number ) ); -EXTERN boolean jpeg_finish_output JPP( (j_decompress_ptr cinfo) ); -EXTERN boolean jpeg_input_complete JPP( (j_decompress_ptr cinfo) ); -EXTERN void jpeg_new_colormap JPP( (j_decompress_ptr cinfo) ); -EXTERN int jpeg_consume_input JPP( (j_decompress_ptr cinfo) ); -/* Return value is one of: */ -/* #define JPEG_SUSPENDED 0 Suspended due to lack of input data */ -#define JPEG_REACHED_SOS 1 /* Reached start of new scan */ -#define JPEG_REACHED_EOI 2 /* Reached end of image */ -#define JPEG_ROW_COMPLETED 3 /* Completed one iMCU row */ -#define JPEG_SCAN_COMPLETED 4 /* Completed last iMCU row of a scan */ - -/* Precalculate output dimensions for current decompression parameters. */ -EXTERN void jpeg_calc_output_dimensions JPP( (j_decompress_ptr cinfo) ); - -/* Install a special processing method for COM or APPn markers. */ -EXTERN void jpeg_set_marker_processor JPP( ( j_decompress_ptr cinfo, - int marker_code, - jpeg_marker_parser_method routine ) ); - -/* Read or write raw DCT coefficients --- useful for lossless transcoding. */ -EXTERN jvirt_barray_ptr * jpeg_read_coefficients JPP( (j_decompress_ptr cinfo) ); -EXTERN void jpeg_write_coefficients JPP( ( j_compress_ptr cinfo, - jvirt_barray_ptr * coef_arrays ) ); -EXTERN void jpeg_copy_critical_parameters JPP( ( j_decompress_ptr srcinfo, - j_compress_ptr dstinfo ) ); - -/* If you choose to abort compression or decompression before completing - * jpeg_finish_(de)compress, then you need to clean up to release memory, - * temporary files, etc. You can just call jpeg_destroy_(de)compress - * if you're done with the JPEG object, but if you want to clean it up and - * reuse it, call this: - */ -EXTERN void jpeg_abort_compress JPP( (j_compress_ptr cinfo) ); -EXTERN void jpeg_abort_decompress JPP( (j_decompress_ptr cinfo) ); - -/* Generic versions of jpeg_abort and jpeg_destroy that work on either - * flavor of JPEG object. These may be more convenient in some places. - */ -EXTERN void jpeg_abort JPP( (j_common_ptr cinfo) ); -EXTERN void jpeg_destroy JPP( (j_common_ptr cinfo) ); - -/* Default restart-marker-resync procedure for use by data source modules */ -EXTERN boolean jpeg_resync_to_restart JPP( ( j_decompress_ptr cinfo, - int desired ) ); - - -/* These marker codes are exported since applications and data source modules - * are likely to want to use them. - */ - -#define JPEG_RST0 0xD0 /* RST0 marker code */ -#define JPEG_EOI 0xD9 /* EOI marker code */ -#define JPEG_APP0 0xE0 /* APP0 marker code */ -#define JPEG_COM 0xFE /* COM marker code */ - - -/* If we have a brain-damaged compiler that emits warnings (or worse, errors) - * for structure definitions that are never filled in, keep it quiet by - * supplying dummy definitions for the various substructures. - */ - -#ifdef INCOMPLETE_TYPES_BROKEN -#ifndef JPEG_INTERNALS /* will be defined in jpegint.h */ -struct jvirt_sarray_control { long dummy; }; -struct jvirt_barray_control { long dummy; }; -struct jpeg_comp_master { long dummy; }; -struct jpeg_c_main_controller { long dummy; }; -struct jpeg_c_prep_controller { long dummy; }; -struct jpeg_c_coef_controller { long dummy; }; -struct jpeg_marker_writer { long dummy; }; -struct jpeg_color_converter { long dummy; }; -struct jpeg_downsampler { long dummy; }; -struct jpeg_forward_dct { long dummy; }; -struct jpeg_entropy_encoder { long dummy; }; -struct jpeg_decomp_master { long dummy; }; -struct jpeg_d_main_controller { long dummy; }; -struct jpeg_d_coef_controller { long dummy; }; -struct jpeg_d_post_controller { long dummy; }; -struct jpeg_input_controller { long dummy; }; -struct jpeg_marker_reader { long dummy; }; -struct jpeg_entropy_decoder { long dummy; }; -struct jpeg_inverse_dct { long dummy; }; -struct jpeg_upsampler { long dummy; }; -struct jpeg_color_deconverter { long dummy; }; -struct jpeg_color_quantizer { long dummy; }; -#endif /* JPEG_INTERNALS */ -#endif /* INCOMPLETE_TYPES_BROKEN */ - - -/* - * The JPEG library modules define JPEG_INTERNALS before including this file. - * The internal structure declarations are read only when that is true. - * Applications using the library should not include jpegint.h, but may wish - * to include jerror.h. - */ - -#ifdef JPEG_INTERNALS -#include "jpegint.h" /* fetch private declarations */ -#include "jerror.h" /* fetch error codes too */ -#endif - -#ifdef __cplusplus -} -#endif - -#endif /* JPEGLIB_H */ diff --git a/tools/urt/libs/l_net/l_net.c b/tools/urt/libs/l_net/l_net.c deleted file mode 100644 index bb92bde..0000000 --- a/tools/urt/libs/l_net/l_net.c +++ /dev/null @@ -1,587 +0,0 @@ -/* - Copyright (C) 1999-2007 id Software, Inc. and contributors. - For a list of contributors, see the accompanying CONTRIBUTORS file. - - This file is part of GtkRadiant. - - GtkRadiant is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - GtkRadiant is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with GtkRadiant; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - */ - -//==================================================================== -// -// Name: l_net.c -// Function: - -// Programmer: MrElusive -// Last update: - -// Tab size: 3 -// Notes: -//==================================================================== - -#include -#include -#include -#include -#include "l_net.h" -#include "l_net_wins.h" - -#define GetMemory malloc -#define FreeMemory free - -#define qtrue 1 -#define qfalse 0 - -#ifdef _DEBUG -void WinPrint( char *str, ... ){ - va_list argptr; - char text[4096]; - - va_start( argptr,str ); - vsprintf( text, str, argptr ); - va_end( argptr ); - - printf( text ); -} -#else -void WinPrint( char *str, ... ){ -} -#endif - -//=========================================================================== -// -// Parameter: - -// Returns: - -// Changes Globals: - -//=========================================================================== -void Net_SetAddressPort( address_t *address, int port ){ - sockaddr_t addr; - - WINS_StringToAddr( address->ip, &addr ); - WINS_SetSocketPort( &addr, port ); - strcpy( address->ip, WINS_AddrToString( &addr ) ); -} //end of the function Net_SetAddressPort -//=========================================================================== -// -// Parameter: - -// Returns: - -// Changes Globals: - -//=========================================================================== -int Net_AddressCompare( address_t *addr1, address_t *addr2 ){ -#ifdef WIN32 - return stricmp( addr1->ip, addr2->ip ); -#endif -#ifdef __linux__ - return strcasecmp( addr1->ip, addr2->ip ); -#endif -} //end of the function Net_AddressCompare -//=========================================================================== -// -// Parameter: - -// Returns: - -// Changes Globals: - -//=========================================================================== -void Net_SocketToAddress( socket_t *sock, address_t *address ){ - strcpy( address->ip, WINS_AddrToString( &sock->addr ) ); -} //end of the function Net_SocketToAddress -//=========================================================================== -// -// Parameter: - -// Returns: - -// Changes Globals: - -//=========================================================================== -int Net_Send( socket_t *sock, netmessage_t *msg ){ - int size; - - size = msg->size; - msg->size = 0; - NMSG_WriteLong( msg, size - 4 ); - msg->size = size; - //WinPrint("Net_Send: message of size %d\n", sendmsg.size); - return WINS_Write( sock->socket, msg->data, msg->size, NULL ); -} //end of the function Net_SendSocketReliable -//=========================================================================== -// returns the number of bytes recieved -// -1 on error -// -// Parameter: - -// Returns: - -// Changes Globals: - -//=========================================================================== -int Net_Receive( socket_t *sock, netmessage_t *msg ){ - int curread; - - if ( sock->remaining > 0 ) { - curread = WINS_Read( sock->socket, &sock->msg.data[sock->msg.size], sock->remaining, NULL ); - if ( curread == -1 ) { - WinPrint( "Net_Receive: read error\n" ); - return -1; - } //end if - sock->remaining -= curread; - sock->msg.size += curread; - if ( sock->remaining <= 0 ) { - sock->remaining = 0; - memcpy( msg, &sock->msg, sizeof( netmessage_t ) ); - sock->msg.size = 0; - return msg->size - 4; - } //end if - return 0; - } //end if - sock->msg.size = WINS_Read( sock->socket, sock->msg.data, 4, NULL ); - if ( sock->msg.size == 0 ) { - return 0; - } - if ( sock->msg.size == -1 ) { - WinPrint( "Net_Receive: size header read error\n" ); - return -1; - } //end if - //WinPrint("Net_Receive: message size header %d\n", msg->size); - sock->msg.read = 0; - sock->remaining = NMSG_ReadLong( &sock->msg ); - if ( sock->remaining == 0 ) { - return 0; - } - if ( sock->remaining < 0 || sock->remaining > MAX_NETMESSAGE ) { - WinPrint( "Net_Receive: invalid message size %d\n", sock->remaining ); - return -1; - } //end if - //try to read the message - curread = WINS_Read( sock->socket, &sock->msg.data[sock->msg.size], sock->remaining, NULL ); - if ( curread == -1 ) { - WinPrint( "Net_Receive: read error\n" ); - return -1; - } //end if - sock->remaining -= curread; - sock->msg.size += curread; - if ( sock->remaining <= 0 ) { - sock->remaining = 0; - memcpy( msg, &sock->msg, sizeof( netmessage_t ) ); - sock->msg.size = 0; - return msg->size - 4; - } //end if - //the message has not been completely read yet -#ifdef _DEBUG - printf( "++timo TODO: debug the Net_Receive on big size messages\n" ); -#endif - return 0; -} //end of the function Net_Receive -//=========================================================================== -// -// Parameter: - -// Returns: - -// Changes Globals: - -//=========================================================================== -socket_t *Net_AllocSocket( void ){ - socket_t *sock; - - sock = (socket_t *) GetMemory( sizeof( socket_t ) ); - memset( sock, 0, sizeof( socket_t ) ); - return sock; -} //end of the function Net_AllocSocket -//=========================================================================== -// -// Parameter: - -// Returns: - -// Changes Globals: - -//=========================================================================== -void Net_FreeSocket( socket_t *sock ){ - FreeMemory( sock ); -} //end of the function Net_FreeSocket -//=========================================================================== -// -// Parameter: - -// Returns: - -// Changes Globals: - -//=========================================================================== -socket_t *Net_Connect( address_t *address, int port ){ - int newsock; - socket_t *sock; - sockaddr_t sendaddr; - - // see if we can resolve the host name - WINS_StringToAddr( address->ip, &sendaddr ); - - newsock = WINS_OpenReliableSocket( port ); - if ( newsock == -1 ) { - return NULL; - } - - sock = Net_AllocSocket(); - if ( sock == NULL ) { - WINS_CloseSocket( newsock ); - return NULL; - } //end if - sock->socket = newsock; - - //connect to the host - if ( WINS_Connect( newsock, &sendaddr ) == -1 ) { - Net_FreeSocket( sock ); - WINS_CloseSocket( newsock ); - WinPrint( "Net_Connect: error connecting\n" ); - return NULL; - } //end if - - memcpy( &sock->addr, &sendaddr, sizeof( sockaddr_t ) ); - //now we can send messages - // - return sock; -} //end of the function Net_Connect - -//=========================================================================== -// -// Parameter: - -// Returns: - -// Changes Globals: - -//=========================================================================== -socket_t *Net_ListenSocket( int port ){ - int newsock; - socket_t *sock; - - newsock = WINS_OpenReliableSocket( port ); - if ( newsock == -1 ) { - return NULL; - } - - if ( WINS_Listen( newsock ) == -1 ) { - WINS_CloseSocket( newsock ); - return NULL; - } //end if - sock = Net_AllocSocket(); - if ( sock == NULL ) { - WINS_CloseSocket( newsock ); - return NULL; - } //end if - sock->socket = newsock; - WINS_GetSocketAddr( newsock, &sock->addr ); - WinPrint( "listen socket opened at %s\n", WINS_AddrToString( &sock->addr ) ); - // - return sock; -} //end of the function Net_ListenSocket -//=========================================================================== -// -// Parameter: - -// Returns: - -// Changes Globals: - -//=========================================================================== -socket_t *Net_Accept( socket_t *sock ){ - int newsocket; - sockaddr_t sendaddr; - socket_t *newsock; - - newsocket = WINS_Accept( sock->socket, &sendaddr ); - if ( newsocket == -1 ) { - return NULL; - } - - newsock = Net_AllocSocket(); - if ( newsock == NULL ) { - WINS_CloseSocket( newsocket ); - return NULL; - } //end if - newsock->socket = newsocket; - memcpy( &newsock->addr, &sendaddr, sizeof( sockaddr_t ) ); - // - return newsock; -} //end of the function Net_Accept -//=========================================================================== -// -// Parameter: - -// Returns: - -// Changes Globals: - -//=========================================================================== -void Net_Disconnect( socket_t *sock ){ - WINS_CloseSocket( sock->socket ); - Net_FreeSocket( sock ); -} //end of the function Net_Disconnect -//=========================================================================== -// -// Parameter: - -// Returns: - -// Changes Globals: - -//=========================================================================== -void Net_StringToAddress( char *string, address_t *address ){ - strcpy( address->ip, string ); -} //end of the function Net_StringToAddress -//=========================================================================== -// -// Parameter: - -// Returns: - -// Changes Globals: - -//=========================================================================== -void Net_MyAddress( address_t *address ){ - strcpy( address->ip, WINS_MyAddress() ); -} //end of the function Net_MyAddress -//=========================================================================== -// -// Parameter: - -// Returns: - -// Changes Globals: - -//=========================================================================== -int Net_Setup( void ){ - WINS_Init(); - // - WinPrint( "my address is %s\n", WINS_MyAddress() ); - // - return qtrue; -} //end of the function Net_Setup -//=========================================================================== -// -// Parameter: - -// Returns: - -// Changes Globals: - -//=========================================================================== -void Net_Shutdown( void ){ - WINS_Shutdown(); -} //end of the function Net_Shutdown -//=========================================================================== -// -// Parameter: - -// Returns: - -// Changes Globals: - -//=========================================================================== -void NMSG_Clear( netmessage_t *msg ){ - msg->size = 4; -} //end of the function NMSG_Clear -//=========================================================================== -// -// Parameter: - -// Returns: - -// Changes Globals: - -//=========================================================================== -void NMSG_WriteChar( netmessage_t *msg, int c ){ - if ( c < -128 || c > 127 ) { - WinPrint( "NMSG_WriteChar: range error\n" ); - } - - if ( msg->size >= MAX_NETMESSAGE ) { - WinPrint( "NMSG_WriteChar: overflow\n" ); - return; - } //end if - msg->data[msg->size] = c; - msg->size++; -} //end of the function NMSG_WriteChar -//=========================================================================== -// -// Parameter: - -// Returns: - -// Changes Globals: - -//=========================================================================== -void NMSG_WriteByte( netmessage_t *msg, int c ){ - if ( c < -128 || c > 127 ) { - WinPrint( "NMSG_WriteByte: range error\n" ); - } - - if ( msg->size + 1 >= MAX_NETMESSAGE ) { - WinPrint( "NMSG_WriteByte: overflow\n" ); - return; - } //end if - msg->data[msg->size] = c; - msg->size++; -} //end of the function NMSG_WriteByte -//=========================================================================== -// -// Parameter: - -// Returns: - -// Changes Globals: - -//=========================================================================== -void NMSG_WriteShort( netmessage_t *msg, int c ){ - if ( c < ( (short)0x8000 ) || c > (short)0x7fff ) { - WinPrint( "NMSG_WriteShort: range error" ); - } - - if ( msg->size + 2 >= MAX_NETMESSAGE ) { - WinPrint( "NMSG_WriteShort: overflow\n" ); - return; - } //end if - msg->data[msg->size] = c & 0xff; - msg->data[msg->size + 1] = c >> 8; - msg->size += 2; -} //end of the function NMSG_WriteShort -//=========================================================================== -// -// Parameter: - -// Returns: - -// Changes Globals: - -//=========================================================================== -void NMSG_WriteLong( netmessage_t *msg, int c ){ - if ( msg->size + 4 >= MAX_NETMESSAGE ) { - WinPrint( "NMSG_WriteLong: overflow\n" ); - return; - } //end if - msg->data[msg->size] = c & 0xff; - msg->data[msg->size + 1] = ( c >> 8 ) & 0xff; - msg->data[msg->size + 2] = ( c >> 16 ) & 0xff; - msg->data[msg->size + 3] = c >> 24; - msg->size += 4; -} //end of the function NMSG_WriteLong -//=========================================================================== -// -// Parameter: - -// Returns: - -// Changes Globals: - -//=========================================================================== -void NMSG_WriteFloat( netmessage_t *msg, float c ){ - if ( msg->size + 4 >= MAX_NETMESSAGE ) { - WinPrint( "NMSG_WriteLong: overflow\n" ); - return; - } //end if - msg->data[msg->size] = *( (int *)&c ) & 0xff; - msg->data[msg->size + 1] = ( *( (int *)&c ) >> 8 ) & 0xff; - msg->data[msg->size + 2] = ( *( (int *)&c ) >> 16 ) & 0xff; - msg->data[msg->size + 3] = *( (int *)&c ) >> 24; - msg->size += 4; -} //end of the function NMSG_WriteFloat -//=========================================================================== -// -// Parameter: - -// Returns: - -// Changes Globals: - -//=========================================================================== -void NMSG_WriteString( netmessage_t *msg, char *string ){ - if ( msg->size + strlen( string ) + 1 >= MAX_NETMESSAGE ) { - WinPrint( "NMSG_WriteString: overflow\n" ); - return; - } //end if - strcpy( &msg->data[msg->size], string ); - msg->size += strlen( string ) + 1; -} //end of the function NMSG_WriteString -//=========================================================================== -// -// Parameter: - -// Returns: - -// Changes Globals: - -//=========================================================================== -void NMSG_ReadStart( netmessage_t *msg ){ - msg->readoverflow = qfalse; - msg->read = 4; -} //end of the function NMSG_ReadStart -//=========================================================================== -// -// Parameter: - -// Returns: - -// Changes Globals: - -//=========================================================================== -int NMSG_ReadChar( netmessage_t *msg ){ - if ( msg->size + 1 > msg->size ) { - msg->readoverflow = qtrue; - WinPrint( "NMSG_ReadChar: read overflow\n" ); - return 0; - } //end if - msg->read++; - return msg->data[msg->read - 1]; -} //end of the function NMSG_ReadChar -//=========================================================================== -// -// Parameter: - -// Returns: - -// Changes Globals: - -//=========================================================================== -int NMSG_ReadByte( netmessage_t *msg ){ - if ( msg->read + 1 > msg->size ) { - msg->readoverflow = qtrue; - WinPrint( "NMSG_ReadByte: read overflow\n" ); - return 0; - } //end if - msg->read++; - return msg->data[msg->read - 1]; -} //end of the function NMSG_ReadByte -//=========================================================================== -// -// Parameter: - -// Returns: - -// Changes Globals: - -//=========================================================================== -int NMSG_ReadShort( netmessage_t *msg ){ - int c; - - if ( msg->read + 2 > msg->size ) { - msg->readoverflow = qtrue; - WinPrint( "NMSG_ReadShort: read overflow\n" ); - return 0; - } //end if - c = (short)( msg->data[msg->read] + ( msg->data[msg->read + 1] << 8 ) ); - msg->read += 2; - return c; -} //end of the function NMSG_ReadShort -//=========================================================================== -// -// Parameter: - -// Returns: - -// Changes Globals: - -//=========================================================================== -int NMSG_ReadLong( netmessage_t *msg ){ - int c; - - if ( msg->read + 4 > msg->size ) { - msg->readoverflow = qtrue; - WinPrint( "NMSG_ReadLong: read overflow\n" ); - return 0; - } //end if - c = msg->data[msg->read] - + ( msg->data[msg->read + 1] << 8 ) - + ( msg->data[msg->read + 2] << 16 ) - + ( msg->data[msg->read + 3] << 24 ); - msg->read += 4; - return c; -} //end of the function NMSG_ReadLong -//=========================================================================== -// -// Parameter: - -// Returns: - -// Changes Globals: - -//=========================================================================== -float NMSG_ReadFloat( netmessage_t *msg ){ - int c; - - if ( msg->read + 4 > msg->size ) { - msg->readoverflow = qtrue; - WinPrint( "NMSG_ReadLong: read overflow\n" ); - return 0; - } //end if - c = msg->data[msg->read] - + ( msg->data[msg->read + 1] << 8 ) - + ( msg->data[msg->read + 2] << 16 ) - + ( msg->data[msg->read + 3] << 24 ); - msg->read += 4; - return *(float *)&c; -} //end of the function NMSG_ReadFloat -//=========================================================================== -// -// Parameter: - -// Returns: - -// Changes Globals: - -//=========================================================================== -char *NMSG_ReadString( netmessage_t *msg ){ - static char string[2048]; - int l, c; - - l = 0; - do - { - if ( msg->read + 1 > msg->size ) { - msg->readoverflow = qtrue; - WinPrint( "NMSG_ReadString: read overflow\n" ); - string[l] = 0; - return string; - } //end if - c = msg->data[msg->read]; - msg->read++; - if ( c == 0 ) { - break; - } - string[l] = c; - l++; - } while ( l < sizeof( string ) - 1 ); - string[l] = 0; - return string; -} //end of the function NMSG_ReadString diff --git a/tools/urt/libs/l_net/l_net.dsp b/tools/urt/libs/l_net/l_net.dsp deleted file mode 100644 index 36a1318..0000000 --- a/tools/urt/libs/l_net/l_net.dsp +++ /dev/null @@ -1,118 +0,0 @@ -# Microsoft Developer Studio Project File - Name="l_net" - Package Owner=<4> -# Microsoft Developer Studio Generated Build File, Format Version 6.00 -# ** DO NOT EDIT ** - -# TARGTYPE "Win32 (x86) Static Library" 0x0104 - -CFG=l_net - Win32 Debug -!MESSAGE This is not a valid makefile. To build this project using NMAKE, -!MESSAGE use the Export Makefile command and run -!MESSAGE -!MESSAGE NMAKE /f "l_net.mak". -!MESSAGE -!MESSAGE You can specify a configuration when running NMAKE -!MESSAGE by defining the macro CFG on the command line. For example: -!MESSAGE -!MESSAGE NMAKE /f "l_net.mak" CFG="l_net - Win32 Debug" -!MESSAGE -!MESSAGE Possible choices for configuration are: -!MESSAGE -!MESSAGE "l_net - Win32 Release" (based on "Win32 (x86) Static Library") -!MESSAGE "l_net - Win32 Debug" (based on "Win32 (x86) Static Library") -!MESSAGE - -# Begin Project -# PROP AllowPerConfigDependencies 0 -# PROP Scc_ProjName "l_net" -# PROP Scc_LocalPath "." -CPP=cl.exe -RSC=rc.exe - -!IF "$(CFG)" == "l_net - Win32 Release" - -# PROP BASE Use_MFC 0 -# PROP BASE Use_Debug_Libraries 0 -# PROP BASE Output_Dir "Release" -# PROP BASE Intermediate_Dir "Release" -# PROP BASE Target_Dir "" -# PROP Use_MFC 0 -# PROP Use_Debug_Libraries 0 -# PROP Output_Dir "Release" -# PROP Intermediate_Dir "Release" -# PROP Target_Dir "" -MTL=midl.exe -F90=df.exe -# ADD BASE F90 /compile_only /include:"Release/" /nologo /warn:nofileopt -# ADD F90 /compile_only /include:"Release/" /nologo /warn:nofileopt -# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_MBCS" /D "_LIB" /YX /FD /c -# ADD CPP /nologo /MD /W3 /O2 /D "WIN32" /D "NDEBUG" /D "_MBCS" /D "_LIB" /FD /c -# SUBTRACT CPP /YX -# ADD BASE RSC /l 0x409 /d "NDEBUG" -# ADD RSC /l 0x409 /d "NDEBUG" -BSC32=bscmake.exe -# ADD BASE BSC32 /nologo -# ADD BSC32 /nologo -LIB32=link.exe -lib -# ADD BASE LIB32 /nologo -# ADD LIB32 /nologo - -!ELSEIF "$(CFG)" == "l_net - Win32 Debug" - -# PROP BASE Use_MFC 0 -# PROP BASE Use_Debug_Libraries 1 -# PROP BASE Output_Dir "Debug" -# PROP BASE Intermediate_Dir "Debug" -# PROP BASE Target_Dir "" -# PROP Use_MFC 0 -# PROP Use_Debug_Libraries 1 -# PROP Output_Dir "Debug" -# PROP Intermediate_Dir "Debug" -# PROP Target_Dir "" -MTL=midl.exe -F90=df.exe -# ADD BASE F90 /check:bounds /compile_only /debug:full /include:"Debug/" /nologo /warn:argument_checking /warn:nofileopt -# ADD F90 /check:bounds /compile_only /debug:full /include:"Debug/" /nologo /warn:argument_checking /warn:nofileopt -# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_MBCS" /D "_LIB" /YX /FD /GZ /c -# ADD CPP /nologo /MDd /W3 /Gm /ZI /Od /D "WIN32" /D "_DEBUG" /D "_MBCS" /D "_LIB" /FR /FD /GZ /c -# SUBTRACT CPP /YX -# ADD BASE RSC /l 0x409 /d "_DEBUG" -# ADD RSC /l 0x409 /d "_DEBUG" -BSC32=bscmake.exe -# ADD BASE BSC32 /nologo -# ADD BSC32 /nologo -LIB32=link.exe -lib -# ADD BASE LIB32 /nologo -# ADD LIB32 /nologo - -!ENDIF - -# Begin Target - -# Name "l_net - Win32 Release" -# Name "l_net - Win32 Debug" -# Begin Group "Source Files" - -# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat;f90;for;f;fpp" -# Begin Source File - -SOURCE=.\l_net.c -# End Source File -# Begin Source File - -SOURCE=.\l_net_wins.c -# End Source File -# End Group -# Begin Group "Header Files" - -# PROP Default_Filter "h;hpp;hxx;hm;inl;fi;fd" -# Begin Source File - -SOURCE=.\l_net.h -# End Source File -# Begin Source File - -SOURCE=.\l_net_wins.h -# End Source File -# End Group -# End Target -# End Project diff --git a/tools/urt/libs/l_net/l_net.h b/tools/urt/libs/l_net/l_net.h deleted file mode 100644 index e83b65a..0000000 --- a/tools/urt/libs/l_net/l_net.h +++ /dev/null @@ -1,125 +0,0 @@ -/* - Copyright (C) 1999-2007 id Software, Inc. and contributors. - For a list of contributors, see the accompanying CONTRIBUTORS file. - - This file is part of GtkRadiant. - - GtkRadiant is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - GtkRadiant is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with GtkRadiant; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - */ - -//==================================================================== -// -// Name: l_net.h -// Function: - -// Programmer: MrElusive -// Last update: TTimo: cross-platform version, l_net library -// Tab size: 2 -// Notes: -//==================================================================== - -//++timo FIXME: the l_net code understands that as the max size for the netmessage_s structure -// we have defined unsigned char data[MAX_NETMESSAGE] in netmessage_s but actually it cannot be filled completely -// we need to introduce a new #define and adapt to data[MAX_NETBUFFER] -#define MAX_NETMESSAGE 1024 -#define MAX_NETADDRESS 32 - -#ifdef __cplusplus -extern "C" { -#endif - -#ifndef __BYTEBOOL__ -#define __BYTEBOOL__ -typedef enum { qfalse, qtrue } qboolean; -typedef unsigned char byte; -#endif - -typedef struct address_s -{ - char ip[MAX_NETADDRESS]; -} address_t; - -typedef struct sockaddr_s -{ - short sa_family; - unsigned char sa_data[14]; -} sockaddr_t; - -typedef struct netmessage_s -{ - unsigned char data[MAX_NETMESSAGE]; - int size; - int read; - int readoverflow; -} netmessage_t; - -typedef struct socket_s -{ - int socket; //socket number - sockaddr_t addr; //socket address - netmessage_t msg; //current message being read - int remaining; //remaining bytes to read for the current message - struct socket_s *prev, *next; //prev and next socket in a list -} socket_t; - -//compare addresses -int Net_AddressCompare( address_t *addr1, address_t *addr2 ); -//gives the address of a socket -void Net_SocketToAddress( socket_t *sock, address_t *address ); -//converts a string to an address -void Net_StringToAddress( char *string, address_t *address ); -//set the address ip port -void Net_SetAddressPort( address_t *address, int port ); -//send a message to the given socket -int Net_Send( socket_t *sock, netmessage_t *msg ); -//recieve a message from the given socket -int Net_Receive( socket_t *sock, netmessage_t *msg ); -//connect to a host -// NOTE: port is the localhost port, usually 0 -// ex: Net_Connect( "192.168.0.1:39000", 0 ) -socket_t *Net_Connect( address_t *address, int port ); -//disconnect from a host -void Net_Disconnect( socket_t *sock ); -//returns the local address -void Net_MyAddress( address_t *address ); -//listen at the given port -socket_t *Net_ListenSocket( int port ); -//accept new connections at the given socket -socket_t *Net_Accept( socket_t *sock ); -//setup networking -int Net_Setup( void ); -//shutdown networking -void Net_Shutdown( void ); -//message handling -void NMSG_Clear( netmessage_t *msg ); -void NMSG_WriteChar( netmessage_t *msg, int c ); -void NMSG_WriteByte( netmessage_t *msg, int c ); -void NMSG_WriteShort( netmessage_t *msg, int c ); -void NMSG_WriteLong( netmessage_t *msg, int c ); -void NMSG_WriteFloat( netmessage_t *msg, float c ); -void NMSG_WriteString( netmessage_t *msg, char *string ); -void NMSG_ReadStart( netmessage_t *msg ); -int NMSG_ReadChar( netmessage_t *msg ); -int NMSG_ReadByte( netmessage_t *msg ); -int NMSG_ReadShort( netmessage_t *msg ); -int NMSG_ReadLong( netmessage_t *msg ); -float NMSG_ReadFloat( netmessage_t *msg ); -char *NMSG_ReadString( netmessage_t *msg ); - -//++timo FIXME: the WINS_ things are not necessary, they can be made portable arther easily -char *WINS_ErrorMessage( int error ); - -#ifdef __cplusplus -} -#endif diff --git a/tools/urt/libs/l_net/l_net.vcproj b/tools/urt/libs/l_net/l_net.vcproj deleted file mode 100644 index e9d1c47..0000000 --- a/tools/urt/libs/l_net/l_net.vcproj +++ /dev/null @@ -1,230 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/tools/urt/libs/l_net/l_net_berkley.c b/tools/urt/libs/l_net/l_net_berkley.c deleted file mode 100644 index 79d1c48..0000000 --- a/tools/urt/libs/l_net/l_net_berkley.c +++ /dev/null @@ -1,744 +0,0 @@ -/* - Copyright (C) 1999-2007 id Software, Inc. and contributors. - For a list of contributors, see the accompanying CONTRIBUTORS file. - - This file is part of GtkRadiant. - - GtkRadiant is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - GtkRadiant is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with GtkRadiant; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - */ - -//=========================================================================== -// -// Name: l_net_wins.c -// Function: WinSock -// Programmer: MrElusive -// Last update: TTimo: cross-platform version, l_net library -// Tab Size: 2 -// Notes: -//=========================================================================== - -//#include -#include -#include -#include -#include "l_net.h" -#include "l_net_wins.h" - -#include -#include -#include -#include -#include -#include -#include -#define SOCKET_ERROR -1 -#define INVALID_SOCKET -1 - -#define WinError WinPrint - -#define qtrue 1 -#define qfalse 0 - -#define ioctlsocket ioctl -#define closesocket close - -int WSAGetLastError(){ - return errno; -} - -/* - typedef struct tag_error_struct - { - int errnum; - LPSTR errstr; - } ERROR_STRUCT; - */ - -typedef struct tag_error_struct -{ - int errnum; - const char *errstr; -} ERROR_STRUCT; - -#define NET_NAMELEN 64 - -static char my_tcpip_address[NET_NAMELEN]; - -#define DEFAULTnet_hostport 26000 - -#define MAXHOSTNAMELEN 256 - -static int net_acceptsocket = -1; // socket for fielding new connections -static int net_controlsocket; -static int net_hostport; // udp port number for acceptsocket -static int net_broadcastsocket = 0; -//static qboolean ifbcastinit = qfalse; -//static struct sockaddr_s broadcastaddr; -static struct sockaddr_s broadcastaddr; - -static unsigned long myAddr; - -ERROR_STRUCT errlist[] = { - {EACCES,"EACCES - The address is protected, user is not root"}, - {EAGAIN,"EAGAIN - Operation on non-blocking socket that cannot return immediatly"}, - {EBADF, "EBADF - sockfd is not a valid descriptor"}, - {EFAULT, "EFAULT - The parameter is not in a writable part of the user address space"}, - {EINVAL,"EINVAL - The socket is already bound to an address"}, - {ENOBUFS,"ENOBUFS - not enough memory"}, - {ENOMEM, "ENOMEM - not enough memory"}, - {ENOTCONN, "ENOTCONN - not connected"}, - {ENOTSOCK,"ENOTSOCK - Argument is file descriptor not a socket"}, - {EOPNOTSUPP,"ENOTSUPP - The referenced socket is not of type SOCK_STREAM"}, - {EPERM, "EPERM - Firewall rules forbid connection"}, - {-1, NULL} -}; - -//=========================================================================== -// -// Parameter: - -// Returns: - -// Changes Globals: - -//=========================================================================== -char *WINS_ErrorMessage( int error ){ - int search = 0; - - if ( !error ) { - return "No error occurred"; - } - - for ( search = 0; errlist[search].errstr; search++ ) - { - if ( error == errlist[search].errnum ) { - return (char *)errlist[search].errstr; - } - } //end for - - return "Unknown error"; -} //end of the function WINS_ErrorMessage -//=========================================================================== -// -// Parameter: - -// Returns: - -// Changes Globals: - -//=========================================================================== -int WINS_Init( void ){ - int i; - struct hostent *local; - char buff[MAXHOSTNAMELEN]; - struct sockaddr_s addr; - char *p; - int r; -/* - linux doesn't have anything to initialize for the net - "Windows .. built for the internet .. the internet .. built with unix" - */ -#if 0 - WORD wVersionRequested; - - wVersionRequested = MAKEWORD( 2, 2 ); - - r = WSAStartup( wVersionRequested, &winsockdata ); - - if ( r ) { - WinPrint( "Winsock initialization failed.\n" ); - return -1; - } -#endif - /* - i = COM_CheckParm ("-udpport"); - if (i == 0)*/ - net_hostport = DEFAULTnet_hostport; - /* - else if (i < com_argc-1) - net_hostport = Q_atoi (com_argv[i+1]); - else - Sys_Error ("WINS_Init: you must specify a number after -udpport"); - */ - - // determine my name & address - gethostname( buff, MAXHOSTNAMELEN ); - local = gethostbyname( buff ); - myAddr = *(int *)local->h_addr_list[0]; - - // if the quake hostname isn't set, set it to the machine name -// if (Q_strcmp(hostname.string, "UNNAMED") == 0) - { - // see if it's a text IP address (well, close enough) - for ( p = buff; *p; p++ ) - if ( ( *p < '0' || *p > '9' ) && *p != '.' ) { - break; - } - - // if it is a real name, strip off the domain; we only want the host - if ( *p ) { - for ( i = 0; i < 15; i++ ) - if ( buff[i] == '.' ) { - break; - } - buff[i] = 0; - } -// Cvar_Set ("hostname", buff); - } - - //++timo WTF is that net_controlsocket? it's sole purpose is to retrieve the local IP? - if ( ( net_controlsocket = WINS_OpenSocket( 0 ) ) == SOCKET_ERROR ) { - WinError( "WINS_Init: Unable to open control socket\n" ); - } - - ( (struct sockaddr_in *)&broadcastaddr )->sin_family = AF_INET; - ( (struct sockaddr_in *)&broadcastaddr )->sin_addr.s_addr = INADDR_BROADCAST; - ( (struct sockaddr_in *)&broadcastaddr )->sin_port = htons( (u_short)net_hostport ); - - WINS_GetSocketAddr( net_controlsocket, &addr ); - strcpy( my_tcpip_address, WINS_AddrToString( &addr ) ); - p = strrchr( my_tcpip_address, ':' ); - if ( p ) { - *p = 0; - } - WinPrint( "Winsock Initialized\n" ); - - return net_controlsocket; -} //end of the function WINS_Init -//=========================================================================== -// -// Parameter: - -// Returns: - -// Changes Globals: - -//=========================================================================== -char *WINS_MyAddress( void ){ - return my_tcpip_address; -} //end of the function WINS_MyAddress -//=========================================================================== -// -// Parameter: - -// Returns: - -// Changes Globals: - -//=========================================================================== -void WINS_Shutdown( void ){ - //WINS_Listen(0); - WINS_CloseSocket( net_controlsocket ); -// WSACleanup(); - // - //WinPrint("Winsock Shutdown\n"); -} //end of the function WINS_Shutdown -//=========================================================================== -// -// Parameter: - -// Returns: - -// Changes Globals: - -//=========================================================================== -/* - void WINS_Listen(int state) - { - // enable listening - if (state) - { - if (net_acceptsocket != -1) - return; - if ((net_acceptsocket = WINS_OpenSocket (net_hostport)) == -1) - WinError ("WINS_Listen: Unable to open accept socket\n"); - return; - } - - // disable listening - if (net_acceptsocket == -1) - return; - WINS_CloseSocket (net_acceptsocket); - net_acceptsocket = -1; - } //end of the function WINS_Listen*/ -//=========================================================================== -// -// Parameter: - -// Returns: - -// Changes Globals: - -//=========================================================================== -int WINS_OpenSocket( int port ){ - int newsocket; - struct sockaddr_in address; - u_long _true = 1; - - if ( ( newsocket = socket( PF_INET, SOCK_DGRAM, IPPROTO_UDP ) ) == SOCKET_ERROR ) { - WinPrint( "WINS_OpenSocket: %s\n", WINS_ErrorMessage( WSAGetLastError() ) ); - return -1; - } //end if - - if ( ioctlsocket( newsocket, FIONBIO, &_true ) == SOCKET_ERROR ) { - WinPrint( "WINS_OpenSocket: %s\n", WINS_ErrorMessage( WSAGetLastError() ) ); - closesocket( newsocket ); - return -1; - } //end if - - memset( (char *) &address, 0, sizeof( address ) ); - address.sin_family = AF_INET; - address.sin_addr.s_addr = INADDR_ANY; - address.sin_port = htons( (u_short)port ); - if ( bind( newsocket, (void *)&address, sizeof( address ) ) == -1 ) { - WinPrint( "WINS_OpenSocket: %s\n", WINS_ErrorMessage( WSAGetLastError() ) ); - closesocket( newsocket ); - return -1; - } //end if - - return newsocket; -} //end of the function WINS_OpenSocket -//=========================================================================== -// -// Parameter: - -// Returns: - -// Changes Globals: - -//=========================================================================== -int WINS_OpenReliableSocket( int port ){ - int newsocket; - struct sockaddr_in address; - qboolean _true = 0xFFFFFFFF; - - //IPPROTO_TCP - // - if ( ( newsocket = socket( AF_INET, SOCK_STREAM, 0 ) ) == -1 ) { - WinPrint( "WINS_OpenReliableSocket: %s\n", WINS_ErrorMessage( WSAGetLastError() ) ); - return -1; - } //end if - - memset( (char *) &address, 0, sizeof( address ) ); - address.sin_family = AF_INET; - address.sin_addr.s_addr = htonl( INADDR_ANY ); - address.sin_port = htons( (u_short)port ); - if ( bind( newsocket, (void *)&address, sizeof( address ) ) == -1 ) { - WinPrint( "WINS_OpenReliableSocket: %s\n", WINS_ErrorMessage( WSAGetLastError() ) ); - closesocket( newsocket ); - return -1; - } //end if - - // - if ( setsockopt( newsocket, IPPROTO_TCP, TCP_NODELAY, (void *) &_true, sizeof( int ) ) == -1 ) { - WinPrint( "WINS_OpenReliableSocket: %s\n", WINS_ErrorMessage( WSAGetLastError() ) ); - WinPrint( "setsockopt error\n" ); - } //end if - - return newsocket; -} //end of the function WINS_OpenReliableSocket -//=========================================================================== -// -// Parameter: - -// Returns: - -// Changes Globals: - -//=========================================================================== -int WINS_Listen( int socket ){ - u_long _true = 1; - - if ( ioctlsocket( socket, FIONBIO, &_true ) == -1 ) { - WinPrint( "WINS_Listen: %s\n", WINS_ErrorMessage( WSAGetLastError() ) ); - return -1; - } //end if - if ( listen( socket, SOMAXCONN ) == SOCKET_ERROR ) { - WinPrint( "WINS_Listen: %s\n", WINS_ErrorMessage( WSAGetLastError() ) ); - return -1; - } //end if - return 0; -} //end of the function WINS_Listen -//=========================================================================== -// -// Parameter: - -// Returns: - -// Changes Globals: - -//=========================================================================== -int WINS_Accept( int socket, struct sockaddr_s *addr ){ - int addrlen = sizeof( struct sockaddr_s ); - int newsocket; - qboolean _true = 1; - - newsocket = accept( socket, (struct sockaddr *)addr, &addrlen ); - if ( newsocket == INVALID_SOCKET ) { - if ( errno == EAGAIN ) { - return -1; - } - WinPrint( "WINS_Accept: %s\n", WINS_ErrorMessage( WSAGetLastError() ) ); - return -1; - } //end if - // - if ( setsockopt( newsocket, IPPROTO_TCP, TCP_NODELAY, (void *) &_true, sizeof( int ) ) == SOCKET_ERROR ) { - WinPrint( "WINS_Accept: %s\n", WINS_ErrorMessage( WSAGetLastError() ) ); - WinPrint( "setsockopt error\n" ); - } //end if - return newsocket; -} //end of the function WINS_Accept -//=========================================================================== -// -// Parameter: - -// Returns: - -// Changes Globals: - -//=========================================================================== -int WINS_CloseSocket( int socket ){ - /* - if (socket == net_broadcastsocket) - net_broadcastsocket = 0; - */ -// shutdown(socket, SD_SEND); - - if ( closesocket( socket ) == SOCKET_ERROR ) { - WinPrint( "WINS_CloseSocket: %s\n", WINS_ErrorMessage( WSAGetLastError() ) ); - return SOCKET_ERROR; - } //end if - return 0; -} //end of the function WINS_CloseSocket -//=========================================================================== -// this lets you type only as much of the net address as required, using -// the local network components to fill in the rest -// -// Parameter: - -// Returns: - -// Changes Globals: - -//=========================================================================== -static int PartialIPAddress( char *in, struct sockaddr_s *hostaddr ){ - char buff[256]; - char *b; - int addr; - int num; - int mask; - - buff[0] = '.'; - b = buff; - strcpy( buff + 1, in ); - if ( buff[1] == '.' ) { - b++; - } - - addr = 0; - mask = -1; - while ( *b == '.' ) - { - num = 0; - if ( *++b < '0' || *b > '9' ) { - return -1; - } - while ( !( *b < '0' || *b > '9' ) ) - num = num * 10 + *( b++ ) - '0'; - mask <<= 8; - addr = ( addr << 8 ) + num; - } - - hostaddr->sa_family = AF_INET; - ( (struct sockaddr_in *)hostaddr )->sin_port = htons( (u_short)net_hostport ); - ( (struct sockaddr_in *)hostaddr )->sin_addr.s_addr = ( myAddr & htonl( mask ) ) | htonl( addr ); - - return 0; -} //end of the function PartialIPAddress -//=========================================================================== -// -// Parameter: - -// Returns: - -// Changes Globals: - -//=========================================================================== -int WINS_Connect( int socket, struct sockaddr_s *addr ){ - int ret; - u_long _true2 = 0xFFFFFFFF; - - ret = connect( socket, (struct sockaddr *)addr, sizeof( struct sockaddr_s ) ); - if ( ret == SOCKET_ERROR ) { - WinPrint( "WINS_Connect: %s\n", WINS_ErrorMessage( WSAGetLastError() ) ); - return -1; - } //end if - if ( ioctlsocket( socket, FIONBIO, &_true2 ) == -1 ) { - WinPrint( "WINS_Connect: %s\n", WINS_ErrorMessage( WSAGetLastError() ) ); - return -1; - } //end if - return 0; -} //end of the function WINS_Connect -//=========================================================================== -// -// Parameter: - -// Returns: - -// Changes Globals: - -//=========================================================================== -int WINS_CheckNewConnections( void ){ - char buf[4]; - - if ( net_acceptsocket == -1 ) { - return -1; - } - - if ( recvfrom( net_acceptsocket, buf, 4, MSG_PEEK, NULL, NULL ) > 0 ) { - return net_acceptsocket; - } - return -1; -} //end of the function WINS_CheckNewConnections -//=========================================================================== -// returns the number of bytes read -// 0 if no bytes available -// -1 on failure -// -// Parameter: - -// Returns: - -// Changes Globals: - -//=========================================================================== -int WINS_Read( int socket, byte *buf, int len, struct sockaddr_s *addr ){ - int addrlen = sizeof( struct sockaddr_s ); - int ret; - - if ( addr ) { - ret = recvfrom( socket, buf, len, 0, (struct sockaddr *)addr, &addrlen ); - if ( ret == -1 ) { -// errno = WSAGetLastError(); - - if ( errno == EAGAIN || errno == ENOTCONN ) { - return 0; - } - } //end if - } //end if - else - { - ret = recv( socket, buf, len, 0 ); - // if there's no data on the socket ret == -1 and errno == EAGAIN - // MSDN states that if ret == 0 the socket has been closed - // man recv doesn't say anything - if ( ret == 0 ) { - return -1; - } - if ( ret == SOCKET_ERROR ) { -// errno = WSAGetLastError(); - - if ( errno == EAGAIN || errno == ENOTCONN ) { - return 0; - } - } //end if - } //end else - if ( ret == SOCKET_ERROR ) { - WinPrint( "WINS_Read: %s\n", WINS_ErrorMessage( WSAGetLastError() ) ); - } //end if - return ret; -} //end of the function WINS_Read -//=========================================================================== -// -// Parameter: - -// Returns: - -// Changes Globals: - -//=========================================================================== -int WINS_MakeSocketBroadcastCapable( int socket ){ - int i = 1; - - // make this socket broadcast capable - if ( setsockopt( socket, SOL_SOCKET, SO_BROADCAST, (char *)&i, sizeof( i ) ) < 0 ) { - return -1; - } - net_broadcastsocket = socket; - - return 0; -} //end of the function WINS_MakeSocketBroadcastCapable -//=========================================================================== -// -// Parameter: - -// Returns: - -// Changes Globals: - -//=========================================================================== -int WINS_Broadcast( int socket, byte *buf, int len ){ - int ret; - - if ( socket != net_broadcastsocket ) { - if ( net_broadcastsocket != 0 ) { - WinError( "Attempted to use multiple broadcasts sockets\n" ); - } - ret = WINS_MakeSocketBroadcastCapable( socket ); - if ( ret == -1 ) { - WinPrint( "Unable to make socket broadcast capable\n" ); - return ret; - } - } - - return WINS_Write( socket, buf, len, &broadcastaddr ); -} //end of the function WINS_Broadcast -//=========================================================================== -// returns qtrue on success or qfalse on failure -// -// Parameter: - -// Returns: - -// Changes Globals: - -//=========================================================================== -int WINS_Write( int socket, byte *buf, int len, struct sockaddr_s *addr ){ - int ret, written; - - if ( addr ) { - written = 0; - while ( written < len ) - { - ret = sendto( socket, &buf[written], len - written, 0, (struct sockaddr *)addr, sizeof( struct sockaddr_s ) ); - if ( ret == SOCKET_ERROR ) { - if ( WSAGetLastError() != EAGAIN ) { - return qfalse; - } - //++timo FIXME: what is this used for? -// Sleep(1000); - } //end if - else - { - written += ret; - } - } - } //end if - else - { - written = 0; - while ( written < len ) - { - ret = send( socket, buf, len, 0 ); - if ( ret == SOCKET_ERROR ) { - if ( WSAGetLastError() != EAGAIN ) { - return qfalse; - } - //++timo FIXME: what is this used for? -// Sleep(1000); - } //end if - else - { - written += ret; - } - } - } //end else - if ( ret == SOCKET_ERROR ) { - WinPrint( "WINS_Write: %s\n", WINS_ErrorMessage( WSAGetLastError() ) ); - } //end if - return ( ret == len ); -} //end of the function WINS_Write -//=========================================================================== -// -// Parameter: - -// Returns: - -// Changes Globals: - -//=========================================================================== -char *WINS_AddrToString( struct sockaddr_s *addr ){ - static char buffer[22]; - int haddr; - - haddr = ntohl( ( (struct sockaddr_in *)addr )->sin_addr.s_addr ); - sprintf( buffer, "%d.%d.%d.%d:%d", ( haddr >> 24 ) & 0xff, ( haddr >> 16 ) & 0xff, ( haddr >> 8 ) & 0xff, haddr & 0xff, ntohs( ( (struct sockaddr_in *)addr )->sin_port ) ); - return buffer; -} //end of the function WINS_AddrToString -//=========================================================================== -// -// Parameter: - -// Returns: - -// Changes Globals: - -//=========================================================================== -int WINS_StringToAddr( char *string, struct sockaddr_s *addr ){ - int ha1, ha2, ha3, ha4, hp; - int ipaddr; - - sscanf( string, "%d.%d.%d.%d:%d", &ha1, &ha2, &ha3, &ha4, &hp ); - ipaddr = ( ha1 << 24 ) | ( ha2 << 16 ) | ( ha3 << 8 ) | ha4; - - addr->sa_family = AF_INET; - ( (struct sockaddr_in *)addr )->sin_addr.s_addr = htonl( ipaddr ); - ( (struct sockaddr_in *)addr )->sin_port = htons( (u_short)hp ); - return 0; -} //end of the function WINS_StringToAddr -//=========================================================================== -// -// Parameter: - -// Returns: - -// Changes Globals: - -//=========================================================================== -int WINS_GetSocketAddr( int socket, struct sockaddr_s *addr ){ - int addrlen = sizeof( struct sockaddr_s ); - unsigned int a; - - memset( addr, 0, sizeof( struct sockaddr_s ) ); - getsockname( socket, (struct sockaddr *)addr, &addrlen ); - a = ( (struct sockaddr_in *)addr )->sin_addr.s_addr; - if ( a == 0 || a == inet_addr( "127.0.0.1" ) ) { - ( (struct sockaddr_in *)addr )->sin_addr.s_addr = myAddr; - } - - return 0; -} //end of the function WINS_GetSocketAddr -//=========================================================================== -// -// Parameter: - -// Returns: - -// Changes Globals: - -//=========================================================================== -int WINS_GetNameFromAddr( struct sockaddr_s *addr, char *name ){ - struct hostent *hostentry; - - hostentry = gethostbyaddr( (char *)&( (struct sockaddr_in *)addr )->sin_addr, sizeof( struct in_addr ), AF_INET ); - if ( hostentry ) { - strncpy( name, (char *)hostentry->h_name, NET_NAMELEN - 1 ); - return 0; - } - - strcpy( name, WINS_AddrToString( addr ) ); - return 0; -} //end of the function WINS_GetNameFromAddr -//=========================================================================== -// -// Parameter: - -// Returns: - -// Changes Globals: - -//=========================================================================== -int WINS_GetAddrFromName( char *name, struct sockaddr_s *addr ){ - struct hostent *hostentry; - - if ( name[0] >= '0' && name[0] <= '9' ) { - return PartialIPAddress( name, addr ); - } - - hostentry = gethostbyname( name ); - if ( !hostentry ) { - return -1; - } - - addr->sa_family = AF_INET; - ( (struct sockaddr_in *)addr )->sin_port = htons( (u_short)net_hostport ); - ( (struct sockaddr_in *)addr )->sin_addr.s_addr = *(int *)hostentry->h_addr_list[0]; - - return 0; -} //end of the function WINS_GetAddrFromName -//=========================================================================== -// -// Parameter: - -// Returns: - -// Changes Globals: - -//=========================================================================== -int WINS_AddrCompare( struct sockaddr_s *addr1, struct sockaddr_s *addr2 ){ - if ( addr1->sa_family != addr2->sa_family ) { - return -1; - } - - if ( ( (struct sockaddr_in *)addr1 )->sin_addr.s_addr != ( (struct sockaddr_in *)addr2 )->sin_addr.s_addr ) { - return -1; - } - - if ( ( (struct sockaddr_in *)addr1 )->sin_port != ( (struct sockaddr_in *)addr2 )->sin_port ) { - return 1; - } - - return 0; -} //end of the function WINS_AddrCompare -//=========================================================================== -// -// Parameter: - -// Returns: - -// Changes Globals: - -//=========================================================================== -int WINS_GetSocketPort( struct sockaddr_s *addr ){ - return ntohs( ( (struct sockaddr_in *)addr )->sin_port ); -} //end of the function WINS_GetSocketPort -//=========================================================================== -// -// Parameter: - -// Returns: - -// Changes Globals: - -//=========================================================================== -int WINS_SetSocketPort( struct sockaddr_s *addr, int port ){ - ( (struct sockaddr_in *)addr )->sin_port = htons( (u_short)port ); - return 0; -} //end of the function WINS_SetSocketPort diff --git a/tools/urt/libs/l_net/l_net_wins.c b/tools/urt/libs/l_net/l_net_wins.c deleted file mode 100644 index 5ba90fa..0000000 --- a/tools/urt/libs/l_net/l_net_wins.c +++ /dev/null @@ -1,767 +0,0 @@ -/* - Copyright (C) 1999-2007 id Software, Inc. and contributors. - For a list of contributors, see the accompanying CONTRIBUTORS file. - - This file is part of GtkRadiant. - - GtkRadiant is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - GtkRadiant is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with GtkRadiant; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - */ - -//=========================================================================== -// -// Name: l_net_wins.c -// Function: WinSock -// Programmer: MrElusive -// Last update: - -// Tab Size: 3 -// Notes: -//=========================================================================== - -#include -#include -#include -#include -#include "l_net.h" -#include "l_net_wins.h" -//#include -//#include "mpdosock.h" - -#define WinError WinPrint - -#define qtrue 1 -#define qfalse 0 - -typedef struct tag_error_struct -{ - int errnum; - LPSTR errstr; -} ERROR_STRUCT; - -#define NET_NAMELEN 64 - -char my_tcpip_address[NET_NAMELEN]; - -#define DEFAULTnet_hostport 26000 - -#define MAXHOSTNAMELEN 256 - -static int net_acceptsocket = -1; // socket for fielding new connections -static int net_controlsocket; -static int net_hostport; // udp port number for acceptsocket -static int net_broadcastsocket = 0; -//static qboolean ifbcastinit = qfalse; -static struct sockaddr_s broadcastaddr; - -static unsigned long myAddr; - -WSADATA winsockdata; - -ERROR_STRUCT errlist[] = { - {WSAEINTR, "WSAEINTR - Interrupted"}, - {WSAEBADF, "WSAEBADF - Bad file number"}, - {WSAEFAULT, "WSAEFAULT - Bad address"}, - {WSAEINVAL, "WSAEINVAL - Invalid argument"}, - {WSAEMFILE, "WSAEMFILE - Too many open files"}, - -/* - * Windows Sockets definitions of regular Berkeley error constants - */ - - {WSAEWOULDBLOCK, "WSAEWOULDBLOCK - Socket marked as non-blocking"}, - {WSAEINPROGRESS, "WSAEINPROGRESS - Blocking call in progress"}, - {WSAEALREADY, "WSAEALREADY - Command already completed"}, - {WSAENOTSOCK, "WSAENOTSOCK - Descriptor is not a socket"}, - {WSAEDESTADDRREQ, "WSAEDESTADDRREQ - Destination address required"}, - {WSAEMSGSIZE, "WSAEMSGSIZE - Data size too large"}, - {WSAEPROTOTYPE, "WSAEPROTOTYPE - Protocol is of wrong type for this socket"}, - {WSAENOPROTOOPT, "WSAENOPROTOOPT - Protocol option not supported for this socket type"}, - {WSAEPROTONOSUPPORT, "WSAEPROTONOSUPPORT - Protocol is not supported"}, - {WSAESOCKTNOSUPPORT, "WSAESOCKTNOSUPPORT - Socket type not supported by this address family"}, - {WSAEOPNOTSUPP, "WSAEOPNOTSUPP - Option not supported"}, - {WSAEPFNOSUPPORT, "WSAEPFNOSUPPORT - "}, - {WSAEAFNOSUPPORT, "WSAEAFNOSUPPORT - Address family not supported by this protocol"}, - {WSAEADDRINUSE, "WSAEADDRINUSE - Address is in use"}, - {WSAEADDRNOTAVAIL, "WSAEADDRNOTAVAIL - Address not available from local machine"}, - {WSAENETDOWN, "WSAENETDOWN - Network subsystem is down"}, - {WSAENETUNREACH, "WSAENETUNREACH - Network cannot be reached"}, - {WSAENETRESET, "WSAENETRESET - Connection has been dropped"}, - {WSAECONNABORTED, "WSAECONNABORTED - Connection aborted"}, - {WSAECONNRESET, "WSAECONNRESET - Connection reset"}, - {WSAENOBUFS, "WSAENOBUFS - No buffer space available"}, - {WSAEISCONN, "WSAEISCONN - Socket is already connected"}, - {WSAENOTCONN, "WSAENOTCONN - Socket is not connected"}, - {WSAESHUTDOWN, "WSAESHUTDOWN - Socket has been shut down"}, - {WSAETOOMANYREFS, "WSAETOOMANYREFS - Too many references"}, - {WSAETIMEDOUT, "WSAETIMEDOUT - Command timed out"}, - {WSAECONNREFUSED, "WSAECONNREFUSED - Connection refused"}, - {WSAELOOP, "WSAELOOP - "}, - {WSAENAMETOOLONG, "WSAENAMETOOLONG - "}, - {WSAEHOSTDOWN, "WSAEHOSTDOWN - Host is down"}, - {WSAEHOSTUNREACH, "WSAEHOSTUNREACH - "}, - {WSAENOTEMPTY, "WSAENOTEMPTY - "}, - {WSAEPROCLIM, "WSAEPROCLIM - "}, - {WSAEUSERS, "WSAEUSERS - "}, - {WSAEDQUOT, "WSAEDQUOT - "}, - {WSAESTALE, "WSAESTALE - "}, - {WSAEREMOTE, "WSAEREMOTE - "}, - -/* - * Extended Windows Sockets error constant definitions - */ - - {WSASYSNOTREADY, "WSASYSNOTREADY - Network subsystem not ready"}, - {WSAVERNOTSUPPORTED, "WSAVERNOTSUPPORTED - Version not supported"}, - {WSANOTINITIALISED, "WSANOTINITIALISED - WSAStartup() has not been successfully called"}, - -/* - * Other error constants. - */ - - {WSAHOST_NOT_FOUND, "WSAHOST_NOT_FOUND - Host not found"}, - {WSATRY_AGAIN, "WSATRY_AGAIN - Host not found or SERVERFAIL"}, - {WSANO_RECOVERY, "WSANO_RECOVERY - Non-recoverable error"}, - {WSANO_DATA, "WSANO_DATA - (or WSANO_ADDRESS) - No data record of requested type"}, - {-1, NULL} -}; - -#ifdef _DEBUG -void WinPrint( char *str, ... ); -#else -void WinPrint( char *str, ... ); -#endif - -//=========================================================================== -// -// Parameter: - -// Returns: - -// Changes Globals: - -//=========================================================================== -char *WINS_ErrorMessage( int error ){ - int search = 0; - - if ( !error ) { - return "No error occurred"; - } - - for ( search = 0; errlist[search].errstr; search++ ) - { - if ( error == errlist[search].errnum ) { - return errlist[search].errstr; - } - } //end for - - return "Unknown error"; -} //end of the function WINS_ErrorMessage -//=========================================================================== -// -// Parameter: - -// Returns: - -// Changes Globals: - -//=========================================================================== -int WINS_Init( void ){ - int i; - struct hostent *local; - char buff[MAXHOSTNAMELEN]; - struct sockaddr_s addr; - char *p; - int r; - WORD wVersionRequested; - - wVersionRequested = MAKEWORD( 1, 1 ); - - r = WSAStartup( wVersionRequested, &winsockdata ); - - if ( r ) { - WinPrint( "Winsock initialization failed.\n" ); - return -1; - } - - /* - i = COM_CheckParm ("-udpport"); - if (i == 0)*/ - net_hostport = DEFAULTnet_hostport; - /* - else if (i < com_argc-1) - net_hostport = Q_atoi (com_argv[i+1]); - else - Sys_Error ("WINS_Init: you must specify a number after -udpport"); - */ - - // determine my name & address - gethostname( buff, MAXHOSTNAMELEN ); - local = gethostbyname( buff ); - myAddr = *(int *)local->h_addr_list[0]; - - // if the quake hostname isn't set, set it to the machine name -// if (Q_strcmp(hostname.string, "UNNAMED") == 0) - { - // see if it's a text IP address (well, close enough) - for ( p = buff; *p; p++ ) - if ( ( *p < '0' || *p > '9' ) && *p != '.' ) { - break; - } - - // if it is a real name, strip off the domain; we only want the host - if ( *p ) { - for ( i = 0; i < 15; i++ ) - if ( buff[i] == '.' ) { - break; - } - buff[i] = 0; - } -// Cvar_Set ("hostname", buff); - } - - if ( ( net_controlsocket = WINS_OpenSocket( 0 ) ) == -1 ) { - WinError( "WINS_Init: Unable to open control socket\n" ); - } - - ( (struct sockaddr_in *)&broadcastaddr )->sin_family = AF_INET; - ( (struct sockaddr_in *)&broadcastaddr )->sin_addr.s_addr = INADDR_BROADCAST; - ( (struct sockaddr_in *)&broadcastaddr )->sin_port = htons( (u_short)net_hostport ); - - WINS_GetSocketAddr( net_controlsocket, &addr ); - strcpy( my_tcpip_address, WINS_AddrToString( &addr ) ); - p = strrchr( my_tcpip_address, ':' ); - if ( p ) { - *p = 0; - } - WinPrint( "Winsock Initialized\n" ); - - return net_controlsocket; -} //end of the function WINS_Init -//=========================================================================== -// -// Parameter: - -// Returns: - -// Changes Globals: - -//=========================================================================== -char *WINS_MyAddress( void ){ - return my_tcpip_address; -} //end of the function WINS_MyAddress -//=========================================================================== -// -// Parameter: - -// Returns: - -// Changes Globals: - -//=========================================================================== -void WINS_Shutdown( void ){ - //WINS_Listen(0); - WINS_CloseSocket( net_controlsocket ); - WSACleanup(); - // - //WinPrint("Winsock Shutdown\n"); -} //end of the function WINS_Shutdown -//=========================================================================== -// -// Parameter: - -// Returns: - -// Changes Globals: - -//=========================================================================== -/* - void WINS_Listen(int state) - { - // enable listening - if (state) - { - if (net_acceptsocket != -1) - return; - if ((net_acceptsocket = WINS_OpenSocket (net_hostport)) == -1) - WinError ("WINS_Listen: Unable to open accept socket\n"); - return; - } - - // disable listening - if (net_acceptsocket == -1) - return; - WINS_CloseSocket (net_acceptsocket); - net_acceptsocket = -1; - } //end of the function WINS_Listen*/ -//=========================================================================== -// -// Parameter: - -// Returns: - -// Changes Globals: - -//=========================================================================== -int WINS_OpenSocket( int port ){ - int newsocket; - struct sockaddr_in address; - u_long _true = 1; - - if ( ( newsocket = socket( PF_INET, SOCK_DGRAM, IPPROTO_UDP ) ) == -1 ) { - WinPrint( "WINS_OpenSocket: %s\n", WINS_ErrorMessage( WSAGetLastError() ) ); - return -1; - } //end if - - if ( ioctlsocket( newsocket, FIONBIO, &_true ) == -1 ) { - WinPrint( "WINS_OpenSocket: %s\n", WINS_ErrorMessage( WSAGetLastError() ) ); - closesocket( newsocket ); - return -1; - } //end if - - memset( (char *) &address, 0, sizeof( address ) ); - address.sin_family = AF_INET; - address.sin_addr.s_addr = INADDR_ANY; - address.sin_port = htons( (u_short)port ); - if ( bind( newsocket, (void *)&address, sizeof( address ) ) == -1 ) { - WinPrint( "WINS_OpenSocket: %s\n", WINS_ErrorMessage( WSAGetLastError() ) ); - closesocket( newsocket ); - return -1; - } //end if - - return newsocket; -} //end of the function WINS_OpenSocket -//=========================================================================== -// -// Parameter: - -// Returns: - -// Changes Globals: - -//=========================================================================== -int WINS_OpenReliableSocket( int port ){ - int newsocket; - struct sockaddr_in address; - BOOL _true = 0xFFFFFFFF; - - //IPPROTO_TCP - // - if ( ( newsocket = socket( AF_INET, SOCK_STREAM, 0 ) ) == -1 ) { - WinPrint( "WINS_OpenReliableSocket: %s\n", WINS_ErrorMessage( WSAGetLastError() ) ); - return -1; - } //end if - - memset( (char *) &address, 0, sizeof( address ) ); - address.sin_family = AF_INET; - address.sin_addr.s_addr = htonl( INADDR_ANY ); - address.sin_port = htons( (u_short)port ); - if ( bind( newsocket, (void *)&address, sizeof( address ) ) == -1 ) { - WinPrint( "WINS_OpenReliableSocket: %s\n", WINS_ErrorMessage( WSAGetLastError() ) ); - closesocket( newsocket ); - return -1; - } //end if - - // - if ( setsockopt( newsocket, IPPROTO_TCP, TCP_NODELAY, (void *) &_true, sizeof( int ) ) == SOCKET_ERROR ) { - WinPrint( "WINS_OpenReliableSocket: %s\n", WINS_ErrorMessage( WSAGetLastError() ) ); - WinPrint( "setsockopt error\n" ); - } //end if - - return newsocket; -} //end of the function WINS_OpenReliableSocket -//=========================================================================== -// -// Parameter: - -// Returns: - -// Changes Globals: - -//=========================================================================== -int WINS_Listen( int socket ){ - u_long _true = 1; - - if ( ioctlsocket( socket, FIONBIO, &_true ) == -1 ) { - WinPrint( "WINS_Listen: %s\n", WINS_ErrorMessage( WSAGetLastError() ) ); - return -1; - } //end if - if ( listen( socket, SOMAXCONN ) == SOCKET_ERROR ) { - WinPrint( "WINS_Listen: %s\n", WINS_ErrorMessage( WSAGetLastError() ) ); - return -1; - } //end if - return 0; -} //end of the function WINS_Listen -//=========================================================================== -// -// Parameter: - -// Returns: - -// Changes Globals: - -//=========================================================================== -int WINS_Accept( int socket, struct sockaddr_s *addr ){ - int addrlen = sizeof( struct sockaddr_s ); - int newsocket; - BOOL _true = 1; - - newsocket = accept( socket, (struct sockaddr *)addr, &addrlen ); - if ( newsocket == INVALID_SOCKET ) { - if ( WSAGetLastError() == WSAEWOULDBLOCK ) { - return -1; - } - WinPrint( "WINS_Accept: %s\n", WINS_ErrorMessage( WSAGetLastError() ) ); - return -1; - } //end if - // - if ( setsockopt( newsocket, IPPROTO_TCP, TCP_NODELAY, (void *) &_true, sizeof( int ) ) == SOCKET_ERROR ) { - WinPrint( "WINS_Accept: %s\n", WINS_ErrorMessage( WSAGetLastError() ) ); - WinPrint( "setsockopt error\n" ); - } //end if - return newsocket; -} //end of the function WINS_Accept -//=========================================================================== -// -// Parameter: - -// Returns: - -// Changes Globals: - -//=========================================================================== -int WINS_CloseSocket( int socket ){ - /* - if (socket == net_broadcastsocket) - net_broadcastsocket = 0; - */ -// shutdown(socket, SD_SEND); - - if ( closesocket( socket ) == SOCKET_ERROR ) { - WinPrint( "WINS_CloseSocket: %s\n", WINS_ErrorMessage( WSAGetLastError() ) ); - return SOCKET_ERROR; - } //end if - return 0; -} //end of the function WINS_CloseSocket -//=========================================================================== -// this lets you type only as much of the net address as required, using -// the local network components to fill in the rest -// -// Parameter: - -// Returns: - -// Changes Globals: - -//=========================================================================== -static int PartialIPAddress( char *in, struct sockaddr_s *hostaddr ){ - char buff[256]; - char *b; - int addr; - int num; - int mask; - - buff[0] = '.'; - b = buff; - strcpy( buff + 1, in ); - if ( buff[1] == '.' ) { - b++; - } - - addr = 0; - mask = -1; - while ( *b == '.' ) - { - num = 0; - if ( *++b < '0' || *b > '9' ) { - return -1; - } - while ( !( *b < '0' || *b > '9' ) ) - num = num * 10 + *( b++ ) - '0'; - mask <<= 8; - addr = ( addr << 8 ) + num; - } - - hostaddr->sa_family = AF_INET; - ( (struct sockaddr_in *)hostaddr )->sin_port = htons( (u_short)net_hostport ); - ( (struct sockaddr_in *)hostaddr )->sin_addr.s_addr = ( myAddr & htonl( mask ) ) | htonl( addr ); - - return 0; -} //end of the function PartialIPAddress -//=========================================================================== -// -// Parameter: - -// Returns: - -// Changes Globals: - -//=========================================================================== -int WINS_Connect( int socket, struct sockaddr_s *addr ){ - int ret; - u_long _true2 = 0xFFFFFFFF; - - ret = connect( socket, (struct sockaddr *)addr, sizeof( struct sockaddr_s ) ); - if ( ret == SOCKET_ERROR ) { - WinPrint( "WINS_Connect: %s\n", WINS_ErrorMessage( WSAGetLastError() ) ); - return -1; - } //end if - if ( ioctlsocket( socket, FIONBIO, &_true2 ) == -1 ) { - WinPrint( "WINS_Connect: %s\n", WINS_ErrorMessage( WSAGetLastError() ) ); - return -1; - } //end if - return 0; -} //end of the function WINS_Connect -//=========================================================================== -// -// Parameter: - -// Returns: - -// Changes Globals: - -//=========================================================================== -int WINS_CheckNewConnections( void ){ - char buf[4]; - - if ( net_acceptsocket == -1 ) { - return -1; - } - - if ( recvfrom( net_acceptsocket, buf, 4, MSG_PEEK, NULL, NULL ) > 0 ) { - return net_acceptsocket; - } - return -1; -} //end of the function WINS_CheckNewConnections -//=========================================================================== -// returns the number of bytes read -// 0 if no bytes available -// -1 on failure -// -// Parameter: - -// Returns: - -// Changes Globals: - -//=========================================================================== -int WINS_Read( int socket, byte *buf, int len, struct sockaddr_s *addr ){ - int addrlen = sizeof( struct sockaddr_s ); - int ret, errno; - - if ( addr ) { - ret = recvfrom( socket, buf, len, 0, (struct sockaddr *)addr, &addrlen ); - if ( ret == -1 ) { - errno = WSAGetLastError(); - - if ( errno == WSAEWOULDBLOCK || errno == WSAECONNREFUSED ) { - return 0; - } - } //end if - } //end if - else - { - ret = recv( socket, buf, len, 0 ); - if ( ret == SOCKET_ERROR ) { - errno = WSAGetLastError(); - - if ( errno == WSAEWOULDBLOCK || errno == WSAECONNREFUSED ) { - return 0; - } - } //end if - } //end else - if ( ret == SOCKET_ERROR ) { - WinPrint( "WINS_Read: %s\n", WINS_ErrorMessage( WSAGetLastError() ) ); - } //end if - return ret; -} //end of the function WINS_Read -//=========================================================================== -// -// Parameter: - -// Returns: - -// Changes Globals: - -//=========================================================================== -int WINS_MakeSocketBroadcastCapable( int socket ){ - int i = 1; - - // make this socket broadcast capable - if ( setsockopt( socket, SOL_SOCKET, SO_BROADCAST, (char *)&i, sizeof( i ) ) < 0 ) { - return -1; - } - net_broadcastsocket = socket; - - return 0; -} //end of the function WINS_MakeSocketBroadcastCapable -//=========================================================================== -// -// Parameter: - -// Returns: - -// Changes Globals: - -//=========================================================================== -int WINS_Broadcast( int socket, byte *buf, int len ){ - int ret; - - if ( socket != net_broadcastsocket ) { - if ( net_broadcastsocket != 0 ) { - WinError( "Attempted to use multiple broadcasts sockets\n" ); - } - ret = WINS_MakeSocketBroadcastCapable( socket ); - if ( ret == -1 ) { - WinPrint( "Unable to make socket broadcast capable\n" ); - return ret; - } - } - - return WINS_Write( socket, buf, len, &broadcastaddr ); -} //end of the function WINS_Broadcast -//=========================================================================== -// returns qtrue on success or qfalse on failure -// -// Parameter: - -// Returns: - -// Changes Globals: - -//=========================================================================== -int WINS_Write( int socket, byte *buf, int len, struct sockaddr_s *addr ){ - int ret, written; - - if ( addr ) { - written = 0; - while ( written < len ) - { - ret = sendto( socket, &buf[written], len - written, 0, (struct sockaddr *)addr, sizeof( struct sockaddr_s ) ); - if ( ret == SOCKET_ERROR ) { - if ( WSAGetLastError() != WSAEWOULDBLOCK ) { - return qfalse; - } - Sleep( 1000 ); - } //end if - else - { - written += ret; - } - } - } //end if - else - { - written = 0; - while ( written < len ) - { - ret = send( socket, buf, len, 0 ); - if ( ret == SOCKET_ERROR ) { - if ( WSAGetLastError() != WSAEWOULDBLOCK ) { - return qfalse; - } - Sleep( 1000 ); - } //end if - else - { - written += ret; - } - } - } //end else - if ( ret == SOCKET_ERROR ) { - WinPrint( "WINS_Write: %s\n", WINS_ErrorMessage( WSAGetLastError() ) ); - } //end if - return ( ret == len ); -} //end of the function WINS_Write -//=========================================================================== -// -// Parameter: - -// Returns: - -// Changes Globals: - -//=========================================================================== -char *WINS_AddrToString( struct sockaddr_s *addr ){ - static char buffer[22]; - int haddr; - - haddr = ntohl( ( (struct sockaddr_in *)addr )->sin_addr.s_addr ); - sprintf( buffer, "%d.%d.%d.%d:%d", ( haddr >> 24 ) & 0xff, ( haddr >> 16 ) & 0xff, ( haddr >> 8 ) & 0xff, haddr & 0xff, ntohs( ( (struct sockaddr_in *)addr )->sin_port ) ); - return buffer; -} //end of the function WINS_AddrToString -//=========================================================================== -// -// Parameter: - -// Returns: - -// Changes Globals: - -//=========================================================================== -int WINS_StringToAddr( char *string, struct sockaddr_s *addr ){ - int ha1, ha2, ha3, ha4, hp; - int ipaddr; - - sscanf( string, "%d.%d.%d.%d:%d", &ha1, &ha2, &ha3, &ha4, &hp ); - ipaddr = ( ha1 << 24 ) | ( ha2 << 16 ) | ( ha3 << 8 ) | ha4; - - addr->sa_family = AF_INET; - ( (struct sockaddr_in *)addr )->sin_addr.s_addr = htonl( ipaddr ); - ( (struct sockaddr_in *)addr )->sin_port = htons( (u_short)hp ); - return 0; -} //end of the function WINS_StringToAddr -//=========================================================================== -// -// Parameter: - -// Returns: - -// Changes Globals: - -//=========================================================================== -int WINS_GetSocketAddr( int socket, struct sockaddr_s *addr ){ - int addrlen = sizeof( struct sockaddr_s ); - unsigned int a; - - memset( addr, 0, sizeof( struct sockaddr_s ) ); - getsockname( socket, (struct sockaddr *)addr, &addrlen ); - a = ( (struct sockaddr_in *)addr )->sin_addr.s_addr; - if ( a == 0 || a == inet_addr( "127.0.0.1" ) ) { - ( (struct sockaddr_in *)addr )->sin_addr.s_addr = myAddr; - } - - return 0; -} //end of the function WINS_GetSocketAddr -//=========================================================================== -// -// Parameter: - -// Returns: - -// Changes Globals: - -//=========================================================================== -int WINS_GetNameFromAddr( struct sockaddr_s *addr, char *name ){ - struct hostent *hostentry; - - hostentry = gethostbyaddr( (char *)&( (struct sockaddr_in *)addr )->sin_addr, sizeof( struct in_addr ), AF_INET ); - if ( hostentry ) { - strncpy( name, (char *)hostentry->h_name, NET_NAMELEN - 1 ); - return 0; - } - - strcpy( name, WINS_AddrToString( addr ) ); - return 0; -} //end of the function WINS_GetNameFromAddr -//=========================================================================== -// -// Parameter: - -// Returns: - -// Changes Globals: - -//=========================================================================== -int WINS_GetAddrFromName( char *name, struct sockaddr_s *addr ){ - struct hostent *hostentry; - - if ( name[0] >= '0' && name[0] <= '9' ) { - return PartialIPAddress( name, addr ); - } - - hostentry = gethostbyname( name ); - if ( !hostentry ) { - return -1; - } - - addr->sa_family = AF_INET; - ( (struct sockaddr_in *)addr )->sin_port = htons( (u_short)net_hostport ); - ( (struct sockaddr_in *)addr )->sin_addr.s_addr = *(int *)hostentry->h_addr_list[0]; - - return 0; -} //end of the function WINS_GetAddrFromName -//=========================================================================== -// -// Parameter: - -// Returns: - -// Changes Globals: - -//=========================================================================== -int WINS_AddrCompare( struct sockaddr_s *addr1, struct sockaddr_s *addr2 ){ - if ( addr1->sa_family != addr2->sa_family ) { - return -1; - } - - if ( ( (struct sockaddr_in *)addr1 )->sin_addr.s_addr != ( (struct sockaddr_in *)addr2 )->sin_addr.s_addr ) { - return -1; - } - - if ( ( (struct sockaddr_in *)addr1 )->sin_port != ( (struct sockaddr_in *)addr2 )->sin_port ) { - return 1; - } - - return 0; -} //end of the function WINS_AddrCompare -//=========================================================================== -// -// Parameter: - -// Returns: - -// Changes Globals: - -//=========================================================================== -int WINS_GetSocketPort( struct sockaddr_s *addr ){ - return ntohs( ( (struct sockaddr_in *)addr )->sin_port ); -} //end of the function WINS_GetSocketPort -//=========================================================================== -// -// Parameter: - -// Returns: - -// Changes Globals: - -//=========================================================================== -int WINS_SetSocketPort( struct sockaddr_s *addr, int port ){ - ( (struct sockaddr_in *)addr )->sin_port = htons( (u_short)port ); - return 0; -} //end of the function WINS_SetSocketPort diff --git a/tools/urt/libs/l_net/l_net_wins.h b/tools/urt/libs/l_net/l_net_wins.h deleted file mode 100644 index 88c86aa..0000000 --- a/tools/urt/libs/l_net/l_net_wins.h +++ /dev/null @@ -1,52 +0,0 @@ -/* - Copyright (C) 1999-2007 id Software, Inc. and contributors. - For a list of contributors, see the accompanying CONTRIBUTORS file. - - This file is part of GtkRadiant. - - GtkRadiant is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - GtkRadiant is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with GtkRadiant; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - */ - -//=========================================================================== -// -// Name: l_net_wins.h -// Function: WinSock -// Programmer: MrElusive -// Last update: TTimo: cross-platform version, l_net library -// Tab Size: 3 -// Notes: -//=========================================================================== - -int WINS_Init( void ); -void WINS_Shutdown( void ); -char *WINS_MyAddress( void ); -int WINS_Listen( int socket ); -int WINS_Accept( int socket, struct sockaddr_s *addr ); -int WINS_OpenSocket( int port ); -int WINS_OpenReliableSocket( int port ); -int WINS_CloseSocket( int socket ); -int WINS_Connect( int socket, struct sockaddr_s *addr ); -int WINS_CheckNewConnections( void ); -int WINS_Read( int socket, byte *buf, int len, struct sockaddr_s *addr ); -int WINS_Write( int socket, byte *buf, int len, struct sockaddr_s *addr ); -int WINS_Broadcast( int socket, byte *buf, int len ); -char *WINS_AddrToString( struct sockaddr_s *addr ); -int WINS_StringToAddr( char *string, struct sockaddr_s *addr ); -int WINS_GetSocketAddr( int socket, struct sockaddr_s *addr ); -int WINS_GetNameFromAddr( struct sockaddr_s *addr, char *name ); -int WINS_GetAddrFromName( char *name, struct sockaddr_s *addr ); -int WINS_AddrCompare( struct sockaddr_s *addr1, struct sockaddr_s *addr2 ); -int WINS_GetSocketPort( struct sockaddr_s *addr ); -int WINS_SetSocketPort( struct sockaddr_s *addr, int port ); diff --git a/tools/urt/libs/libs.vcproj b/tools/urt/libs/libs.vcproj deleted file mode 100644 index 71b155a..0000000 --- a/tools/urt/libs/libs.vcproj +++ /dev/null @@ -1,592 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/tools/urt/libs/maplib.cpp b/tools/urt/libs/maplib.cpp deleted file mode 100644 index 5611d4c..0000000 --- a/tools/urt/libs/maplib.cpp +++ /dev/null @@ -1,2 +0,0 @@ - -#include "maplib.h" diff --git a/tools/urt/libs/maplib.h b/tools/urt/libs/maplib.h deleted file mode 100644 index a52b144..0000000 --- a/tools/urt/libs/maplib.h +++ /dev/null @@ -1,218 +0,0 @@ - -#if !defined ( INCLUDED_MAPLIB_H ) -#define INCLUDED_MAPLIB_H - -#include "nameable.h" -#include "mapfile.h" - -#include "traverselib.h" -#include "transformlib.h" -#include "scenelib.h" -#include "string/string.h" -#include "instancelib.h" -#include "selectionlib.h" -#include "generic/callback.h" - - -class NameableString : public Nameable -{ -CopiedString m_name; -public: -NameableString( const char* name ) - : m_name( name ){ -} - -const char* name() const { - return m_name.c_str(); -} -void attach( const NameCallback& callback ){ -} -void detach( const NameCallback& callback ){ -} -}; - - -class UndoFileChangeTracker : public UndoTracker, public MapFile -{ -std::size_t m_size; -std::size_t m_saved; -typedef void ( UndoFileChangeTracker::*Pending )(); -Pending m_pending; -Callback m_changed; - -public: -UndoFileChangeTracker() : m_size( 0 ), m_saved( MAPFILE_MAX_CHANGES ), m_pending( 0 ){ -} -void print(){ - globalOutputStream() << "saved: " << Unsigned( m_saved ) << " size: " << Unsigned( m_size ) << "\n"; -} - -void push(){ - ++m_size; - m_changed(); - //print(); -} -void pop(){ - --m_size; - m_changed(); - //print(); -} -void pushOperation(){ - if ( m_size < m_saved ) { - // redo queue has been flushed.. it is now impossible to get back to the saved state via undo/redo - m_saved = MAPFILE_MAX_CHANGES; - } - push(); -} -void clear(){ - m_size = 0; - m_changed(); - //print(); -} -void begin(){ - m_pending = Pending( &UndoFileChangeTracker::pushOperation ); -} -void undo(){ - m_pending = Pending( &UndoFileChangeTracker::pop ); -} -void redo(){ - m_pending = Pending( &UndoFileChangeTracker::push ); -} - -void changed(){ - if ( m_pending != 0 ) { - ( ( *this ).*m_pending )(); - m_pending = 0; - } -} - -void save(){ - m_saved = m_size; - m_changed(); -} -bool saved() const { - return m_saved == m_size; -} - -void setChangedCallback( const Callback& changed ){ - m_changed = changed; - m_changed(); -} - -std::size_t changes() const { - return m_size; -} -}; - - -class MapRoot : public scene::Node::Symbiot, public scene::Instantiable, public scene::Traversable::Observer -{ -class TypeCasts -{ -NodeTypeCastTable m_casts; -public: -TypeCasts(){ - NodeStaticCast::install( m_casts ); - NodeContainedCast::install( m_casts ); - NodeContainedCast::install( m_casts ); - NodeContainedCast::install( m_casts ); - NodeContainedCast::install( m_casts ); -} -NodeTypeCastTable& get(){ - return m_casts; -} -}; - -scene::Node m_node; -IdentityTransform m_transform; -TraversableNodeSet m_traverse; -Instances m_instances; -typedef SelectableInstance Instance; -NameableString m_name; -UndoFileChangeTracker m_changeTracker; -public: -typedef LazyStatic StaticTypeCasts; - -scene::Traversable& get( NullType){ - return m_traverse; -} -Transformable& get( NullType){ - return m_transform; -} -Nameable& get( NullType){ - return m_name; -} -MapFile& get( NullType){ - return m_changeTracker; -} - -MapRoot( const char* name ) : m_node( this, this, StaticTypeCasts::instance().get() ), m_name( name ){ - m_node.m_isRoot = true; - - m_traverse.attach( this ); - - GlobalUndoSystem().trackerAttach( m_changeTracker ); -} -~MapRoot(){ -} -void release(){ - GlobalUndoSystem().trackerDetach( m_changeTracker ); - - m_traverse.detach( this ); - delete this; -} -scene::Node& node(){ - return m_node; -} - -InstanceCounter m_instanceCounter; -void instanceAttach( const scene::Path& path ){ - if ( ++m_instanceCounter.m_count == 1 ) { - m_traverse.instanceAttach( path_find_mapfile( path.begin(), path.end() ) ); - } -} -void instanceDetach( const scene::Path& path ){ - if ( --m_instanceCounter.m_count == 0 ) { - m_traverse.instanceDetach( path_find_mapfile( path.begin(), path.end() ) ); - } -} - -void insert( scene::Node& child ){ - m_instances.insert( child ); -} -void erase( scene::Node& child ){ - m_instances.erase( child ); -} - -scene::Node& clone() const { - return ( new MapRoot( *this ) )->node(); -} - -scene::Instance* create( const scene::Path& path, scene::Instance* parent ){ - return new Instance( path, parent ); -} -void forEachInstance( const scene::Instantiable::Visitor& visitor ){ - m_instances.forEachInstance( visitor ); -} -void insert( scene::Instantiable::Observer* observer, const scene::Path& path, scene::Instance* instance ){ - m_instances.insert( observer, path, instance ); - instanceAttach( path ); -} -scene::Instance* erase( scene::Instantiable::Observer* observer, const scene::Path& path ){ - instanceDetach( path ); - return m_instances.erase( observer, path ); -} -}; - -inline void MapRoot_construct(){ -} - -inline void MapRoot_destroy(){ -} - -inline NodeSmartReference NewMapRoot( const char* name ){ - return NodeSmartReference( ( new MapRoot( name ) )->node() ); -} - - -#endif diff --git a/tools/urt/libs/math/aabb.cpp b/tools/urt/libs/math/aabb.cpp deleted file mode 100644 index e624417..0000000 --- a/tools/urt/libs/math/aabb.cpp +++ /dev/null @@ -1,2 +0,0 @@ - -#include "aabb.h" diff --git a/tools/urt/libs/math/aabb.h b/tools/urt/libs/math/aabb.h deleted file mode 100644 index 4c0eb44..0000000 --- a/tools/urt/libs/math/aabb.h +++ /dev/null @@ -1,243 +0,0 @@ - -#if !defined( INCLUDED_MATH_AABB_H ) -#define INCLUDED_MATH_AABB_H - -/// \file -/// \brief Axis-aligned bounding-box data types and related operations. - -#include "math/matrix.h" -#include "math/plane.h" - -class AABB -{ -public: -Vector3 origin, extents; - -AABB() : origin( 0, 0, 0 ), extents( -1,-1,-1 ){ -} -AABB( const Vector3& origin_, const Vector3& extents_ ) : - origin( origin_ ), extents( extents_ ){ -} -}; - -const float c_aabb_max = FLT_MAX; - -inline bool extents_valid( float f ){ - return f >= 0.0f && f <= c_aabb_max; -} - -inline bool origin_valid( float f ){ - return f >= -c_aabb_max && f <= c_aabb_max; -} - -inline bool aabb_valid( const AABB& aabb ){ - return origin_valid( aabb.origin[0] ) - && origin_valid( aabb.origin[1] ) - && origin_valid( aabb.origin[2] ) - && extents_valid( aabb.extents[0] ) - && extents_valid( aabb.extents[1] ) - && extents_valid( aabb.extents[2] ); -} - -inline AABB aabb_for_minmax( const Vector3& min, const Vector3& max ){ - AABB aabb; - aabb.origin = vector3_mid( min, max ); - aabb.extents = vector3_subtracted( max, aabb.origin ); - return aabb; -} - -template -class AABBExtend -{ -public: -static void apply( AABB& aabb, const Vector3& point ){ - float displacement = point[Index::value] - aabb.origin[Index::value]; - float half_difference = static_cast( 0.5 * ( fabs( displacement ) - aabb.extents[Index::value] ) ); - if ( half_difference > 0.0f ) { - aabb.origin[Index::value] += ( displacement >= 0.0f ) ? half_difference : -half_difference; - aabb.extents[Index::value] += half_difference; - } -} -static void apply( AABB& aabb, const AABB& other ){ - float displacement = other.origin[Index::value] - aabb.origin[Index::value]; - float difference = other.extents[Index::value] - aabb.extents[Index::value]; - if ( fabs( displacement ) > fabs( difference ) ) { - float half_difference = static_cast( 0.5 * ( fabs( displacement ) + difference ) ); - if ( half_difference > 0.0f ) { - aabb.origin[Index::value] += ( displacement >= 0.0f ) ? half_difference : -half_difference; - aabb.extents[Index::value] += half_difference; - } - } - else if ( difference > 0.0f ) { - aabb.origin[Index::value] = other.origin[Index::value]; - aabb.extents[Index::value] = other.extents[Index::value]; - } -} -}; - -inline void aabb_extend_by_point( AABB& aabb, const Vector3& point ){ - AABBExtend< ct_int<0> >::apply( aabb, point ); - AABBExtend< ct_int<1> >::apply( aabb, point ); - AABBExtend< ct_int<2> >::apply( aabb, point ); -} - -inline void aabb_extend_by_point_safe( AABB& aabb, const Vector3& point ){ - if ( aabb_valid( aabb ) ) { - aabb_extend_by_point( aabb, point ); - } - else - { - aabb.origin = point; - aabb.extents = Vector3( 0, 0, 0 ); - } -} - -class AABBExtendByPoint -{ -AABB& m_aabb; -public: -AABBExtendByPoint( AABB& aabb ) : m_aabb( aabb ){ -} -void operator()( const Vector3& point ) const { - aabb_extend_by_point_safe( m_aabb, point ); -} -}; - -inline void aabb_extend_by_aabb( AABB& aabb, const AABB& other ){ - AABBExtend< ct_int<0> >::apply( aabb, other ); - AABBExtend< ct_int<1> >::apply( aabb, other ); - AABBExtend< ct_int<2> >::apply( aabb, other ); -} - -inline void aabb_extend_by_aabb_safe( AABB& aabb, const AABB& other ){ - if ( aabb_valid( aabb ) && aabb_valid( other ) ) { - aabb_extend_by_aabb( aabb, other ); - } - else if ( aabb_valid( other ) ) { - aabb = other; - } -} - -inline void aabb_extend_by_vec3( AABB& aabb, const Vector3& extension ){ - vector3_add( aabb.extents, extension ); -} - - - - -template -inline bool aabb_intersects_point_dimension( const AABB& aabb, const Vector3& point ){ - return fabs( point[Index::value] - aabb.origin[Index::value] ) < aabb.extents[Index::value]; -} - -inline bool aabb_intersects_point( const AABB& aabb, const Vector3& point ){ - return aabb_intersects_point_dimension< ct_int<0> >( aabb, point ) - && aabb_intersects_point_dimension< ct_int<1> >( aabb, point ) - && aabb_intersects_point_dimension< ct_int<2> >( aabb, point ); -} - -template -inline bool aabb_intersects_aabb_dimension( const AABB& aabb, const AABB& other ){ - return fabs( other.origin[Index::value] - aabb.origin[Index::value] ) < ( aabb.extents[Index::value] + other.extents[Index::value] ); -} - -inline bool aabb_intersects_aabb( const AABB& aabb, const AABB& other ){ - return aabb_intersects_aabb_dimension< ct_int<0> >( aabb, other ) - && aabb_intersects_aabb_dimension< ct_int<1> >( aabb, other ) - && aabb_intersects_aabb_dimension< ct_int<2> >( aabb, other ); -} - -inline unsigned int aabb_classify_plane( const AABB& aabb, const Plane3& plane ){ - double distance_origin = vector3_dot( plane.normal(), aabb.origin ) + plane.dist(); - - if ( fabs( distance_origin ) < ( fabs( plane.a * aabb.extents[0] ) - + fabs( plane.b * aabb.extents[1] ) - + fabs( plane.c * aabb.extents[2] ) ) ) { - return 1; // partially inside - } - else if ( distance_origin < 0 ) { - return 2; // totally inside - } - return 0; // totally outside -} - -inline unsigned int aabb_oriented_classify_plane( const AABB& aabb, const Matrix4& transform, const Plane3& plane ){ - double distance_origin = vector3_dot( plane.normal(), aabb.origin ) + plane.dist(); - - if ( fabs( distance_origin ) < ( fabs( aabb.extents[0] * vector3_dot( plane.normal(), vector4_to_vector3( transform.x() ) ) ) - + fabs( aabb.extents[1] * vector3_dot( plane.normal(), vector4_to_vector3( transform.y() ) ) ) - + fabs( aabb.extents[2] * vector3_dot( plane.normal(), vector4_to_vector3( transform.z() ) ) ) ) ) { - return 1; // partially inside - } - else if ( distance_origin < 0 ) { - return 2; // totally inside - } - return 0; // totally outside -} - -inline void aabb_corners( const AABB& aabb, Vector3 corners[8] ){ - Vector3 min( vector3_subtracted( aabb.origin, aabb.extents ) ); - Vector3 max( vector3_added( aabb.origin, aabb.extents ) ); - corners[0] = Vector3( min[0], max[1], max[2] ); - corners[1] = Vector3( max[0], max[1], max[2] ); - corners[2] = Vector3( max[0], min[1], max[2] ); - corners[3] = Vector3( min[0], min[1], max[2] ); - corners[4] = Vector3( min[0], max[1], min[2] ); - corners[5] = Vector3( max[0], max[1], min[2] ); - corners[6] = Vector3( max[0], min[1], min[2] ); - corners[7] = Vector3( min[0], min[1], min[2] ); -} - -inline void aabb_planes( const AABB& aabb, Plane3 planes[6] ){ - planes[0] = Plane3( g_vector3_axes[0], aabb.origin[0] + aabb.extents[0] ); - planes[1] = Plane3( vector3_negated( g_vector3_axes[0] ), -( aabb.origin[0] - aabb.extents[0] ) ); - planes[2] = Plane3( g_vector3_axes[1], aabb.origin[1] + aabb.extents[1] ); - planes[3] = Plane3( vector3_negated( g_vector3_axes[1] ), -( aabb.origin[1] - aabb.extents[1] ) ); - planes[4] = Plane3( g_vector3_axes[2], aabb.origin[2] + aabb.extents[2] ); - planes[5] = Plane3( vector3_negated( g_vector3_axes[2] ), -( aabb.origin[2] - aabb.extents[2] ) ); -} - -const Vector3 aabb_normals[6] = { - Vector3( 1, 0, 0 ), - Vector3( 0, 1, 0 ), - Vector3( 0, 0, 1 ), - Vector3( -1, 0, 0 ), - Vector3( 0,-1, 0 ), - Vector3( 0, 0,-1 ), -}; - -const float aabb_texcoord_topleft[2] = { 0, 0 }; -const float aabb_texcoord_topright[2] = { 1, 0 }; -const float aabb_texcoord_botleft[2] = { 0, 1 }; -const float aabb_texcoord_botright[2] = { 1, 1 }; - - -inline AABB aabb_for_oriented_aabb( const AABB& aabb, const Matrix4& transform ){ - return AABB( - matrix4_transformed_point( transform, aabb.origin ), - Vector3( - static_cast( fabs( transform[0] * aabb.extents[0] ) - + fabs( transform[4] * aabb.extents[1] ) - + fabs( transform[8] * aabb.extents[2] ) ), - static_cast( fabs( transform[1] * aabb.extents[0] ) - + fabs( transform[5] * aabb.extents[1] ) - + fabs( transform[9] * aabb.extents[2] ) ), - static_cast( fabs( transform[2] * aabb.extents[0] ) - + fabs( transform[6] * aabb.extents[1] ) - + fabs( transform[10] * aabb.extents[2] ) ) - ) - ); -} - -inline AABB aabb_for_oriented_aabb_safe( const AABB& aabb, const Matrix4& transform ){ - if ( aabb_valid( aabb ) ) { - return aabb_for_oriented_aabb( aabb, transform ); - } - return aabb; -} - -inline AABB aabb_infinite(){ - return AABB( Vector3( 0, 0, 0 ), Vector3( c_aabb_max, c_aabb_max, c_aabb_max ) ); -} - -#endif diff --git a/tools/urt/libs/math/curve.cpp b/tools/urt/libs/math/curve.cpp deleted file mode 100644 index fa76240..0000000 --- a/tools/urt/libs/math/curve.cpp +++ /dev/null @@ -1,2 +0,0 @@ - -#include "curve.h" diff --git a/tools/urt/libs/math/curve.h b/tools/urt/libs/math/curve.h deleted file mode 100644 index 31d8906..0000000 --- a/tools/urt/libs/math/curve.h +++ /dev/null @@ -1,232 +0,0 @@ - -#if !defined( INCLUDED_MATH_CURVE_H ) -#define INCLUDED_MATH_CURVE_H - -/// \file -/// \brief Curve data types and related operations. - -#include "debugging/debugging.h" -#include "container/array.h" -#include - - -template -struct BernsteinPolynomial -{ - static double apply( double t ){ - return 1; // general case not implemented - } -}; - -typedef ct_int<0> Zero; -typedef ct_int<1> One; -typedef ct_int<2> Two; -typedef ct_int<3> Three; -typedef ct_int<4> Four; - -template<> -struct BernsteinPolynomial -{ - static double apply( double t ){ - return 1; - } -}; - -template<> -struct BernsteinPolynomial -{ - static double apply( double t ){ - return 1 - t; - } -}; - -template<> -struct BernsteinPolynomial -{ - static double apply( double t ){ - return t; - } -}; - -template<> -struct BernsteinPolynomial -{ - static double apply( double t ){ - return ( 1 - t ) * ( 1 - t ); - } -}; - -template<> -struct BernsteinPolynomial -{ - static double apply( double t ){ - return 2 * ( 1 - t ) * t; - } -}; - -template<> -struct BernsteinPolynomial -{ - static double apply( double t ){ - return t * t; - } -}; - -template<> -struct BernsteinPolynomial -{ - static double apply( double t ){ - return ( 1 - t ) * ( 1 - t ) * ( 1 - t ); - } -}; - -template<> -struct BernsteinPolynomial -{ - static double apply( double t ){ - return 3 * ( 1 - t ) * ( 1 - t ) * t; - } -}; - -template<> -struct BernsteinPolynomial -{ - static double apply( double t ){ - return 3 * ( 1 - t ) * t * t; - } -}; - -template<> -struct BernsteinPolynomial -{ - static double apply( double t ){ - return t * t * t; - } -}; - -typedef Array ControlPoints; - -inline Vector3 CubicBezier_evaluate( const Vector3* firstPoint, double t ){ - Vector3 result( 0, 0, 0 ); - double denominator = 0; - - { - double weight = BernsteinPolynomial::apply( t ); - result += vector3_scaled( *firstPoint++, weight ); - denominator += weight; - } - { - double weight = BernsteinPolynomial::apply( t ); - result += vector3_scaled( *firstPoint++, weight ); - denominator += weight; - } - { - double weight = BernsteinPolynomial::apply( t ); - result += vector3_scaled( *firstPoint++, weight ); - denominator += weight; - } - { - double weight = BernsteinPolynomial::apply( t ); - result += vector3_scaled( *firstPoint++, weight ); - denominator += weight; - } - - return result / denominator; -} - -inline Vector3 CubicBezier_evaluateMid( const Vector3* firstPoint ){ - return vector3_scaled( firstPoint[0], 0.125 ) - + vector3_scaled( firstPoint[1], 0.375 ) - + vector3_scaled( firstPoint[2], 0.375 ) - + vector3_scaled( firstPoint[3], 0.125 ); -} - -inline Vector3 CatmullRom_evaluate( const ControlPoints& controlPoints, double t ){ - // scale t to be segment-relative - t *= double(controlPoints.size() - 1); - - // subtract segment index; - std::size_t segment = 0; - for ( std::size_t i = 0; i < controlPoints.size() - 1; ++i ) - { - if ( t <= double(i + 1) ) { - segment = i; - break; - } - } - t -= segment; - - const double reciprocal_alpha = 1.0 / 3.0; - - Vector3 bezierPoints[4]; - bezierPoints[0] = controlPoints[segment]; - bezierPoints[1] = ( segment > 0 ) - ? controlPoints[segment] + vector3_scaled( controlPoints[segment + 1] - controlPoints[segment - 1], reciprocal_alpha * 0.5 ) - : controlPoints[segment] + vector3_scaled( controlPoints[segment + 1] - controlPoints[segment], reciprocal_alpha ); - bezierPoints[2] = ( segment < controlPoints.size() - 2 ) - ? controlPoints[segment + 1] + vector3_scaled( controlPoints[segment] - controlPoints[segment + 2], reciprocal_alpha * 0.5 ) - : controlPoints[segment + 1] + vector3_scaled( controlPoints[segment] - controlPoints[segment + 1], reciprocal_alpha ); - bezierPoints[3] = controlPoints[segment + 1]; - return CubicBezier_evaluate( bezierPoints, t ); -} - -typedef Array Knots; - -inline double BSpline_basis( const Knots& knots, std::size_t i, std::size_t degree, double t ){ - if ( degree == 0 ) { - if ( knots[i] <= t - && t < knots[i + 1] - && knots[i] < knots[i + 1] ) { - return 1; - } - return 0; - } - double leftDenom = knots[i + degree] - knots[i]; - double left = ( leftDenom == 0 ) ? 0 : ( ( t - knots[i] ) / leftDenom ) * BSpline_basis( knots, i, degree - 1, t ); - double rightDenom = knots[i + degree + 1] - knots[i + 1]; - double right = ( rightDenom == 0 ) ? 0 : ( ( knots[i + degree + 1] - t ) / rightDenom ) * BSpline_basis( knots, i + 1, degree - 1, t ); - return left + right; -} - -inline Vector3 BSpline_evaluate( const ControlPoints& controlPoints, const Knots& knots, std::size_t degree, double t ){ - Vector3 result( 0, 0, 0 ); - for ( std::size_t i = 0; i < controlPoints.size(); ++i ) - { - result += vector3_scaled( controlPoints[i], BSpline_basis( knots, i, degree, t ) ); - } - return result; -} - -typedef Array NURBSWeights; - -inline Vector3 NURBS_evaluate( const ControlPoints& controlPoints, const NURBSWeights& weights, const Knots& knots, std::size_t degree, double t ){ - Vector3 result( 0, 0, 0 ); - double denominator = 0; - for ( std::size_t i = 0; i < controlPoints.size(); ++i ) - { - double weight = weights[i] * BSpline_basis( knots, i, degree, t ); - result += vector3_scaled( controlPoints[i], weight ); - denominator += weight; - } - return result / denominator; -} - -inline void KnotVector_openUniform( Knots& knots, std::size_t count, std::size_t degree ){ - knots.resize( count + degree + 1 ); - - std::size_t equalKnots = 1; - - for ( std::size_t i = 0; i < equalKnots; ++i ) - { - knots[i] = 0; - knots[knots.size() - ( i + 1 )] = 1; - } - - std::size_t difference = knots.size() - 2 * ( equalKnots ); - for ( std::size_t i = 0; i < difference; ++i ) - { - knots[i + equalKnots] = Knots::value_type( double(i + 1) * 1.0 / double(difference + 1) ); - } -} - -#endif diff --git a/tools/urt/libs/math/expression.cpp b/tools/urt/libs/math/expression.cpp deleted file mode 100644 index 634b900..0000000 --- a/tools/urt/libs/math/expression.cpp +++ /dev/null @@ -1,189 +0,0 @@ - -#include "expression.h" - -Vector3 testAdded1( const Vector3& a, const Vector3& b ){ - return vector3_added( a, vector3_added( a, b ) ); -} - -Vector3 testAdded2( const Vector3& a, const Vector3& b ){ - return vector3_for_expression( vector_added( vector3_identity( a ), vector_added( vector3_identity( a ), vector3_identity( b ) ) ) ); -} - -Vector3 testMultiplied1( const Vector3& a, const Vector3& b ){ - return vector3_scaled( a, b ); -} - -Vector3 testMultiplied2( const Vector3& a, const Vector3& b ){ - return vector3_for_expression( vector_multiplied( vector3_identity( a ), vector3_identity( b ) ) ); -} - -Vector3 testCross1( const Vector3& a, const Vector3& b ){ - return vector3_cross( a, b ); -} - -Vector3 testCross2( const Vector3& a, const Vector3& b ){ - return vector3_for_expression( vector_cross( vector3_identity( a ), vector3_identity( b ) ) ); -} - -double testDot1( const Vector3& a, const Vector3& b ){ - return vector3_dot( a, b ); -} - -double testDot2( const Vector3& a, const Vector3& b ){ - return float_for_expression( vector_dot( vector3_identity( a ), vector3_identity( b ) ) ); -} - -double testLength1( const Vector3& a ){ - return vector3_length( a ); -} - -double testLength2( const Vector3& a ){ - return float_for_expression( vector_length( vector3_identity( a ) ) ); -} - -Vector3 testNormalised1( const Vector3& a ){ - return vector3_normalised( a ); -} - -Vector3 testNormalised2( const Vector3& a ){ - return vector3_for_expression( vector_normalised( vector3_identity( a ) ) ); -} - -Vector3 testNegated1( const Vector3& a ){ - return vector3_negated( a ); -} - -Vector3 testNegated2( const Vector3& a ){ - return vector3_for_expression( vector_negated( vector3_identity( a ) ) ); -} - -Vector3 testScaled1( const Vector3& a, const double& b ){ - return vector3_scaled( a, b ); -} - -Vector3 testScaled2( const Vector3& a, const double& b ){ - return vector3_for_expression( vector_scaled( vector3_identity( a ), float_literal( b ) ) ); -} - -Vector3 testMatrixMultiplied1( const Vector3& a, const Matrix4& b ){ - return matrix4_transformed_point( b, vector3_added( a, Vector3( 1, 0, 0 ) ) ); -} - -Vector3 testMatrixMultiplied2( const Vector3& a, const Matrix4& b ){ - return vector3_for_expression( - point_multiplied( - vector_added( - vector3_identity( a ), - vector3_literal( Vector3( 1, 0, 0 ) ) - ), - matrix4_identity( b ) - ) - ); -} - -Matrix4 testMatrix4Multiplied1( const Matrix4& a, const Matrix4& b ){ - return matrix4_multiplied_by_matrix4( a, matrix4_multiplied_by_matrix4( a, b ) ); -} - -Matrix4 testMatrix4Multiplied2( const Matrix4& a, const Matrix4& b ){ - return matrix4_for_expression( - matrix4_multiplied( - matrix4_identity( a ), - matrix4_identity( b ) - ) - ); -} - -Matrix4 testMatrix4AffineMultiplied1( const Matrix4& a, const Matrix4& b ){ - return matrix4_affine_multiplied_by_matrix4( a, b ); -} - -Matrix4 testMatrix4AffineMultiplied2( const Matrix4& a, const Matrix4& b ){ - return matrix4_affine_for_expression( - matrix4_multiplied( - matrix4_identity( a ), - matrix4_identity( b ) - ) - ); -} - -Matrix4 testMatrix4MultipliedConstant1( const Matrix4& a ){ - return matrix4_multiplied_by_matrix4( a, g_matrix4_identity ); -} - -Matrix4 testMatrix4MultipliedConstant2( const Matrix4& a ){ - return matrix4_for_expression( - matrix4_multiplied( - matrix4_identity( a ), - matrix4_identity( g_matrix4_identity ) - ) - ); -} -Matrix4 testMatrix4Transposed1( const Matrix4& a ){ - return matrix4_transposed( a ); -} - -Matrix4 testMatrix4Transposed2( const Matrix4& a ){ - return matrix4_for_expression( matrix_transposed( matrix4_identity( a ) ) ); -} - -Vector3 testMulti1( const Matrix4& a, const Vector3& b, const Vector3& c ){ - return vector3_added( matrix4_transformed_point( matrix4_transposed( a ), b ), c ); -} - -Vector3 testMulti2( const Matrix4& a, const Vector3& b, const Vector3& c ){ - return vector3_for_expression( - vector_added( - point_multiplied( - vector3_identity( b ), - matrix_transposed( matrix4_identity( a ) ) - ), - vector3_identity( c ) - ) - ); -} - -template -class TestBinaryFunction -{ -typedef Value ( *Function )( const First&, const Second& ); -Function m_function; -public: - -TestBinaryFunction( Function function ) : m_function( function ){ -} -Value run( const First& first, const Second& second ) const { - return m_function( first, second ); -} -}; - -template -class TestUnaryFunction -{ -typedef Value ( *Function )( const First& ); -Function m_function; -public: - -TestUnaryFunction( Function function ) : m_function( function ){ -} -Value run( const First& first ) const { - return m_function( first ); -} -}; - -class TestAll -{ -public: -TestAll(){ - Vector3 result1 = TestBinaryFunction( testAdded1 ).run( Vector3( 0, 0, 0 ), Vector3( 1, 1, 1 ) ); - Vector3 result2 = TestBinaryFunction( testAdded2 ).run( Vector3( 0, 0, 0 ), Vector3( 1, 1, 1 ) ); - Vector3 result3 = TestBinaryFunction( testMultiplied1 ).run( Vector3( 1, 2, 3 ), Vector3( 2, 1, 0.5f ) ); - Vector3 result4 = TestBinaryFunction( testMultiplied2 ).run( Vector3( 1, 2, 3 ), Vector3( 2, 1, 0.5f ) ); - Vector3 result5 = TestBinaryFunction( testScaled1 ).run( Vector3( 1, 2, 3 ), 2.0 ); - Vector3 result6 = TestBinaryFunction( testScaled2 ).run( Vector3( 1, 2, 3 ), 2.0 ); - Vector3 result7 = TestBinaryFunction( testMatrixMultiplied1 ).run( Vector3( 1, 2, 3 ), matrix4_rotation_for_x_degrees( 90 ) ); - Vector3 result8 = TestBinaryFunction( testMatrixMultiplied2 ).run( Vector3( 1, 2, 3 ), matrix4_rotation_for_x_degrees( 90 ) ); - Vector3 result9 = TestUnaryFunction( testNormalised1 ).run( Vector3( 1, 2, 3 ) ); - Vector3 result10 = TestUnaryFunction( testNormalised2 ).run( Vector3( 1, 2, 3 ) ); -} -} g_testAll; diff --git a/tools/urt/libs/math/expression.h b/tools/urt/libs/math/expression.h deleted file mode 100644 index fb02f5f..0000000 --- a/tools/urt/libs/math/expression.h +++ /dev/null @@ -1,532 +0,0 @@ - -#if !defined ( INCLUDED_EXPRESSION_H ) -#define INCLUDED_EXPRESSION_H - -#include - -template -class Literal -{ -Value m_value; -public: -typedef Value value_type; - -Literal( const Value& value ) - : m_value( value ){ -} -const value_type& eval() const { - return m_value; -} -}; - -template -inline Literal float_literal( const Value& value ){ - return Literal( value ); -} - -template -inline float float_for_expression( const Expression& expression ){ - return expression.eval(); -} - - -template -class ScalarDivided -{ -First first; -Second second; -public: -typedef typename First::value_type value_type; - -ScalarDivided( const First& first_, const Second& second_ ) : first( first_ ), second( second_ ){ -} -value_type eval() const { - return static_cast( first.eval() / second.eval() ); -} -}; - -template -inline ScalarDivided float_divided( const First& first, const Second& second ){ - return ScalarDivided( first, second ); -} - -template -inline ScalarDivided, First> float_reciprocal( const First& first ){ - typedef typename First::value_type first_value_type; - return ScalarDivided, First>( float_literal( first_value_type( 1.0 ) ), first ); -} - -template -class SquareRoot -{ -First first; -public: -typedef typename First::value_type value_type; - -SquareRoot( const First& first_ ) : first( first_ ){ -} -value_type eval() const { - return static_cast( sqrt( first.eval() ) ); -} -}; - -template -inline SquareRoot float_square_root( const First& first ){ - return SquareRoot( first ); -} - - -template -class BasicVector3Literal -{ -const BasicVector3 m_value; -public: -typedef Element value_type; -typedef ct_int<3> dimension; - -BasicVector3Literal( const BasicVector3& value ) - : m_value( value ){ -} -const value_type& eval( unsigned int i ) const { - return m_value[i]; -} -}; - -template -inline BasicVector3Literal vector3_literal( const BasicVector3& value ){ - return BasicVector3Literal( value ); -} - -typedef BasicVector3Literal Vector3Literal; - -template -class BasicVector3Identity -{ -const BasicVector3& m_value; -public: -typedef Element value_type; -typedef ct_int<3> dimension; - -BasicVector3Identity( const BasicVector3& value ) - : m_value( value ){ -} -const value_type& eval( unsigned int i ) const { - return m_value[i]; -} -}; - -template -inline BasicVector3Identity vector3_identity( const BasicVector3& value ){ - return BasicVector3Identity( value ); -} - -typedef BasicVector3Identity Vector3Identity; - -template -inline BasicVector3 vector3_for_expression( const Expression& expression ){ - return Vector3( expression.eval( 0 ), expression.eval( 1 ), expression.eval( 2 ) ); -} - - -template -class VectorScalar -{ -First first; -Literal second; -public: -typedef typename First::value_type value_type; -typedef typename First::dimension dimension; - -VectorScalar( const First& first_, const Second& second_ ) - : first( first_ ), second( second_.eval() ){ -} -value_type eval( unsigned int i ) const { - return Operation::apply( first.eval( i ), second.eval() ); -} -}; - - - -template -class VectorVector -{ -First first; -Second second; -public: -typedef typename First::value_type value_type; -typedef typename First::dimension dimension; - -VectorVector( const First& first_, const Second& second_ ) - : first( first_ ), second( second_ ){ -} -value_type eval( unsigned int i ) const { - return Operation::apply( first.eval( i ), second.eval( i ) ); -} -}; - -template -class Added -{ -public: -typedef First value_type; - -static value_type apply( const First& first, const Second& second ){ - return static_cast( first + second ); -} -}; - -template -inline VectorVector, First, Second> -vector_added( const First& first, const Second& second ){ - typedef typename First::value_type first_value_type; - typedef typename Second::value_type second_value_type; - return VectorVector, First, Second>( first, second ); -} - -template -class Multiplied -{ -public: -typedef First value_type; - -static value_type apply( const First& first, const Second& second ){ - return static_cast( first * second ); -} -}; - -template -inline VectorVector, First, Second> -vector_multiplied( const First& first, const Second& second ){ - typedef typename First::value_type first_value_type; - typedef typename Second::value_type second_value_type; - return VectorVector, First, Second>( first, second ); -} - -template -inline VectorScalar, First, Second> -vector_scaled( const First& first, const Second& second ){ - typedef typename First::value_type first_value_type; - typedef typename Second::value_type second_value_type; - return VectorScalar, First, Second>( first, second ); -} - -template -class Negated -{ -public: -typedef First value_type; - -static value_type apply( const First& first ){ - return -first; -} -}; - -template -class VectorUnary -{ -First first; -public: -typedef typename First::value_type value_type; -typedef typename First::dimension dimension; - -VectorUnary( const First& first_ ) : first( first_ ){ -} -value_type eval( unsigned int i ) const { - return Operation::apply( first.eval( i ) ); -} -}; - -template -inline VectorUnary > -vector_negated( const First& first ){ - typedef typename First::value_type first_value_type; - return VectorUnary >( first ); -} - -template -class VectorCross -{ -First first; -Second second; -public: -typedef typename First::value_type value_type; -typedef typename First::dimension dimension; - -VectorCross( const First& first_, const Second& second_ ) - : first( first_ ), second( second_ ){ -} -value_type eval( unsigned int i ) const { - return first.eval( ( i + 1 ) % 3 ) * second.eval( ( i + 2 ) % 3 ) - first.eval( ( i + 2 ) % 3 ) * second.eval( ( i + 1 ) % 3 ); -} -}; - -template -inline VectorCross -vector_cross( const First& first, const Second& second ){ - return VectorCross( first, second ); -} - - -template -class VectorDot -{ -First first; -Second second; -public: -typedef typename First::value_type value_type; -typedef typename First::dimension dimension; - -VectorDot( const First& first_, const Second& second_ ) - : first( first_ ), second( second_ ){ -} - -template -struct eval_dot -{ - static value_type apply( const First& first, const Second& second ){ - return static_cast( - first.eval( Index::value ) * second.eval( Index::value ) - + eval_dot< ct_int >::apply( first, second ) - ); - } -}; - -template<> -struct eval_dot< ct_int<0> > -{ - static value_type apply( const First& first, const Second& second ){ - return first.eval( 0 ) * second.eval( 0 ); - } -}; - -value_type eval() const { - return eval_dot< ct_int >::apply( first, second ); -} -}; - - -template -inline VectorDot vector_dot( const First& first, const Second& second ){ - return VectorDot( first, second ); -} - -template -class VectorLengthSquared -{ -First first; -public: -typedef typename First::value_type value_type; -typedef typename First::dimension dimension; - -VectorLengthSquared( const First& first_ ) - : first( first_ ){ -} - -static value_type squared( const value_type& value ){ - return value * value; -} - -template -struct eval_squared -{ - static value_type apply( const First& first ){ - return static_cast( - squared( first.eval( Index::value ) ) - + eval_squared< ct_int >::apply( first ) - ); - } -}; - -template<> -struct eval_squared< ct_int<0> > -{ - static value_type apply( const First& first ){ - return squared( first.eval( 0 ) ); - } -}; - -value_type eval() const { - return eval_squared< ct_int >::apply( first ); -} -}; - -template -inline VectorLengthSquared vector_length_squared( const First& first ){ - return VectorLengthSquared( first ); -} - -template -inline SquareRoot< VectorLengthSquared > vector_length( const First& first ){ - return float_square_root( vector_length_squared( first ) ); -} - -#if 1 -template -inline VectorScalar< - Multiplied, - First, - // multiple evaulations of subexpression - ScalarDivided< - Literal, - SquareRoot< - VectorLengthSquared - > - > - > vector_normalised( const First& first ){ - typedef typename First::value_type first_value_type; - return vector_scaled( first, float_reciprocal( vector_length( first ) ) ); -} -#else -template -inline VectorScalar< - Multiplied, - First, - // single evaluation of subexpression - Literal - > -vector_normalised( const First& first ){ - typedef typename First::value_type first_value_type; - return vector_scaled( first, float_literal( static_cast( first_value_type( 1.0 ) / vector_length( first ).eval() ) ) ); -} -#endif - - -class Matrix4Literal -{ -const Matrix4 m_value; -public: -typedef float value_type; -typedef ct_int<4> dimension0; -typedef ct_int<4> dimension1; - -Matrix4Literal( const Matrix4& value ) - : m_value( value ){ -} -const value_type& eval( unsigned int r, unsigned int c ) const { - return m_value[r * 4 + c]; -} -}; - -inline Matrix4Literal matrix4_literal( const Matrix4& value ){ - return Matrix4Literal( value ); -} - -class Matrix4Identity -{ -const Matrix4& m_value; -public: -typedef float value_type; -typedef ct_int<4> dimension0; -typedef ct_int<4> dimension1; - -Matrix4Identity( const Matrix4& value ) - : m_value( value ){ -} -const value_type& eval( unsigned int r, unsigned int c ) const { - return m_value[r * 4 + c]; -} -}; - -inline Matrix4Identity matrix4_identity( const Matrix4& value ){ - return Matrix4Identity( value ); -} - -template -inline Matrix4 matrix4_for_expression( const Expression& expression ){ - return Matrix4( - expression.eval( 0, 0 ), expression.eval( 0, 1 ), expression.eval( 0, 2 ), expression.eval( 0, 3 ), - expression.eval( 1, 0 ), expression.eval( 1, 1 ), expression.eval( 1, 2 ), expression.eval( 1, 3 ), - expression.eval( 2, 0 ), expression.eval( 2, 1 ), expression.eval( 2, 2 ), expression.eval( 2, 3 ), - expression.eval( 3, 0 ), expression.eval( 3, 1 ), expression.eval( 3, 2 ), expression.eval( 3, 3 ) - ); -} - -template -inline Matrix4 matrix4_affine_for_expression( const Expression& expression ){ - return Matrix4( - expression.eval( 0, 0 ), expression.eval( 0, 1 ), expression.eval( 0, 2 ), 0, - expression.eval( 1, 0 ), expression.eval( 1, 1 ), expression.eval( 1, 2 ), 0, - expression.eval( 2, 0 ), expression.eval( 2, 1 ), expression.eval( 2, 2 ), 0, - expression.eval( 3, 0 ), expression.eval( 3, 1 ), expression.eval( 3, 2 ), 1 - ); -} - - -template -class PointMultiplied -{ -const First& first; -const Second& second; -public: -typedef typename First::value_type value_type; -typedef typename First::dimension dimension; - -PointMultiplied( const First& first_, const Second& second_ ) - : first( first_ ), second( second_ ){ -} -value_type eval( unsigned int i ) const { - return static_cast( second.eval( 0, i ) * first.eval( 0 ) - + second.eval( 1, i ) * first.eval( 1 ) - + second.eval( 2, i ) * first.eval( 2 ) - + second.eval( 3, i ) ); -} -}; - -template -inline PointMultiplied point_multiplied( const First& point, const Second& matrix ){ - return PointMultiplied( point, matrix ); -} - -template -class Matrix4Multiplied -{ -const First& first; -const Second& second; -public: -typedef typename First::value_type value_type; -typedef typename First::dimension0 dimension0; -typedef typename First::dimension1 dimension1; - -Matrix4Multiplied( const First& first_, const Second& second_ ) - : first( first_ ), second( second_ ){ -} - -value_type eval( unsigned int r, unsigned int c ) const { - return static_cast( - second.eval( r, 0 ) * first.eval( 0, c ) - + second.eval( r, 1 ) * first.eval( 1, c ) - + second.eval( r, 2 ) * first.eval( 2, c ) - + second.eval( r, 3 ) * first.eval( 3, c ) - ); -} -}; - -template -inline Matrix4Multiplied matrix4_multiplied( const First& first, const Second& second ){ - return Matrix4Multiplied( first, second ); -} - -template -class MatrixTransposed -{ -const First& first; -public: -typedef typename First::value_type value_type; -typedef typename First::dimension0 dimension0; -typedef typename First::dimension1 dimension1; - -MatrixTransposed( const First& first_ ) - : first( first_ ){ -} - -value_type eval( unsigned int r, unsigned int c ) const { - return first.eval( c, r ); -} -}; - -template -inline MatrixTransposed matrix_transposed( const First& first ){ - return MatrixTransposed( first ); -} - -#endif diff --git a/tools/urt/libs/math/frustum.cpp b/tools/urt/libs/math/frustum.cpp deleted file mode 100644 index 1b0248f..0000000 --- a/tools/urt/libs/math/frustum.cpp +++ /dev/null @@ -1,2 +0,0 @@ - -#include "frustum.h" diff --git a/tools/urt/libs/math/frustum.h b/tools/urt/libs/math/frustum.h deleted file mode 100644 index 0ef4ae1..0000000 --- a/tools/urt/libs/math/frustum.h +++ /dev/null @@ -1,587 +0,0 @@ - -#if !defined( INCLUDED_MATH_FRUSTUM_H ) -#define INCLUDED_MATH_FRUSTUM_H - -/// \file -/// \brief View-frustum data types and related operations. - -#include "generic/enumeration.h" -#include "math/matrix.h" -#include "math/plane.h" -#include "math/aabb.h" -#include "math/line.h" - -inline Matrix4 matrix4_frustum( float left, float right, float bottom, float top, float nearval, float farval ){ - return Matrix4( - static_cast( ( 2 * nearval ) / ( right - left ) ), - 0, - 0, - 0, - 0, - static_cast( ( 2 * nearval ) / ( top - bottom ) ), - 0, - 0, - static_cast( ( right + left ) / ( right - left ) ), - static_cast( ( top + bottom ) / ( top - bottom ) ), - static_cast( -( farval + nearval ) / ( farval - nearval ) ), - -1, - 0, - 0, - static_cast( -( 2 * farval * nearval ) / ( farval - nearval ) ), - 0 - ); -} - - - -typedef unsigned char ClipResult; -const ClipResult c_CLIP_PASS = 0x00; // 000000 -const ClipResult c_CLIP_LT_X = 0x01; // 000001 -const ClipResult c_CLIP_GT_X = 0x02; // 000010 -const ClipResult c_CLIP_LT_Y = 0x04; // 000100 -const ClipResult c_CLIP_GT_Y = 0x08; // 001000 -const ClipResult c_CLIP_LT_Z = 0x10; // 010000 -const ClipResult c_CLIP_GT_Z = 0x20; // 100000 -const ClipResult c_CLIP_FAIL = 0x3F; // 111111 - -template -class Vector4ClipLT -{ -public: -static bool compare( const Vector4& self ){ - return self[Index::value] < self[3]; -} -static double scale( const Vector4& self, const Vector4& other ){ - return ( self[Index::value] - self[3] ) / ( other[3] - other[Index::value] ); -} -}; - -template -class Vector4ClipGT -{ -public: -static bool compare( const Vector4& self ){ - return self[Index::value] > -self[3]; -} -static double scale( const Vector4& self, const Vector4& other ){ - return ( self[Index::value] + self[3] ) / ( -other[3] - other[Index::value] ); -} -}; - -template -class Vector4ClipPolygon -{ -public: -typedef Vector4* iterator; -typedef const Vector4* const_iterator; - -static std::size_t apply( const_iterator first, const_iterator last, iterator out ){ - const_iterator next = first, i = last - 1; - iterator tmp( out ); - bool b0 = ClipPlane::compare( *i ); - while ( next != last ) - { - bool b1 = ClipPlane::compare( *next ); - if ( b0 ^ b1 ) { - *out = vector4_subtracted( *next, *i ); - - double scale = ClipPlane::scale( *i, *out ); - - ( *out )[0] = static_cast( ( *i )[0] + scale * ( ( *out )[0] ) ); - ( *out )[1] = static_cast( ( *i )[1] + scale * ( ( *out )[1] ) ); - ( *out )[2] = static_cast( ( *i )[2] + scale * ( ( *out )[2] ) ); - ( *out )[3] = static_cast( ( *i )[3] + scale * ( ( *out )[3] ) ); - - ++out; - } - - if ( b1 ) { - *out = *next; - ++out; - } - - i = next; - ++next; - b0 = b1; - } - - return out - tmp; -} -}; - -#define CLIP_X_LT_W( p ) ( Vector4ClipLT< ct_int<0> >::compare( p ) ) -#define CLIP_X_GT_W( p ) ( Vector4ClipGT< ct_int<0> >::compare( p ) ) -#define CLIP_Y_LT_W( p ) ( Vector4ClipLT< ct_int<1> >::compare( p ) ) -#define CLIP_Y_GT_W( p ) ( Vector4ClipGT< ct_int<1> >::compare( p ) ) -#define CLIP_Z_LT_W( p ) ( Vector4ClipLT< ct_int<2> >::compare( p ) ) -#define CLIP_Z_GT_W( p ) ( Vector4ClipGT< ct_int<2> >::compare( p ) ) - -inline ClipResult homogenous_clip_point( const Vector4& clipped ){ - ClipResult result = c_CLIP_FAIL; - if ( CLIP_X_LT_W( clipped ) ) { - result &= ~c_CLIP_LT_X; // X < W - } - if ( CLIP_X_GT_W( clipped ) ) { - result &= ~c_CLIP_GT_X; // X > -W - } - if ( CLIP_Y_LT_W( clipped ) ) { - result &= ~c_CLIP_LT_Y; // Y < W - } - if ( CLIP_Y_GT_W( clipped ) ) { - result &= ~c_CLIP_GT_Y; // Y > -W - } - if ( CLIP_Z_LT_W( clipped ) ) { - result &= ~c_CLIP_LT_Z; // Z < W - } - if ( CLIP_Z_GT_W( clipped ) ) { - result &= ~c_CLIP_GT_Z; // Z > -W - } - return result; -} - -/// \brief Clips \p point by canonical matrix \p self. -/// Stores the result in \p clipped. -/// Returns a bitmask indicating which clip-planes the point was outside. -inline ClipResult matrix4_clip_point( const Matrix4& self, const Vector3& point, Vector4& clipped ){ - clipped[0] = point[0]; - clipped[1] = point[1]; - clipped[2] = point[2]; - clipped[3] = 1; - matrix4_transform_vector4( self, clipped ); - return homogenous_clip_point( clipped ); -} - - -inline std::size_t homogenous_clip_triangle( Vector4 clipped[9] ){ - Vector4 buffer[9]; - std::size_t count = 3; - count = Vector4ClipPolygon< Vector4ClipLT< ct_int<0> > >::apply( clipped, clipped + count, buffer ); - count = Vector4ClipPolygon< Vector4ClipGT< ct_int<0> > >::apply( buffer, buffer + count, clipped ); - count = Vector4ClipPolygon< Vector4ClipLT< ct_int<1> > >::apply( clipped, clipped + count, buffer ); - count = Vector4ClipPolygon< Vector4ClipGT< ct_int<1> > >::apply( buffer, buffer + count, clipped ); - count = Vector4ClipPolygon< Vector4ClipLT< ct_int<2> > >::apply( clipped, clipped + count, buffer ); - return Vector4ClipPolygon< Vector4ClipGT< ct_int<2> > >::apply( buffer, buffer + count, clipped ); -} - -/// \brief Transforms and clips the triangle formed by \p p0, \p p1, \p p2 by the canonical matrix \p self. -/// Stores the resulting polygon in \p clipped. -/// Returns the number of points in the resulting polygon. -inline std::size_t matrix4_clip_triangle( const Matrix4& self, const Vector3& p0, const Vector3& p1, const Vector3& p2, Vector4 clipped[9] ){ - clipped[0][0] = p0[0]; - clipped[0][1] = p0[1]; - clipped[0][2] = p0[2]; - clipped[0][3] = 1; - clipped[1][0] = p1[0]; - clipped[1][1] = p1[1]; - clipped[1][2] = p1[2]; - clipped[1][3] = 1; - clipped[2][0] = p2[0]; - clipped[2][1] = p2[1]; - clipped[2][2] = p2[2]; - clipped[2][3] = 1; - - matrix4_transform_vector4( self, clipped[0] ); - matrix4_transform_vector4( self, clipped[1] ); - matrix4_transform_vector4( self, clipped[2] ); - - return homogenous_clip_triangle( clipped ); -} - -inline std::size_t homogenous_clip_line( Vector4 clipped[2] ){ - const Vector4& p0 = clipped[0]; - const Vector4& p1 = clipped[1]; - - // early out - { - ClipResult mask0 = homogenous_clip_point( clipped[0] ); - ClipResult mask1 = homogenous_clip_point( clipped[1] ); - - if ( ( mask0 | mask1 ) == c_CLIP_PASS ) { // both points passed all planes - return 2; - } - - if ( mask0 & mask1 ) { // both points failed any one plane - return 0; - } - } - - { - const bool index = CLIP_X_LT_W( p0 ); - if ( index ^ CLIP_X_LT_W( p1 ) ) { - Vector4 clip( vector4_subtracted( p1, p0 ) ); - - double scale = ( p0[0] - p0[3] ) / ( clip[3] - clip[0] ); - - clip[0] = static_cast( p0[0] + scale * clip[0] ); - clip[1] = static_cast( p0[1] + scale * clip[1] ); - clip[2] = static_cast( p0[2] + scale * clip[2] ); - clip[3] = static_cast( p0[3] + scale * clip[3] ); - - clipped[index] = clip; - } - else if ( index == 0 ) { - return 0; - } - } - - { - const bool index = CLIP_X_GT_W( p0 ); - if ( index ^ CLIP_X_GT_W( p1 ) ) { - Vector4 clip( vector4_subtracted( p1, p0 ) ); - - double scale = ( p0[0] + p0[3] ) / ( -clip[3] - clip[0] ); - - clip[0] = static_cast( p0[0] + scale * clip[0] ); - clip[1] = static_cast( p0[1] + scale * clip[1] ); - clip[2] = static_cast( p0[2] + scale * clip[2] ); - clip[3] = static_cast( p0[3] + scale * clip[3] ); - - clipped[index] = clip; - } - else if ( index == 0 ) { - return 0; - } - } - - { - const bool index = CLIP_Y_LT_W( p0 ); - if ( index ^ CLIP_Y_LT_W( p1 ) ) { - Vector4 clip( vector4_subtracted( p1, p0 ) ); - - double scale = ( p0[1] - p0[3] ) / ( clip[3] - clip[1] ); - - clip[0] = static_cast( p0[0] + scale * clip[0] ); - clip[1] = static_cast( p0[1] + scale * clip[1] ); - clip[2] = static_cast( p0[2] + scale * clip[2] ); - clip[3] = static_cast( p0[3] + scale * clip[3] ); - - clipped[index] = clip; - } - else if ( index == 0 ) { - return 0; - } - } - - { - const bool index = CLIP_Y_GT_W( p0 ); - if ( index ^ CLIP_Y_GT_W( p1 ) ) { - Vector4 clip( vector4_subtracted( p1, p0 ) ); - - double scale = ( p0[1] + p0[3] ) / ( -clip[3] - clip[1] ); - - clip[0] = static_cast( p0[0] + scale * clip[0] ); - clip[1] = static_cast( p0[1] + scale * clip[1] ); - clip[2] = static_cast( p0[2] + scale * clip[2] ); - clip[3] = static_cast( p0[3] + scale * clip[3] ); - - clipped[index] = clip; - } - else if ( index == 0 ) { - return 0; - } - } - - { - const bool index = CLIP_Z_LT_W( p0 ); - if ( index ^ CLIP_Z_LT_W( p1 ) ) { - Vector4 clip( vector4_subtracted( p1, p0 ) ); - - double scale = ( p0[2] - p0[3] ) / ( clip[3] - clip[2] ); - - clip[0] = static_cast( p0[0] + scale * clip[0] ); - clip[1] = static_cast( p0[1] + scale * clip[1] ); - clip[2] = static_cast( p0[2] + scale * clip[2] ); - clip[3] = static_cast( p0[3] + scale * clip[3] ); - - clipped[index] = clip; - } - else if ( index == 0 ) { - return 0; - } - } - - { - const bool index = CLIP_Z_GT_W( p0 ); - if ( index ^ CLIP_Z_GT_W( p1 ) ) { - Vector4 clip( vector4_subtracted( p1, p0 ) ); - - double scale = ( p0[2] + p0[3] ) / ( -clip[3] - clip[2] ); - - clip[0] = static_cast( p0[0] + scale * clip[0] ); - clip[1] = static_cast( p0[1] + scale * clip[1] ); - clip[2] = static_cast( p0[2] + scale * clip[2] ); - clip[3] = static_cast( p0[3] + scale * clip[3] ); - - clipped[index] = clip; - } - else if ( index == 0 ) { - return 0; - } - } - - return 2; -} - -/// \brief Transforms and clips the line formed by \p p0, \p p1 by the canonical matrix \p self. -/// Stores the resulting line in \p clipped. -/// Returns the number of points in the resulting line. -inline std::size_t matrix4_clip_line( const Matrix4& self, const Vector3& p0, const Vector3& p1, Vector4 clipped[2] ){ - clipped[0][0] = p0[0]; - clipped[0][1] = p0[1]; - clipped[0][2] = p0[2]; - clipped[0][3] = 1; - clipped[1][0] = p1[0]; - clipped[1][1] = p1[1]; - clipped[1][2] = p1[2]; - clipped[1][3] = 1; - - matrix4_transform_vector4( self, clipped[0] ); - matrix4_transform_vector4( self, clipped[1] ); - - return homogenous_clip_line( clipped ); -} - - - - -struct Frustum -{ - Plane3 right, left, bottom, top, back, front; - - Frustum(){ - } - Frustum( const Plane3& _right, - const Plane3& _left, - const Plane3& _bottom, - const Plane3& _top, - const Plane3& _back, - const Plane3& _front ) - : right( _right ), left( _left ), bottom( _bottom ), top( _top ), back( _back ), front( _front ){ - } -}; - -inline Frustum frustum_transformed( const Frustum& frustum, const Matrix4& transform ){ - return Frustum( - plane3_transformed( frustum.right, transform ), - plane3_transformed( frustum.left, transform ), - plane3_transformed( frustum.bottom, transform ), - plane3_transformed( frustum.top, transform ), - plane3_transformed( frustum.back, transform ), - plane3_transformed( frustum.front, transform ) - ); -} - -inline Frustum frustum_inverse_transformed( const Frustum& frustum, const Matrix4& transform ){ - return Frustum( - plane3_inverse_transformed( frustum.right, transform ), - plane3_inverse_transformed( frustum.left, transform ), - plane3_inverse_transformed( frustum.bottom, transform ), - plane3_inverse_transformed( frustum.top, transform ), - plane3_inverse_transformed( frustum.back, transform ), - plane3_inverse_transformed( frustum.front, transform ) - ); -} - -inline bool viewproj_test_point( const Matrix4& viewproj, const Vector3& point ){ - Vector4 hpoint( matrix4_transformed_vector4( viewproj, Vector4( point, 1.0f ) ) ); - if ( fabs( hpoint[0] ) < fabs( hpoint[3] ) - && fabs( hpoint[1] ) < fabs( hpoint[3] ) - && fabs( hpoint[2] ) < fabs( hpoint[3] ) ) { - return true; - } - return false; -} - -inline bool viewproj_test_transformed_point( const Matrix4& viewproj, const Vector3& point, const Matrix4& localToWorld ){ - return viewproj_test_point( viewproj, matrix4_transformed_point( localToWorld, point ) ); -} - -inline Frustum frustum_from_viewproj( const Matrix4& viewproj ){ - return Frustum - ( - plane3_normalised( Plane3( viewproj[ 3] - viewproj[ 0], viewproj[ 7] - viewproj[ 4], viewproj[11] - viewproj[ 8], viewproj[15] - viewproj[12] ) ), - plane3_normalised( Plane3( viewproj[ 3] + viewproj[ 0], viewproj[ 7] + viewproj[ 4], viewproj[11] + viewproj[ 8], viewproj[15] + viewproj[12] ) ), - plane3_normalised( Plane3( viewproj[ 3] + viewproj[ 1], viewproj[ 7] + viewproj[ 5], viewproj[11] + viewproj[ 9], viewproj[15] + viewproj[13] ) ), - plane3_normalised( Plane3( viewproj[ 3] - viewproj[ 1], viewproj[ 7] - viewproj[ 5], viewproj[11] - viewproj[ 9], viewproj[15] - viewproj[13] ) ), - plane3_normalised( Plane3( viewproj[ 3] - viewproj[ 2], viewproj[ 7] - viewproj[ 6], viewproj[11] - viewproj[10], viewproj[15] - viewproj[14] ) ), - plane3_normalised( Plane3( viewproj[ 3] + viewproj[ 2], viewproj[ 7] + viewproj[ 6], viewproj[11] + viewproj[10], viewproj[15] + viewproj[14] ) ) - ); -} - -struct VolumeIntersection -{ - enum Value - { - OUTSIDE, - INSIDE, - PARTIAL - }; -}; - -typedef EnumeratedValue VolumeIntersectionValue; - -const VolumeIntersectionValue c_volumeOutside( VolumeIntersectionValue::OUTSIDE ); -const VolumeIntersectionValue c_volumeInside( VolumeIntersectionValue::INSIDE ); -const VolumeIntersectionValue c_volumePartial( VolumeIntersectionValue::PARTIAL ); - -inline VolumeIntersectionValue frustum_test_aabb( const Frustum& frustum, const AABB& aabb ){ - VolumeIntersectionValue result = c_volumeInside; - - switch ( aabb_classify_plane( aabb, frustum.right ) ) - { - case 2: - return c_volumeOutside; - case 1: - result = c_volumePartial; - } - - switch ( aabb_classify_plane( aabb, frustum.left ) ) - { - case 2: - return c_volumeOutside; - case 1: - result = c_volumePartial; - } - - switch ( aabb_classify_plane( aabb, frustum.bottom ) ) - { - case 2: - return c_volumeOutside; - case 1: - result = c_volumePartial; - } - - switch ( aabb_classify_plane( aabb, frustum.top ) ) - { - case 2: - return c_volumeOutside; - case 1: - result = c_volumePartial; - } - - switch ( aabb_classify_plane( aabb, frustum.back ) ) - { - case 2: - return c_volumeOutside; - case 1: - result = c_volumePartial; - } - - switch ( aabb_classify_plane( aabb, frustum.front ) ) - { - case 2: - return c_volumeOutside; - case 1: - result = c_volumePartial; - } - - return result; -} - -inline double plane_distance_to_point( const Plane3& plane, const Vector3& point ){ - return vector3_dot( plane.normal(), point ) + plane.d; -} - -inline double plane_distance_to_oriented_extents( const Plane3& plane, const Vector3& extents, const Matrix4& orientation ){ - return fabs( extents[0] * vector3_dot( plane.normal(), vector4_to_vector3( orientation.x() ) ) ) - + fabs( extents[1] * vector3_dot( plane.normal(), vector4_to_vector3( orientation.y() ) ) ) - + fabs( extents[2] * vector3_dot( plane.normal(), vector4_to_vector3( orientation.z() ) ) ); -} - -/// \brief Return false if \p aabb with \p orientation is partially or completely outside \p plane. -inline bool plane_contains_oriented_aabb( const Plane3& plane, const AABB& aabb, const Matrix4& orientation ){ - double dot = plane_distance_to_point( plane, aabb.origin ); - return !( dot > 0 || -dot < plane_distance_to_oriented_extents( plane, aabb.extents, orientation ) ); -} - -inline VolumeIntersectionValue frustum_intersects_transformed_aabb( const Frustum& frustum, const AABB& aabb, const Matrix4& localToWorld ){ - AABB aabb_world( aabb ); - matrix4_transform_point( localToWorld, aabb_world.origin ); - - if ( plane_contains_oriented_aabb( frustum.right, aabb_world, localToWorld ) - || plane_contains_oriented_aabb( frustum.left, aabb_world, localToWorld ) - || plane_contains_oriented_aabb( frustum.bottom, aabb_world, localToWorld ) - || plane_contains_oriented_aabb( frustum.top, aabb_world, localToWorld ) - || plane_contains_oriented_aabb( frustum.back, aabb_world, localToWorld ) - || plane_contains_oriented_aabb( frustum.front, aabb_world, localToWorld ) ) { - return c_volumeOutside; - } - return c_volumeInside; -} - -inline bool plane3_test_point( const Plane3& plane, const Vector3& point ){ - return vector3_dot( point, plane.normal() ) + plane.dist() <= 0; -} - -inline bool plane3_test_line( const Plane3& plane, const Segment& segment ){ - return segment_classify_plane( segment, plane ) == 2; -} - -inline bool frustum_test_point( const Frustum& frustum, const Vector3& point ){ - return !plane3_test_point( frustum.right, point ) - && !plane3_test_point( frustum.left, point ) - && !plane3_test_point( frustum.bottom, point ) - && !plane3_test_point( frustum.top, point ) - && !plane3_test_point( frustum.back, point ) - && !plane3_test_point( frustum.front, point ); -} - -inline bool frustum_test_line( const Frustum& frustum, const Segment& segment ){ - return !plane3_test_line( frustum.right, segment ) - && !plane3_test_line( frustum.left, segment ) - && !plane3_test_line( frustum.bottom, segment ) - && !plane3_test_line( frustum.top, segment ) - && !plane3_test_line( frustum.back, segment ) - && !plane3_test_line( frustum.front, segment ); -} - -inline bool viewer_test_plane( const Vector4& viewer, const Plane3& plane ){ - return ( ( plane.a * viewer[0] ) - + ( plane.b * viewer[1] ) - + ( plane.c * viewer[2] ) - + ( plane.d * viewer[3] ) ) > 0; -} - -inline Vector3 triangle_cross( const Vector3& p0, const Vector3& p1, const Vector3& p2 ){ - return vector3_cross( vector3_subtracted( p1, p0 ), vector3_subtracted( p1, p2 ) ); -} - -inline bool viewer_test_triangle( const Vector4& viewer, const Vector3& p0, const Vector3& p1, const Vector3& p2 ){ - Vector3 cross( triangle_cross( p0, p1, p2 ) ); - return ( ( viewer[0] * cross[0] ) - + ( viewer[1] * cross[1] ) - + ( viewer[2] * cross[2] ) - + ( viewer[3] * 0 ) ) > 0; -} - -inline Vector4 viewer_from_transformed_viewer( const Vector4& viewer, const Matrix4& transform ){ - if ( viewer[3] == 0 ) { - return Vector4( matrix4_transformed_direction( transform, vector4_to_vector3( viewer ) ), 0 ); - } - else - { - return Vector4( matrix4_transformed_point( transform, vector4_to_vector3( viewer ) ), viewer[3] ); - } -} - -inline bool viewer_test_transformed_plane( const Vector4& viewer, const Plane3& plane, const Matrix4& localToWorld ){ -#if 0 - return viewer_test_plane( viewer_from_transformed_viewer( viewer, matrix4_affine_inverse( localToWorld ) ), plane ); -#else - return viewer_test_plane( viewer, plane3_transformed( plane, localToWorld ) ); -#endif -} - -inline Vector4 viewer_from_viewproj( const Matrix4& viewproj ){ - // get viewer pos in object coords - Vector4 viewer( matrix4_transformed_vector4( matrix4_full_inverse( viewproj ), Vector4( 0, 0, -1, 0 ) ) ); - if ( viewer[3] != 0 ) { // non-affine matrix - viewer[0] /= viewer[3]; - viewer[1] /= viewer[3]; - viewer[2] /= viewer[3]; - viewer[3] /= viewer[3]; - } - return viewer; -} - -#endif diff --git a/tools/urt/libs/math/line.cpp b/tools/urt/libs/math/line.cpp deleted file mode 100644 index a45b405..0000000 --- a/tools/urt/libs/math/line.cpp +++ /dev/null @@ -1,2 +0,0 @@ - -#include "line.h" diff --git a/tools/urt/libs/math/line.h b/tools/urt/libs/math/line.h deleted file mode 100644 index a16682b..0000000 --- a/tools/urt/libs/math/line.h +++ /dev/null @@ -1,118 +0,0 @@ - -#if !defined( INCLUDED_MATH_LINE_H ) -#define INCLUDED_MATH_LINE_H - -/// \file -/// \brief Line data types and related operations. - -#include "math/vector.h" -#include "math/plane.h" - -/// \brief A line segment defined by a start point and and end point. -class Line -{ -public: -Vector3 start, end; - -Line(){ -} -Line( const Vector3& start_, const Vector3& end_ ) : start( start_ ), end( end_ ){ -} -}; - -inline Vector3 line_closest_point( const Line& line, const Vector3& point ){ - Vector3 v = line.end - line.start; - Vector3 w = point - line.start; - - double c1 = vector3_dot( w,v ); - if ( c1 <= 0 ) { - return line.start; - } - - double c2 = vector3_dot( v,v ); - if ( c2 <= c1 ) { - return line.end; - } - - return Vector3( line.start + v * ( c1 / c2 ) ); -} - - -class Segment -{ -public: -Vector3 origin, extents; - -Segment(){ -} -Segment( const Vector3& origin_, const Vector3& extents_ ) : - origin( origin_ ), extents( extents_ ){ -} -}; - - -inline Segment segment_for_startend( const Vector3& start, const Vector3& end ){ - Segment segment; - segment.origin = vector3_mid( start, end ); - segment.extents = vector3_subtracted( end, segment.origin ); - return segment; -} - -inline unsigned int segment_classify_plane( const Segment& segment, const Plane3& plane ){ - double distance_origin = vector3_dot( plane.normal(), segment.origin ) + plane.dist(); - - if ( fabs( distance_origin ) < fabs( vector3_dot( plane.normal(), segment.extents ) ) ) { - return 1; // partially inside - } - else if ( distance_origin < 0 ) { - return 2; // totally inside - } - return 0; // totally outside -} - - -class Ray -{ -public: -Vector3 origin, direction; - -Ray(){ -} -Ray( const Vector3& origin_, const Vector3& direction_ ) : - origin( origin_ ), direction( direction_ ){ -} -}; - -inline Ray ray_for_points( const Vector3& origin, const Vector3& p2 ){ - return Ray( origin, vector3_normalised( vector3_subtracted( p2, origin ) ) ); -} - -inline void ray_transform( Ray& ray, const Matrix4& matrix ){ - matrix4_transform_point( matrix, ray.origin ); - matrix4_transform_direction( matrix, ray.direction ); -} - -// closest-point-on-line -inline double ray_squared_distance_to_point( const Ray& ray, const Vector3& point ){ - return vector3_length_squared( - vector3_subtracted( - point, - vector3_added( - ray.origin, - vector3_scaled( - ray.direction, - vector3_dot( - vector3_subtracted( point, ray.origin ), - ray.direction - ) - ) - ) - ) - ); -} - -inline double ray_distance_to_plane( const Ray& ray, const Plane3& plane ){ - return -( vector3_dot( plane.normal(), ray.origin ) - plane.dist() ) / vector3_dot( ray.direction, plane.normal() ); -} - -#endif diff --git a/tools/urt/libs/math/matrix.cpp b/tools/urt/libs/math/matrix.cpp deleted file mode 100644 index 50ba3f4..0000000 --- a/tools/urt/libs/math/matrix.cpp +++ /dev/null @@ -1,2 +0,0 @@ - -#include "matrix.h" diff --git a/tools/urt/libs/math/matrix.h b/tools/urt/libs/math/matrix.h deleted file mode 100644 index da5481e..0000000 --- a/tools/urt/libs/math/matrix.h +++ /dev/null @@ -1,1163 +0,0 @@ - -#if !defined( INCLUDED_MATH_MATRIX_H ) -#define INCLUDED_MATH_MATRIX_H - -/// \file -/// \brief Matrix data types and related operations. - -#include "math/vector.h" - -/// \brief A 4x4 matrix stored in single-precision floating-point. -class Matrix4 -{ -float m_elements[16]; -public: - -Matrix4(){ -} -Matrix4( float xx_, float xy_, float xz_, float xw_, - float yx_, float yy_, float yz_, float yw_, - float zx_, float zy_, float zz_, float zw_, - float tx_, float ty_, float tz_, float tw_ ){ - xx() = xx_; - xy() = xy_; - xz() = xz_; - xw() = xw_; - yx() = yx_; - yy() = yy_; - yz() = yz_; - yw() = yw_; - zx() = zx_; - zy() = zy_; - zz() = zz_; - zw() = zw_; - tx() = tx_; - ty() = ty_; - tz() = tz_; - tw() = tw_; -} - -float& xx(){ - return m_elements[0]; -} -const float& xx() const { - return m_elements[0]; -} -float& xy(){ - return m_elements[1]; -} -const float& xy() const { - return m_elements[1]; -} -float& xz(){ - return m_elements[2]; -} -const float& xz() const { - return m_elements[2]; -} -float& xw(){ - return m_elements[3]; -} -const float& xw() const { - return m_elements[3]; -} -float& yx(){ - return m_elements[4]; -} -const float& yx() const { - return m_elements[4]; -} -float& yy(){ - return m_elements[5]; -} -const float& yy() const { - return m_elements[5]; -} -float& yz(){ - return m_elements[6]; -} -const float& yz() const { - return m_elements[6]; -} -float& yw(){ - return m_elements[7]; -} -const float& yw() const { - return m_elements[7]; -} -float& zx(){ - return m_elements[8]; -} -const float& zx() const { - return m_elements[8]; -} -float& zy(){ - return m_elements[9]; -} -const float& zy() const { - return m_elements[9]; -} -float& zz(){ - return m_elements[10]; -} -const float& zz() const { - return m_elements[10]; -} -float& zw(){ - return m_elements[11]; -} -const float& zw() const { - return m_elements[11]; -} -float& tx(){ - return m_elements[12]; -} -const float& tx() const { - return m_elements[12]; -} -float& ty(){ - return m_elements[13]; -} -const float& ty() const { - return m_elements[13]; -} -float& tz(){ - return m_elements[14]; -} -const float& tz() const { - return m_elements[14]; -} -float& tw(){ - return m_elements[15]; -} -const float& tw() const { - return m_elements[15]; -} - -Vector4& x(){ - return reinterpret_cast( xx() ); -} -const Vector4& x() const { - return reinterpret_cast( xx() ); -} -Vector4& y(){ - return reinterpret_cast( yx() ); -} -const Vector4& y() const { - return reinterpret_cast( yx() ); -} -Vector4& z(){ - return reinterpret_cast( zx() ); -} -const Vector4& z() const { - return reinterpret_cast( zx() ); -} -Vector4& t(){ - return reinterpret_cast( tx() ); -} -const Vector4& t() const { - return reinterpret_cast( tx() ); -} - -const float& index( std::size_t i ) const { - return m_elements[i]; -} -float& index( std::size_t i ){ - return m_elements[i]; -} -const float& operator[]( std::size_t i ) const { - return m_elements[i]; -} -float& operator[]( std::size_t i ){ - return m_elements[i]; -} -const float& index( std::size_t r, std::size_t c ) const { - return m_elements[( r << 2 ) + c]; -} -float& index( std::size_t r, std::size_t c ){ - return m_elements[( r << 2 ) + c]; -} -}; - -/// \brief The 4x4 identity matrix. -const Matrix4 g_matrix4_identity( - 1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1 - ); - - -/// \brief Returns true if \p self and \p other are exactly element-wise equal. -inline bool operator==( const Matrix4& self, const Matrix4& other ){ - return self.xx() == other.xx() && self.xy() == other.xy() && self.xz() == other.xz() && self.xw() == other.xw() - && self.yx() == other.yx() && self.yy() == other.yy() && self.yz() == other.yz() && self.yw() == other.yw() - && self.zx() == other.zx() && self.zy() == other.zy() && self.zz() == other.zz() && self.zw() == other.zw() - && self.tx() == other.tx() && self.ty() == other.ty() && self.tz() == other.tz() && self.tw() == other.tw(); -} - -/// \brief Returns true if \p self and \p other are exactly element-wise equal. -inline bool matrix4_equal( const Matrix4& self, const Matrix4& other ){ - return self == other; -} - -/// \brief Returns true if \p self and \p other are element-wise equal within \p epsilon. -inline bool matrix4_equal_epsilon( const Matrix4& self, const Matrix4& other, float epsilon ){ - return float_equal_epsilon( self.xx(), other.xx(), epsilon ) - && float_equal_epsilon( self.xy(), other.xy(), epsilon ) - && float_equal_epsilon( self.xz(), other.xz(), epsilon ) - && float_equal_epsilon( self.xw(), other.xw(), epsilon ) - && float_equal_epsilon( self.yx(), other.yx(), epsilon ) - && float_equal_epsilon( self.yy(), other.yy(), epsilon ) - && float_equal_epsilon( self.yz(), other.yz(), epsilon ) - && float_equal_epsilon( self.yw(), other.yw(), epsilon ) - && float_equal_epsilon( self.zx(), other.zx(), epsilon ) - && float_equal_epsilon( self.zy(), other.zy(), epsilon ) - && float_equal_epsilon( self.zz(), other.zz(), epsilon ) - && float_equal_epsilon( self.zw(), other.zw(), epsilon ) - && float_equal_epsilon( self.tx(), other.tx(), epsilon ) - && float_equal_epsilon( self.ty(), other.ty(), epsilon ) - && float_equal_epsilon( self.tz(), other.tz(), epsilon ) - && float_equal_epsilon( self.tw(), other.tw(), epsilon ); -} - -/// \brief Returns true if \p self and \p other are exactly element-wise equal. -/// \p self and \p other must be affine. -inline bool matrix4_affine_equal( const Matrix4& self, const Matrix4& other ){ - return self[0] == other[0] - && self[1] == other[1] - && self[2] == other[2] - && self[4] == other[4] - && self[5] == other[5] - && self[6] == other[6] - && self[8] == other[8] - && self[9] == other[9] - && self[10] == other[10] - && self[12] == other[12] - && self[13] == other[13] - && self[14] == other[14]; -} - -enum Matrix4Handedness -{ - MATRIX4_RIGHTHANDED = 0, - MATRIX4_LEFTHANDED = 1, -}; - -/// \brief Returns MATRIX4_RIGHTHANDED if \p self is right-handed, else returns MATRIX4_LEFTHANDED. -inline Matrix4Handedness matrix4_handedness( const Matrix4& self ){ - return ( - vector3_dot( - vector3_cross( vector4_to_vector3( self.x() ), vector4_to_vector3( self.y() ) ), - vector4_to_vector3( self.z() ) - ) - < 0.0 - ) ? MATRIX4_LEFTHANDED : MATRIX4_RIGHTHANDED; -} - - - - - -/// \brief Returns \p self post-multiplied by \p other. -inline Matrix4 matrix4_multiplied_by_matrix4( const Matrix4& self, const Matrix4& other ){ - return Matrix4( - other[0] * self[0] + other[1] * self[4] + other[2] * self[8] + other[3] * self[12], - other[0] * self[1] + other[1] * self[5] + other[2] * self[9] + other[3] * self[13], - other[0] * self[2] + other[1] * self[6] + other[2] * self[10] + other[3] * self[14], - other[0] * self[3] + other[1] * self[7] + other[2] * self[11] + other[3] * self[15], - other[4] * self[0] + other[5] * self[4] + other[6] * self[8] + other[7] * self[12], - other[4] * self[1] + other[5] * self[5] + other[6] * self[9] + other[7] * self[13], - other[4] * self[2] + other[5] * self[6] + other[6] * self[10] + other[7] * self[14], - other[4] * self[3] + other[5] * self[7] + other[6] * self[11] + other[7] * self[15], - other[8] * self[0] + other[9] * self[4] + other[10] * self[8] + other[11] * self[12], - other[8] * self[1] + other[9] * self[5] + other[10] * self[9] + other[11] * self[13], - other[8] * self[2] + other[9] * self[6] + other[10] * self[10] + other[11] * self[14], - other[8] * self[3] + other[9] * self[7] + other[10] * self[11] + other[11] * self[15], - other[12] * self[0] + other[13] * self[4] + other[14] * self[8] + other[15] * self[12], - other[12] * self[1] + other[13] * self[5] + other[14] * self[9] + other[15] * self[13], - other[12] * self[2] + other[13] * self[6] + other[14] * self[10] + other[15] * self[14], - other[12] * self[3] + other[13] * self[7] + other[14] * self[11] + other[15] * self[15] - ); -} - -/// \brief Post-multiplies \p self by \p other in-place. -inline void matrix4_multiply_by_matrix4( Matrix4& self, const Matrix4& other ){ - self = matrix4_multiplied_by_matrix4( self, other ); -} - - -/// \brief Returns \p self pre-multiplied by \p other. -inline Matrix4 matrix4_premultiplied_by_matrix4( const Matrix4& self, const Matrix4& other ){ -#if 1 - return matrix4_multiplied_by_matrix4( other, self ); -#else - return Matrix4( - self[0] * other[0] + self[1] * other[4] + self[2] * other[8] + self[3] * other[12], - self[0] * other[1] + self[1] * other[5] + self[2] * other[9] + self[3] * other[13], - self[0] * other[2] + self[1] * other[6] + self[2] * other[10] + self[3] * other[14], - self[0] * other[3] + self[1] * other[7] + self[2] * other[11] + self[3] * other[15], - self[4] * other[0] + self[5] * other[4] + self[6] * other[8] + self[7] * other[12], - self[4] * other[1] + self[5] * other[5] + self[6] * other[9] + self[7] * other[13], - self[4] * other[2] + self[5] * other[6] + self[6] * other[10] + self[7] * other[14], - self[4] * other[3] + self[5] * other[7] + self[6] * other[11] + self[7] * other[15], - self[8] * other[0] + self[9] * other[4] + self[10] * other[8] + self[11] * other[12], - self[8] * other[1] + self[9] * other[5] + self[10] * other[9] + self[11] * other[13], - self[8] * other[2] + self[9] * other[6] + self[10] * other[10] + self[11] * other[14], - self[8] * other[3] + self[9] * other[7] + self[10] * other[11] + self[11] * other[15], - self[12] * other[0] + self[13] * other[4] + self[14] * other[8] + self[15] * other[12], - self[12] * other[1] + self[13] * other[5] + self[14] * other[9] + self[15] * other[13], - self[12] * other[2] + self[13] * other[6] + self[14] * other[10] + self[15] * other[14], - self[12] * other[3] + self[13] * other[7] + self[14] * other[11] + self[15] * other[15] - ); -#endif -} - -/// \brief Pre-multiplies \p self by \p other in-place. -inline void matrix4_premultiply_by_matrix4( Matrix4& self, const Matrix4& other ){ - self = matrix4_premultiplied_by_matrix4( self, other ); -} - -/// \brief returns true if \p transform is affine. -inline bool matrix4_is_affine( const Matrix4& transform ){ - return transform[3] == 0 && transform[7] == 0 && transform[11] == 0 && transform[15] == 1; -} - -/// \brief Returns \p self post-multiplied by \p other. -/// \p self and \p other must be affine. -inline Matrix4 matrix4_affine_multiplied_by_matrix4( const Matrix4& self, const Matrix4& other ){ - return Matrix4( - other[0] * self[0] + other[1] * self[4] + other[2] * self[8], - other[0] * self[1] + other[1] * self[5] + other[2] * self[9], - other[0] * self[2] + other[1] * self[6] + other[2] * self[10], - 0, - other[4] * self[0] + other[5] * self[4] + other[6] * self[8], - other[4] * self[1] + other[5] * self[5] + other[6] * self[9], - other[4] * self[2] + other[5] * self[6] + other[6] * self[10], - 0, - other[8] * self[0] + other[9] * self[4] + other[10] * self[8], - other[8] * self[1] + other[9] * self[5] + other[10] * self[9], - other[8] * self[2] + other[9] * self[6] + other[10] * self[10], - 0, - other[12] * self[0] + other[13] * self[4] + other[14] * self[8] + self[12], - other[12] * self[1] + other[13] * self[5] + other[14] * self[9] + self[13], - other[12] * self[2] + other[13] * self[6] + other[14] * self[10] + self[14], - 1 - ); -} - -/// \brief Post-multiplies \p self by \p other in-place. -/// \p self and \p other must be affine. -inline void matrix4_affine_multiply_by_matrix4( Matrix4& self, const Matrix4& other ){ - self = matrix4_affine_multiplied_by_matrix4( self, other ); -} - -/// \brief Returns \p self pre-multiplied by \p other. -/// \p self and \p other must be affine. -inline Matrix4 matrix4_affine_premultiplied_by_matrix4( const Matrix4& self, const Matrix4& other ){ -#if 1 - return matrix4_affine_multiplied_by_matrix4( other, self ); -#else - return Matrix4( - self[0] * other[0] + self[1] * other[4] + self[2] * other[8], - self[0] * other[1] + self[1] * other[5] + self[2] * other[9], - self[0] * other[2] + self[1] * other[6] + self[2] * other[10], - 0, - self[4] * other[0] + self[5] * other[4] + self[6] * other[8], - self[4] * other[1] + self[5] * other[5] + self[6] * other[9], - self[4] * other[2] + self[5] * other[6] + self[6] * other[10], - 0, - self[8] * other[0] + self[9] * other[4] + self[10] * other[8], - self[8] * other[1] + self[9] * other[5] + self[10] * other[9], - self[8] * other[2] + self[9] * other[6] + self[10] * other[10], - 0, - self[12] * other[0] + self[13] * other[4] + self[14] * other[8] + other[12], - self[12] * other[1] + self[13] * other[5] + self[14] * other[9] + other[13], - self[12] * other[2] + self[13] * other[6] + self[14] * other[10] + other[14], - 1 - ) - ); -#endif -} - -/// \brief Pre-multiplies \p self by \p other in-place. -/// \p self and \p other must be affine. -inline void matrix4_affine_premultiply_by_matrix4( Matrix4& self, const Matrix4& other ){ - self = matrix4_affine_premultiplied_by_matrix4( self, other ); -} - -/// \brief Returns \p point transformed by \p self. -template -inline BasicVector3 matrix4_transformed_point( const Matrix4& self, const BasicVector3& point ){ - return BasicVector3( - static_cast( self[0] * point[0] + self[4] * point[1] + self[8] * point[2] + self[12] ), - static_cast( self[1] * point[0] + self[5] * point[1] + self[9] * point[2] + self[13] ), - static_cast( self[2] * point[0] + self[6] * point[1] + self[10] * point[2] + self[14] ) - ); -} - -/// \brief Transforms \p point by \p self in-place. -template -inline void matrix4_transform_point( const Matrix4& self, BasicVector3& point ){ - point = matrix4_transformed_point( self, point ); -} - -/// \brief Returns \p vector4 transformed by \p self. -template -inline BasicVector3 matrix4_transformed_direction( const Matrix4& self, const BasicVector3& direction ){ - return BasicVector3( - static_cast( self[0] * direction[0] + self[4] * direction[1] + self[8] * direction[2] ), - static_cast( self[1] * direction[0] + self[5] * direction[1] + self[9] * direction[2] ), - static_cast( self[2] * direction[0] + self[6] * direction[1] + self[10] * direction[2] ) - ); -} - -/// \brief Transforms \p direction by \p self in-place. -template -inline void matrix4_transform_direction( const Matrix4& self, BasicVector3& normal ){ - normal = matrix4_transformed_direction( self, normal ); -} - -/// \brief Returns \p vector4 transformed by \p self. -inline Vector4 matrix4_transformed_vector4( const Matrix4& self, const Vector4& vector4 ){ - return Vector4( - self[0] * vector4[0] + self[4] * vector4[1] + self[8] * vector4[2] + self[12] * vector4[3], - self[1] * vector4[0] + self[5] * vector4[1] + self[9] * vector4[2] + self[13] * vector4[3], - self[2] * vector4[0] + self[6] * vector4[1] + self[10] * vector4[2] + self[14] * vector4[3], - self[3] * vector4[0] + self[7] * vector4[1] + self[11] * vector4[2] + self[15] * vector4[3] - ); -} - -/// \brief Transforms \p vector4 by \p self in-place. -inline void matrix4_transform_vector4( const Matrix4& self, Vector4& vector4 ){ - vector4 = matrix4_transformed_vector4( self, vector4 ); -} - - -/// \brief Transposes \p self in-place. -inline void matrix4_transpose( Matrix4& self ){ - std::swap( self.xy(), self.yx() ); - std::swap( self.xz(), self.zx() ); - std::swap( self.xw(), self.tx() ); - std::swap( self.yz(), self.zy() ); - std::swap( self.yw(), self.ty() ); - std::swap( self.zw(), self.tz() ); -} - -/// \brief Returns \p self transposed. -inline Matrix4 matrix4_transposed( const Matrix4& self ){ - return Matrix4( - self.xx(), - self.yx(), - self.zx(), - self.tx(), - self.xy(), - self.yy(), - self.zy(), - self.ty(), - self.xz(), - self.yz(), - self.zz(), - self.tz(), - self.xw(), - self.yw(), - self.zw(), - self.tw() - ); -} - - -/// \brief Inverts an affine transform in-place. -/// Adapted from Graphics Gems 2. -inline void matrix4_affine_invert( Matrix4& self ){ - Matrix4 other( self ); - - // determinant of rotation submatrix - float det - = other[0] * ( other[5] * other[10] - other[9] * other[6] ) - - other[1] * ( other[4] * other[10] - other[8] * other[6] ) - + other[2] * ( other[4] * other[9] - other[8] * other[5] ); - - // throw exception here if (det*det < 1e-25) - - // invert rotation submatrix - det = 1.0f / det; - self[0] = ( ( other[5] * other[10] - other[6] * other[9] ) * det ); - self[1] = ( -( other[1] * other[10] - other[2] * other[9] ) * det ); - self[2] = ( ( other[1] * other[6] - other[2] * other[5] ) * det ); - self[4] = ( -( other[4] * other[10] - other[6] * other[8] ) * det ); - self[5] = ( ( other[0] * other[10] - other[2] * other[8] ) * det ); - self[6] = ( -( other[0] * other[6] - other[2] * other[4] ) * det ); - self[8] = ( ( other[4] * other[9] - other[5] * other[8] ) * det ); - self[9] = ( -( other[0] * other[9] - other[1] * other[8] ) * det ); - self[10] = ( ( other[0] * other[5] - other[1] * other[4] ) * det ); - - // multiply translation part by rotation - self[12] = -( other[12] * self[0] + - other[13] * self[4] + - other[14] * self[8] ); - self[13] = -( other[12] * self[1] + - other[13] * self[5] + - other[14] * self[9] ); - self[14] = -( other[12] * self[2] + - other[13] * self[6] + - other[14] * self[10] ); -} - -/// \brief A compile-time-constant integer. -template -struct ct_int -{ - enum { value = Value }; -}; - -/// \brief A compile-time-constant row/column index into a 4x4 matrix. -template -class Matrix4Index -{ -public: -typedef ct_int r; -typedef ct_int c; -typedef ct_int<( r::value * 4 ) + c::value> i; -}; - -/// \brief A functor which returns the cofactor of a 3x3 submatrix obtained by ignoring a given row and column of a 4x4 matrix. -/// \param Row Defines the compile-time-constant integers x, y and z with values corresponding to the indices of the three rows to use. -/// \param Col Defines the compile-time-constant integers x, y and z with values corresponding to the indices of the three columns to use. -template -class Matrix4Cofactor -{ -public: -typedef typename Matrix4Index::i xx; -typedef typename Matrix4Index::i xy; -typedef typename Matrix4Index::i xz; -typedef typename Matrix4Index::i yx; -typedef typename Matrix4Index::i yy; -typedef typename Matrix4Index::i yz; -typedef typename Matrix4Index::i zx; -typedef typename Matrix4Index::i zy; -typedef typename Matrix4Index::i zz; -static double apply( const Matrix4& self ){ - return self[xx::value] * ( self[yy::value] * self[zz::value] - self[zy::value] * self[yz::value] ) - - self[xy::value] * ( self[yx::value] * self[zz::value] - self[zx::value] * self[yz::value] ) - + self[xz::value] * ( self[yx::value] * self[zy::value] - self[zx::value] * self[yy::value] ); -} -}; - -/// \brief The cofactor element indices for a 4x4 matrix row or column. -/// \param Element The index of the element to ignore. -template -class Cofactor4 -{ -public: -typedef ct_int<( Element <= 0 ) ? 1 : 0> x; -typedef ct_int<( Element <= 1 ) ? 2 : 1> y; -typedef ct_int<( Element <= 2 ) ? 3 : 2> z; -}; - -/// \brief Returns the determinant of \p self. -inline double matrix4_determinant( const Matrix4& self ){ - return self.xx() * Matrix4Cofactor< Cofactor4<0>, Cofactor4<0> >::apply( self ) - - self.xy() * Matrix4Cofactor< Cofactor4<0>, Cofactor4<1> >::apply( self ) - + self.xz() * Matrix4Cofactor< Cofactor4<0>, Cofactor4<2> >::apply( self ) - - self.xw() * Matrix4Cofactor< Cofactor4<0>, Cofactor4<3> >::apply( self ); -} - -/// \brief Returns the inverse of \p self using the Adjoint method. -/// \todo Throw an exception if the determinant is zero. -inline Matrix4 matrix4_full_inverse( const Matrix4& self ){ - double determinant = 1.0 / matrix4_determinant( self ); - - return Matrix4( - static_cast( Matrix4Cofactor< Cofactor4<0>, Cofactor4<0> >::apply( self ) * determinant ), - static_cast( -Matrix4Cofactor< Cofactor4<1>, Cofactor4<0> >::apply( self ) * determinant ), - static_cast( Matrix4Cofactor< Cofactor4<2>, Cofactor4<0> >::apply( self ) * determinant ), - static_cast( -Matrix4Cofactor< Cofactor4<3>, Cofactor4<0> >::apply( self ) * determinant ), - static_cast( -Matrix4Cofactor< Cofactor4<0>, Cofactor4<1> >::apply( self ) * determinant ), - static_cast( Matrix4Cofactor< Cofactor4<1>, Cofactor4<1> >::apply( self ) * determinant ), - static_cast( -Matrix4Cofactor< Cofactor4<2>, Cofactor4<1> >::apply( self ) * determinant ), - static_cast( Matrix4Cofactor< Cofactor4<3>, Cofactor4<1> >::apply( self ) * determinant ), - static_cast( Matrix4Cofactor< Cofactor4<0>, Cofactor4<2> >::apply( self ) * determinant ), - static_cast( -Matrix4Cofactor< Cofactor4<1>, Cofactor4<2> >::apply( self ) * determinant ), - static_cast( Matrix4Cofactor< Cofactor4<2>, Cofactor4<2> >::apply( self ) * determinant ), - static_cast( -Matrix4Cofactor< Cofactor4<3>, Cofactor4<2> >::apply( self ) * determinant ), - static_cast( -Matrix4Cofactor< Cofactor4<0>, Cofactor4<3> >::apply( self ) * determinant ), - static_cast( Matrix4Cofactor< Cofactor4<1>, Cofactor4<3> >::apply( self ) * determinant ), - static_cast( -Matrix4Cofactor< Cofactor4<2>, Cofactor4<3> >::apply( self ) * determinant ), - static_cast( Matrix4Cofactor< Cofactor4<3>, Cofactor4<3> >::apply( self ) * determinant ) - ); -} - -/// \brief Inverts \p self in-place using the Adjoint method. -inline void matrix4_full_invert( Matrix4& self ){ - self = matrix4_full_inverse( self ); -} - - -/// \brief Constructs a pure-translation matrix from \p translation. -inline Matrix4 matrix4_translation_for_vec3( const Vector3& translation ){ - return Matrix4( - 1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 1, 0, - translation[0], translation[1], translation[2], 1 - ); -} - -/// \brief Returns the translation part of \p self. -inline Vector3 matrix4_get_translation_vec3( const Matrix4& self ){ - return vector4_to_vector3( self.t() ); -} - -/// \brief Concatenates \p self with \p translation. -/// The concatenated \p translation occurs before \p self. -inline void matrix4_translate_by_vec3( Matrix4& self, const Vector3& translation ){ - matrix4_multiply_by_matrix4( self, matrix4_translation_for_vec3( translation ) ); -} - -/// \brief Returns \p self Concatenated with \p translation. -/// The concatenated translation occurs before \p self. -inline Matrix4 matrix4_translated_by_vec3( const Matrix4& self, const Vector3& translation ){ - return matrix4_multiplied_by_matrix4( self, matrix4_translation_for_vec3( translation ) ); -} - - -#include "math/pi.h" - -/// \brief Returns \p angle modulated by the range [0, 360). -/// \p angle must be in the range [-360, 360). -inline float angle_modulate_degrees_range( float angle ){ - return static_cast( float_mod_range( angle, 360.0 ) ); -} - -/// \brief Returns \p euler angles converted from radians to degrees. -inline Vector3 euler_radians_to_degrees( const Vector3& euler ){ - return Vector3( - static_cast( radians_to_degrees( euler.x() ) ), - static_cast( radians_to_degrees( euler.y() ) ), - static_cast( radians_to_degrees( euler.z() ) ) - ); -} - -/// \brief Returns \p euler angles converted from degrees to radians. -inline Vector3 euler_degrees_to_radians( const Vector3& euler ){ - return Vector3( - static_cast( degrees_to_radians( euler.x() ) ), - static_cast( degrees_to_radians( euler.y() ) ), - static_cast( degrees_to_radians( euler.z() ) ) - ); -} - - - -/// \brief Constructs a pure-rotation matrix about the x axis from sin \p s and cosine \p c of an angle. -inline Matrix4 matrix4_rotation_for_sincos_x( float s, float c ){ - return Matrix4( - 1, 0, 0, 0, - 0, c, s, 0, - 0,-s, c, 0, - 0, 0, 0, 1 - ); -} - -/// \brief Constructs a pure-rotation matrix about the x axis from an angle in radians. -inline Matrix4 matrix4_rotation_for_x( double x ){ - return matrix4_rotation_for_sincos_x( static_cast( sin( x ) ), static_cast( cos( x ) ) ); -} - -/// \brief Constructs a pure-rotation matrix about the x axis from an angle in degrees. -inline Matrix4 matrix4_rotation_for_x_degrees( float x ){ - return matrix4_rotation_for_x( degrees_to_radians( x ) ); -} - -/// \brief Constructs a pure-rotation matrix about the y axis from sin \p s and cosine \p c of an angle. -inline Matrix4 matrix4_rotation_for_sincos_y( float s, float c ){ - return Matrix4( - c, 0,-s, 0, - 0, 1, 0, 0, - s, 0, c, 0, - 0, 0, 0, 1 - ); -} - -/// \brief Constructs a pure-rotation matrix about the y axis from an angle in radians. -inline Matrix4 matrix4_rotation_for_y( double y ){ - return matrix4_rotation_for_sincos_y( static_cast( sin( y ) ), static_cast( cos( y ) ) ); -} - -/// \brief Constructs a pure-rotation matrix about the y axis from an angle in degrees. -inline Matrix4 matrix4_rotation_for_y_degrees( float y ){ - return matrix4_rotation_for_y( degrees_to_radians( y ) ); -} - -/// \brief Constructs a pure-rotation matrix about the z axis from sin \p s and cosine \p c of an angle. -inline Matrix4 matrix4_rotation_for_sincos_z( float s, float c ){ - return Matrix4( - c, s, 0, 0, - -s, c, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1 - ); -} - -/// \brief Constructs a pure-rotation matrix about the z axis from an angle in radians. -inline Matrix4 matrix4_rotation_for_z( double z ){ - return matrix4_rotation_for_sincos_z( static_cast( sin( z ) ), static_cast( cos( z ) ) ); -} - -/// \brief Constructs a pure-rotation matrix about the z axis from an angle in degrees. -inline Matrix4 matrix4_rotation_for_z_degrees( float z ){ - return matrix4_rotation_for_z( degrees_to_radians( z ) ); -} - -/// \brief Constructs a pure-rotation matrix from a set of euler angles (radians) in the order (x, y, z). -/*! \verbatim - clockwise rotation around X, Y, Z, facing along axis - 1 0 0 cy 0 -sy cz sz 0 - 0 cx sx 0 1 0 -sz cz 0 - 0 -sx cx sy 0 cy 0 0 1 - - rows of Z by cols of Y - cy*cz -sy*cz+sz -sy*sz+cz - -sz*cy -sz*sy+cz - - .. or something like that.. - - final rotation is Z * Y * X - cy*cz -sx*-sy*cz+cx*sz cx*-sy*sz+sx*cz - -cy*sz sx*sy*sz+cx*cz -cx*-sy*sz+sx*cz - sy -sx*cy cx*cy - - transposed - cy.cz + 0.sz + sy.0 cy.-sz + 0 .cz + sy.0 cy.0 + 0 .0 + sy.1 | - sx.sy.cz + cx.sz + -sx.cy.0 sx.sy.-sz + cx.cz + -sx.cy.0 sx.sy.0 + cx.0 + -sx.cy.1 | - -cx.sy.cz + sx.sz + cx.cy.0 -cx.sy.-sz + sx.cz + cx.cy.0 -cx.sy.0 + 0 .0 + cx.cy.1 | - \endverbatim */ -inline Matrix4 matrix4_rotation_for_euler_xyz( const Vector3& euler ){ -#if 1 - - double cx = cos( euler[0] ); - double sx = sin( euler[0] ); - double cy = cos( euler[1] ); - double sy = sin( euler[1] ); - double cz = cos( euler[2] ); - double sz = sin( euler[2] ); - - return Matrix4( - static_cast( cy * cz ), - static_cast( cy * sz ), - static_cast( -sy ), - 0, - static_cast( sx * sy * cz + cx * -sz ), - static_cast( sx * sy * sz + cx * cz ), - static_cast( sx * cy ), - 0, - static_cast( cx * sy * cz + sx * sz ), - static_cast( cx * sy * sz + -sx * cz ), - static_cast( cx * cy ), - 0, - 0, - 0, - 0, - 1 - ); - -#else - - return matrix4_premultiply_by_matrix4( - matrix4_premultiply_by_matrix4( - matrix4_rotation_for_x( euler[0] ), - matrix4_rotation_for_y( euler[1] ) - ), - matrix4_rotation_for_z( euler[2] ) - ); - -#endif -} - -/// \brief Constructs a pure-rotation matrix from a set of euler angles (degrees) in the order (x, y, z). -inline Matrix4 matrix4_rotation_for_euler_xyz_degrees( const Vector3& euler ){ - return matrix4_rotation_for_euler_xyz( euler_degrees_to_radians( euler ) ); -} - -/// \brief Concatenates \p self with the rotation transform produced by \p euler angles (degrees) in the order (x, y, z). -/// The concatenated rotation occurs before \p self. -inline void matrix4_rotate_by_euler_xyz_degrees( Matrix4& self, const Vector3& euler ){ - matrix4_multiply_by_matrix4( self, matrix4_rotation_for_euler_xyz_degrees( euler ) ); -} - - -/// \brief Constructs a pure-rotation matrix from a set of euler angles (radians) in the order (y, z, x). -inline Matrix4 matrix4_rotation_for_euler_yzx( const Vector3& euler ){ - return matrix4_premultiplied_by_matrix4( - matrix4_premultiplied_by_matrix4( - matrix4_rotation_for_y( euler[1] ), - matrix4_rotation_for_z( euler[2] ) - ), - matrix4_rotation_for_x( euler[0] ) - ); -} - -/// \brief Constructs a pure-rotation matrix from a set of euler angles (degrees) in the order (y, z, x). -inline Matrix4 matrix4_rotation_for_euler_yzx_degrees( const Vector3& euler ){ - return matrix4_rotation_for_euler_yzx( euler_degrees_to_radians( euler ) ); -} - -/// \brief Constructs a pure-rotation matrix from a set of euler angles (radians) in the order (x, z, y). -inline Matrix4 matrix4_rotation_for_euler_xzy( const Vector3& euler ){ - return matrix4_premultiplied_by_matrix4( - matrix4_premultiplied_by_matrix4( - matrix4_rotation_for_x( euler[0] ), - matrix4_rotation_for_z( euler[2] ) - ), - matrix4_rotation_for_y( euler[1] ) - ); -} - -/// \brief Constructs a pure-rotation matrix from a set of euler angles (degrees) in the order (x, z, y). -inline Matrix4 matrix4_rotation_for_euler_xzy_degrees( const Vector3& euler ){ - return matrix4_rotation_for_euler_xzy( euler_degrees_to_radians( euler ) ); -} - -/// \brief Constructs a pure-rotation matrix from a set of euler angles (radians) in the order (y, x, z). -/*! \verbatim - | cy.cz + sx.sy.-sz + -cx.sy.0 0.cz + cx.-sz + sx.0 sy.cz + -sx.cy.-sz + cx.cy.0 | - | cy.sz + sx.sy.cz + -cx.sy.0 0.sz + cx.cz + sx.0 sy.sz + -sx.cy.cz + cx.cy.0 | - | cy.0 + sx.sy.0 + -cx.sy.1 0.0 + cx.0 + sx.1 sy.0 + -sx.cy.0 + cx.cy.1 | - \endverbatim */ -inline Matrix4 matrix4_rotation_for_euler_yxz( const Vector3& euler ){ -#if 1 - - double cx = cos( euler[0] ); - double sx = sin( euler[0] ); - double cy = cos( euler[1] ); - double sy = sin( euler[1] ); - double cz = cos( euler[2] ); - double sz = sin( euler[2] ); - - return Matrix4( - static_cast( cy * cz + sx * sy * -sz ), - static_cast( cy * sz + sx * sy * cz ), - static_cast( -cx * sy ), - 0, - static_cast( cx * -sz ), - static_cast( cx * cz ), - static_cast( sx ), - 0, - static_cast( sy * cz + -sx * cy * -sz ), - static_cast( sy * sz + -sx * cy * cz ), - static_cast( cx * cy ), - 0, - 0, - 0, - 0, - 1 - ); - -#else - - return matrix4_premultiply_by_matrix4( - matrix4_premultiply_by_matrix4( - matrix4_rotation_for_y( euler[1] ), - matrix4_rotation_for_x( euler[0] ) - ), - matrix4_rotation_for_z( euler[2] ) - ); - -#endif -} - -/// \brief Constructs a pure-rotation matrix from a set of euler angles (degrees) in the order (y, x, z). -inline Matrix4 matrix4_rotation_for_euler_yxz_degrees( const Vector3& euler ){ - return matrix4_rotation_for_euler_yxz( euler_degrees_to_radians( euler ) ); -} - -/// \brief Returns \p self concatenated with the rotation transform produced by \p euler angles (degrees) in the order (y, x, z). -/// The concatenated rotation occurs before \p self. -inline Matrix4 matrix4_rotated_by_euler_yxz_degrees( const Matrix4& self, const Vector3& euler ){ - return matrix4_multiplied_by_matrix4( self, matrix4_rotation_for_euler_yxz_degrees( euler ) ); -} - -/// \brief Concatenates \p self with the rotation transform produced by \p euler angles (degrees) in the order (y, x, z). -/// The concatenated rotation occurs before \p self. -inline void matrix4_rotate_by_euler_yxz_degrees( Matrix4& self, const Vector3& euler ){ - self = matrix4_rotated_by_euler_yxz_degrees( self, euler ); -} - -/// \brief Constructs a pure-rotation matrix from a set of euler angles (radians) in the order (z, x, y). -inline Matrix4 matrix4_rotation_for_euler_zxy( const Vector3& euler ){ -#if 1 - return matrix4_premultiplied_by_matrix4( - matrix4_premultiplied_by_matrix4( - matrix4_rotation_for_z( euler[2] ), - matrix4_rotation_for_x( euler[0] ) - ), - matrix4_rotation_for_y( euler[1] ) - ); -#else - double cx = cos( euler[0] ); - double sx = sin( euler[0] ); - double cy = cos( euler[1] ); - double sy = sin( euler[1] ); - double cz = cos( euler[2] ); - double sz = sin( euler[2] ); - - return Matrix4( - static_cast( cz * cy + sz * sx * sy ), - static_cast( sz * cx ), - static_cast( cz * -sy + sz * sx * cy ), - 0, - static_cast( -sz * cy + cz * sx * sy ), - static_cast( cz * cx ), - static_cast( -sz * -sy + cz * cx * cy ), - 0, - static_cast( cx * sy ), - static_cast( -sx ), - static_cast( cx * cy ), - 0, - 0, - 0, - 0, - 1 - ); -#endif -} - -/// \brief Constructs a pure-rotation matrix from a set of euler angles (degres=es) in the order (z, x, y). -inline Matrix4 matrix4_rotation_for_euler_zxy_degrees( const Vector3& euler ){ - return matrix4_rotation_for_euler_zxy( euler_degrees_to_radians( euler ) ); -} - -/// \brief Returns \p self concatenated with the rotation transform produced by \p euler angles (degrees) in the order (z, x, y). -/// The concatenated rotation occurs before \p self. -inline Matrix4 matrix4_rotated_by_euler_zxy_degrees( const Matrix4& self, const Vector3& euler ){ - return matrix4_multiplied_by_matrix4( self, matrix4_rotation_for_euler_zxy_degrees( euler ) ); -} - -/// \brief Concatenates \p self with the rotation transform produced by \p euler angles (degrees) in the order (z, x, y). -/// The concatenated rotation occurs before \p self. -inline void matrix4_rotate_by_euler_zxy_degrees( Matrix4& self, const Vector3& euler ){ - self = matrix4_rotated_by_euler_zxy_degrees( self, euler ); -} - -/// \brief Constructs a pure-rotation matrix from a set of euler angles (radians) in the order (z, y, x). -inline Matrix4 matrix4_rotation_for_euler_zyx( const Vector3& euler ){ -#if 1 - - double cx = cos( euler[0] ); - double sx = sin( euler[0] ); - double cy = cos( euler[1] ); - double sy = sin( euler[1] ); - double cz = cos( euler[2] ); - double sz = sin( euler[2] ); - - return Matrix4( - static_cast( cy * cz ), - static_cast( sx * sy * cz + cx * sz ), - static_cast( cx * -sy * cz + sx * sz ), - 0, - static_cast( cy * -sz ), - static_cast( sx * sy * -sz + cx * cz ), - static_cast( cx * -sy * -sz + sx * cz ), - 0, - static_cast( sy ), - static_cast( -sx * cy ), - static_cast( cx * cy ), - 0, - 0, - 0, - 0, - 1 - ); - -#else - - return matrix4_premultiply_by_matrix4( - matrix4_premultiply_by_matrix4( - matrix4_rotation_for_z( euler[2] ), - matrix4_rotation_for_y( euler[1] ) - ), - matrix4_rotation_for_x( euler[0] ) - ); - -#endif -} - -/// \brief Constructs a pure-rotation matrix from a set of euler angles (degrees) in the order (z, y, x). -inline Matrix4 matrix4_rotation_for_euler_zyx_degrees( const Vector3& euler ){ - return matrix4_rotation_for_euler_zyx( euler_degrees_to_radians( euler ) ); -} - - -/// \brief Calculates and returns a set of euler angles that produce the rotation component of \p self when applied in the order (x, y, z). -/// \p self must be affine and orthonormal (unscaled) to produce a meaningful result. -inline Vector3 matrix4_get_rotation_euler_xyz( const Matrix4& self ){ - double a = asin( -self[2] ); - double ca = cos( a ); - - if ( fabs( ca ) > 0.005 ) { // Gimbal lock? - return Vector3( - static_cast( atan2( self[6] / ca, self[10] / ca ) ), - static_cast( a ), - static_cast( atan2( self[1] / ca, self[0] / ca ) ) - ); - } - else // Gimbal lock has occurred - { - return Vector3( - static_cast( atan2( -self[9], self[5] ) ), - static_cast( a ), - 0 - ); - } -} - -/// \brief \copydoc matrix4_get_rotation_euler_xyz(const Matrix4&) -inline Vector3 matrix4_get_rotation_euler_xyz_degrees( const Matrix4& self ){ - return euler_radians_to_degrees( matrix4_get_rotation_euler_xyz( self ) ); -} - -/// \brief Calculates and returns a set of euler angles that produce the rotation component of \p self when applied in the order (y, x, z). -/// \p self must be affine and orthonormal (unscaled) to produce a meaningful result. -inline Vector3 matrix4_get_rotation_euler_yxz( const Matrix4& self ){ - double a = asin( self[6] ); - double ca = cos( a ); - - if ( fabs( ca ) > 0.005 ) { // Gimbal lock? - return Vector3( - static_cast( a ), - static_cast( atan2( -self[2] / ca, self[10] / ca ) ), - static_cast( atan2( -self[4] / ca, self[5] / ca ) ) - ); - } - else // Gimbal lock has occurred - { - return Vector3( - static_cast( a ), - static_cast( atan2( self[8], self[0] ) ), - 0 - ); - } -} - -/// \brief \copydoc matrix4_get_rotation_euler_yxz(const Matrix4&) -inline Vector3 matrix4_get_rotation_euler_yxz_degrees( const Matrix4& self ){ - return euler_radians_to_degrees( matrix4_get_rotation_euler_yxz( self ) ); -} - -/// \brief Calculates and returns a set of euler angles that produce the rotation component of \p self when applied in the order (z, x, y). -/// \p self must be affine and orthonormal (unscaled) to produce a meaningful result. -inline Vector3 matrix4_get_rotation_euler_zxy( const Matrix4& self ){ - double a = asin( -self[9] ); - double ca = cos( a ); - - if ( fabs( ca ) > 0.005 ) { // Gimbal lock? - return Vector3( - static_cast( a ), - static_cast( atan2( self[8] / ca, self[10] / ca ) ), - static_cast( atan2( self[1] / ca, self[5] / ca ) ) - ); - } - else // Gimbal lock has occurred - { - return Vector3( - static_cast( a ), - 0, - static_cast( atan2( -self[4], self[0] ) ) - ); - } -} - -/// \brief \copydoc matrix4_get_rotation_euler_zxy(const Matrix4&) -inline Vector3 matrix4_get_rotation_euler_zxy_degrees( const Matrix4& self ){ - return euler_radians_to_degrees( matrix4_get_rotation_euler_zxy( self ) ); -} - -/// \brief Calculates and returns a set of euler angles that produce the rotation component of \p self when applied in the order (z, y, x). -/// \p self must be affine and orthonormal (unscaled) to produce a meaningful result. -inline Vector3 matrix4_get_rotation_euler_zyx( const Matrix4& self ){ - double a = asin( self[8] ); - double ca = cos( a ); - - if ( fabs( ca ) > 0.005 ) { // Gimbal lock? - return Vector3( - static_cast( atan2( -self[9] / ca, self[10] / ca ) ), - static_cast( a ), - static_cast( atan2( -self[4] / ca, self[0] / ca ) ) - ); - } - else // Gimbal lock has occurred - { - return Vector3( - 0, - static_cast( a ), - static_cast( atan2( self[1], self[5] ) ) - ); - } -} - -/// \brief \copydoc matrix4_get_rotation_euler_zyx(const Matrix4&) -inline Vector3 matrix4_get_rotation_euler_zyx_degrees( const Matrix4& self ){ - return euler_radians_to_degrees( matrix4_get_rotation_euler_zyx( self ) ); -} - - -/// \brief Rotate \p self by \p euler angles (degrees) applied in the order (x, y, z), using \p pivotpoint. -inline void matrix4_pivoted_rotate_by_euler_xyz_degrees( Matrix4& self, const Vector3& euler, const Vector3& pivotpoint ){ - matrix4_translate_by_vec3( self, pivotpoint ); - matrix4_rotate_by_euler_xyz_degrees( self, euler ); - matrix4_translate_by_vec3( self, vector3_negated( pivotpoint ) ); -} - - -/// \brief Constructs a pure-scale matrix from \p scale. -inline Matrix4 matrix4_scale_for_vec3( const Vector3& scale ){ - return Matrix4( - scale[0], 0, 0, 0, - 0, scale[1], 0, 0, - 0, 0, scale[2], 0, - 0, 0, 0, 1 - ); -} - -/// \brief Calculates and returns the (x, y, z) scale values that produce the scale component of \p self. -/// \p self must be affine and orthogonal to produce a meaningful result. -inline Vector3 matrix4_get_scale_vec3( const Matrix4& self ){ - return Vector3( - static_cast( vector3_length( vector4_to_vector3( self.x() ) ) ), - static_cast( vector3_length( vector4_to_vector3( self.y() ) ) ), - static_cast( vector3_length( vector4_to_vector3( self.z() ) ) ) - ); -} - -/// \brief Scales \p self by \p scale. -inline void matrix4_scale_by_vec3( Matrix4& self, const Vector3& scale ){ - matrix4_multiply_by_matrix4( self, matrix4_scale_for_vec3( scale ) ); -} - -/// \brief Scales \p self by \p scale, using \p pivotpoint. -inline void matrix4_pivoted_scale_by_vec3( Matrix4& self, const Vector3& scale, const Vector3& pivotpoint ){ - matrix4_translate_by_vec3( self, pivotpoint ); - matrix4_scale_by_vec3( self, scale ); - matrix4_translate_by_vec3( self, vector3_negated( pivotpoint ) ); -} - - -/// \brief Transforms \p self by \p translation, \p euler and \p scale. -/// The transforms are combined in the order: scale, rotate-z, rotate-y, rotate-x, translate. -inline void matrix4_transform_by_euler_xyz_degrees( Matrix4& self, const Vector3& translation, const Vector3& euler, const Vector3& scale ){ - matrix4_translate_by_vec3( self, translation ); - matrix4_rotate_by_euler_xyz_degrees( self, euler ); - matrix4_scale_by_vec3( self, scale ); -} - -/// \brief Transforms \p self by \p translation, \p euler and \p scale, using \p pivotpoint. -inline void matrix4_pivoted_transform_by_euler_xyz_degrees( Matrix4& self, const Vector3& translation, const Vector3& euler, const Vector3& scale, const Vector3& pivotpoint ){ - matrix4_translate_by_vec3( self, pivotpoint + translation ); - matrix4_rotate_by_euler_xyz_degrees( self, euler ); - matrix4_scale_by_vec3( self, scale ); - matrix4_translate_by_vec3( self, vector3_negated( pivotpoint ) ); -} - - -#endif diff --git a/tools/urt/libs/math/pi.cpp b/tools/urt/libs/math/pi.cpp deleted file mode 100644 index aebe712..0000000 --- a/tools/urt/libs/math/pi.cpp +++ /dev/null @@ -1,2 +0,0 @@ - -#include "pi.h" diff --git a/tools/urt/libs/math/pi.h b/tools/urt/libs/math/pi.h deleted file mode 100644 index 8ac189c..0000000 --- a/tools/urt/libs/math/pi.h +++ /dev/null @@ -1,23 +0,0 @@ - -#if !defined( INCLUDED_MATH_PI_H ) -#define INCLUDED_MATH_PI_H - -/// \file -/// \brief Pi constants and degrees/radians conversion. - -const double c_pi = 3.1415926535897932384626433832795; -const double c_half_pi = c_pi / 2; -const double c_2pi = 2 * c_pi; -const double c_inv_2pi = 1 / c_2pi; - -const double c_DEG2RADMULT = c_pi / 180.0; -const double c_RAD2DEGMULT = 180.0 / c_pi; - -inline double radians_to_degrees( double radians ){ - return radians * c_RAD2DEGMULT; -} -inline double degrees_to_radians( double degrees ){ - return degrees * c_DEG2RADMULT; -} - -#endif diff --git a/tools/urt/libs/math/plane.cpp b/tools/urt/libs/math/plane.cpp deleted file mode 100644 index 95c7702..0000000 --- a/tools/urt/libs/math/plane.cpp +++ /dev/null @@ -1,2 +0,0 @@ - -#include "plane.h" diff --git a/tools/urt/libs/math/plane.h b/tools/urt/libs/math/plane.h deleted file mode 100644 index 72db71f..0000000 --- a/tools/urt/libs/math/plane.h +++ /dev/null @@ -1,116 +0,0 @@ - -#if !defined( INCLUDED_MATH_PLANE_H ) -#define INCLUDED_MATH_PLANE_H - -/// \file -/// \brief Plane data types and related operations. - -#include "math/matrix.h" - -/// \brief A plane equation stored in double-precision floating-point. -class Plane3 -{ -public: -double a, b, c, d; - -Plane3(){ -} -Plane3( double _a, double _b, double _c, double _d ) - : a( _a ), b( _b ), c( _c ), d( _d ){ -} -template -Plane3( const BasicVector3& normal, double dist ) - : a( normal.x() ), b( normal.y() ), c( normal.z() ), d( dist ){ -} - -BasicVector3& normal(){ - return reinterpret_cast&>( *this ); -} -const BasicVector3& normal() const { - return reinterpret_cast&>( *this ); -} -double& dist(){ - return d; -} -const double& dist() const { - return d; -} -}; - -inline Plane3 plane3_normalised( const Plane3& plane ){ - double rmagnitude = 1.0 / sqrt( plane.a * plane.a + plane.b * plane.b + plane.c * plane.c ); - return Plane3( - plane.a * rmagnitude, - plane.b * rmagnitude, - plane.c * rmagnitude, - plane.d * rmagnitude - ); -} - -inline Plane3 plane3_translated( const Plane3& plane, const Vector3& translation ){ - Plane3 transformed; - transformed.a = plane.a; - transformed.b = plane.b; - transformed.c = plane.c; - transformed.d = -( ( -plane.d * transformed.a + translation.x() ) * transformed.a + - ( -plane.d * transformed.b + translation.y() ) * transformed.b + - ( -plane.d * transformed.c + translation.z() ) * transformed.c ); - return transformed; -} - -inline Plane3 plane3_transformed( const Plane3& plane, const Matrix4& transform ){ - Plane3 transformed; - transformed.a = transform[0] * plane.a + transform[4] * plane.b + transform[8] * plane.c; - transformed.b = transform[1] * plane.a + transform[5] * plane.b + transform[9] * plane.c; - transformed.c = transform[2] * plane.a + transform[6] * plane.b + transform[10] * plane.c; - transformed.d = -( ( -plane.d * transformed.a + transform[12] ) * transformed.a + - ( -plane.d * transformed.b + transform[13] ) * transformed.b + - ( -plane.d * transformed.c + transform[14] ) * transformed.c ); - return transformed; -} - -inline Plane3 plane3_inverse_transformed( const Plane3& plane, const Matrix4& transform ){ - return Plane3 - ( - transform[ 0] * plane.a + transform[ 1] * plane.b + transform[ 2] * plane.c + transform[ 3] * plane.d, - transform[ 4] * plane.a + transform[ 5] * plane.b + transform[ 6] * plane.c + transform[ 7] * plane.d, - transform[ 8] * plane.a + transform[ 9] * plane.b + transform[10] * plane.c + transform[11] * plane.d, - transform[12] * plane.a + transform[13] * plane.b + transform[14] * plane.c + transform[15] * plane.d - ); -} - -inline Plane3 plane3_flipped( const Plane3& plane ){ - return Plane3( vector3_negated( plane.normal() ), -plane.dist() ); -} - -const double c_PLANE_NORMAL_EPSILON = 0.0001f; -const double c_PLANE_DIST_EPSILON = 0.02; - -inline bool plane3_equal( const Plane3& self, const Plane3& other ){ - return vector3_equal_epsilon( self.normal(), other.normal(), c_PLANE_NORMAL_EPSILON ) - && float_equal_epsilon( self.dist(), other.dist(), c_PLANE_DIST_EPSILON ); -} - -inline bool plane3_opposing( const Plane3& self, const Plane3& other ){ - return plane3_equal( self, plane3_flipped( other ) ); -} - -inline bool plane3_valid( const Plane3& self ){ - return float_equal_epsilon( vector3_dot( self.normal(), self.normal() ), 1.0, 0.01 ); -} - -template -inline Plane3 plane3_for_points( const BasicVector3& p0, const BasicVector3& p1, const BasicVector3& p2 ){ - Plane3 self; - self.normal() = vector3_normalised( vector3_cross( vector3_subtracted( p1, p0 ), vector3_subtracted( p2, p0 ) ) ); - self.dist() = vector3_dot( p0, self.normal() ); - return self; -} - -template -inline Plane3 plane3_for_points( const BasicVector3 planepts[3] ){ - return plane3_for_points( planepts[2], planepts[1], planepts[0] ); -} - - -#endif diff --git a/tools/urt/libs/math/quaternion.cpp b/tools/urt/libs/math/quaternion.cpp deleted file mode 100644 index 942c52b..0000000 --- a/tools/urt/libs/math/quaternion.cpp +++ /dev/null @@ -1,2 +0,0 @@ - -#include "quaternion.h" diff --git a/tools/urt/libs/math/quaternion.h b/tools/urt/libs/math/quaternion.h deleted file mode 100644 index 23e6f16..0000000 --- a/tools/urt/libs/math/quaternion.h +++ /dev/null @@ -1,264 +0,0 @@ - -#if !defined( INCLUDED_MATH_QUATERNION_H ) -#define INCLUDED_MATH_QUATERNION_H - -/// \file -/// \brief Quaternion data types and related operations. - -#include "math/matrix.h" - -/// \brief A quaternion stored in single-precision floating-point. -typedef Vector4 Quaternion; - -const Quaternion c_quaternion_identity( 0, 0, 0, 1 ); - -inline Quaternion quaternion_multiplied_by_quaternion( const Quaternion& quaternion, const Quaternion& other ){ - return Quaternion( - quaternion[3] * other[0] + quaternion[0] * other[3] + quaternion[1] * other[2] - quaternion[2] * other[1], - quaternion[3] * other[1] + quaternion[1] * other[3] + quaternion[2] * other[0] - quaternion[0] * other[2], - quaternion[3] * other[2] + quaternion[2] * other[3] + quaternion[0] * other[1] - quaternion[1] * other[0], - quaternion[3] * other[3] - quaternion[0] * other[0] - quaternion[1] * other[1] - quaternion[2] * other[2] - ); -} - -inline void quaternion_multiply_by_quaternion( Quaternion& quaternion, const Quaternion& other ){ - quaternion = quaternion_multiplied_by_quaternion( quaternion, other ); -} - -/// \brief Constructs a quaternion which rotates between two points on the unit-sphere, \p from and \p to. -inline Quaternion quaternion_for_unit_vectors( const Vector3& from, const Vector3& to ){ - return Quaternion( vector3_cross( from, to ), static_cast( vector3_dot( from, to ) ) ); -} - -inline Quaternion quaternion_for_axisangle( const Vector3& axis, double angle ){ - angle *= 0.5; - float sa = static_cast( sin( angle ) ); - return Quaternion( axis[0] * sa, axis[1] * sa, axis[2] * sa, static_cast( cos( angle ) ) ); -} - -inline Quaternion quaternion_inverse( const Quaternion& quaternion ){ - return Quaternion( vector3_negated( vector4_to_vector3( quaternion ) ), quaternion[3] ); -} - -inline void quaternion_conjugate( Quaternion& quaternion ){ - quaternion = quaternion_inverse( quaternion ); -} - -inline Quaternion quaternion_normalised( const Quaternion& quaternion ){ - const double n = ( 1.0 / ( quaternion[0] * quaternion[0] + quaternion[1] * quaternion[1] + quaternion[2] * quaternion[2] + quaternion[3] * quaternion[3] ) ); - return Quaternion( - static_cast( quaternion[0] * n ), - static_cast( quaternion[1] * n ), - static_cast( quaternion[2] * n ), - static_cast( quaternion[3] * n ) - ); -} - -inline void quaternion_normalise( Quaternion& quaternion ){ - quaternion = quaternion_normalised( quaternion ); -} - -/// \brief Constructs a pure-rotation matrix from \p quaternion. -inline Matrix4 matrix4_rotation_for_quaternion( const Quaternion& quaternion ){ -#if 0 - const double xx = quaternion[0] * quaternion[0]; - const double xy = quaternion[0] * quaternion[1]; - const double xz = quaternion[0] * quaternion[2]; - const double xw = quaternion[0] * quaternion[3]; - - const double yy = quaternion[1] * quaternion[1]; - const double yz = quaternion[1] * quaternion[2]; - const double yw = quaternion[1] * quaternion[3]; - - const double zz = quaternion[2] * quaternion[2]; - const double zw = quaternion[2] * quaternion[3]; - - return Matrix4( - static_cast( 1 - 2 * ( yy + zz ) ), - static_cast( 2 * ( xy + zw ) ), - static_cast( 2 * ( xz - yw ) ), - 0, - static_cast( 2 * ( xy - zw ) ), - static_cast( 1 - 2 * ( xx + zz ) ), - static_cast( 2 * ( yz + xw ) ), - 0, - static_cast( 2 * ( xz + yw ) ), - static_cast( 2 * ( yz - xw ) ), - static_cast( 1 - 2 * ( xx + yy ) ), - 0, - 0, - 0, - 0, - 1 - ); - -#else - const double x2 = quaternion[0] + quaternion[0]; - const double y2 = quaternion[1] + quaternion[1]; - const double z2 = quaternion[2] + quaternion[2]; - const double xx = quaternion[0] * x2; - const double xy = quaternion[0] * y2; - const double xz = quaternion[0] * z2; - const double yy = quaternion[1] * y2; - const double yz = quaternion[1] * z2; - const double zz = quaternion[2] * z2; - const double wx = quaternion[3] * x2; - const double wy = quaternion[3] * y2; - const double wz = quaternion[3] * z2; - - return Matrix4( - static_cast( 1.0 - ( yy + zz ) ), - static_cast( xy + wz ), - static_cast( xz - wy ), - 0, - static_cast( xy - wz ), - static_cast( 1.0 - ( xx + zz ) ), - static_cast( yz + wx ), - 0, - static_cast( xz + wy ), - static_cast( yz - wx ), - static_cast( 1.0 - ( xx + yy ) ), - 0, - 0, - 0, - 0, - 1 - ); - -#endif -} - -const double c_half_sqrt2 = 0.70710678118654752440084436210485; -const float c_half_sqrt2f = static_cast( c_half_sqrt2 ); - -inline bool quaternion_component_is_90( float component ){ - return ( fabs( component ) - c_half_sqrt2 ) < 0.001; -} - -inline Matrix4 matrix4_rotation_for_quaternion_quantised( const Quaternion& quaternion ){ - if ( quaternion.y() == 0 - && quaternion.z() == 0 - && quaternion_component_is_90( quaternion.x() ) - && quaternion_component_is_90( quaternion.w() ) ) { - return matrix4_rotation_for_sincos_x( ( quaternion.x() > 0 ) ? 1.f : -1.f, 0 ); - } - - if ( quaternion.x() == 0 - && quaternion.z() == 0 - && quaternion_component_is_90( quaternion.y() ) - && quaternion_component_is_90( quaternion.w() ) ) { - return matrix4_rotation_for_sincos_y( ( quaternion.y() > 0 ) ? 1.f : -1.f, 0 ); - } - - if ( quaternion.x() == 0 - && quaternion.y() == 0 - && quaternion_component_is_90( quaternion.z() ) - && quaternion_component_is_90( quaternion.w() ) ) { - return matrix4_rotation_for_sincos_z( ( quaternion.z() > 0 ) ? 1.f : -1.f, 0 ); - } - - return matrix4_rotation_for_quaternion( quaternion ); -} - -inline Quaternion quaternion_for_matrix4_rotation( const Matrix4& matrix4 ){ - Matrix4 transposed = matrix4_transposed( matrix4 ); - - double trace = transposed[0] + transposed[5] + transposed[10] + 1.0; - - if ( trace > 0.0001 ) { - double S = 0.5 / sqrt( trace ); - return Quaternion( - static_cast( ( transposed[9] - transposed[6] ) * S ), - static_cast( ( transposed[2] - transposed[8] ) * S ), - static_cast( ( transposed[4] - transposed[1] ) * S ), - static_cast( 0.25 / S ) - ); - } - - if ( transposed[0] >= transposed[5] && transposed[0] >= transposed[10] ) { - double S = 2.0 * sqrt( 1.0 + transposed[0] - transposed[5] - transposed[10] ); - return Quaternion( - static_cast( 0.25 / S ), - static_cast( ( transposed[1] + transposed[4] ) / S ), - static_cast( ( transposed[2] + transposed[8] ) / S ), - static_cast( ( transposed[6] + transposed[9] ) / S ) - ); - } - - if ( transposed[5] >= transposed[0] && transposed[5] >= transposed[10] ) { - double S = 2.0 * sqrt( 1.0 + transposed[5] - transposed[0] - transposed[10] ); - return Quaternion( - static_cast( ( transposed[1] + transposed[4] ) / S ), - static_cast( 0.25 / S ), - static_cast( ( transposed[6] + transposed[9] ) / S ), - static_cast( ( transposed[2] + transposed[8] ) / S ) - ); - } - - double S = 2.0 * sqrt( 1.0 + transposed[10] - transposed[0] - transposed[5] ); - return Quaternion( - static_cast( ( transposed[2] + transposed[8] ) / S ), - static_cast( ( transposed[6] + transposed[9] ) / S ), - static_cast( 0.25 / S ), - static_cast( ( transposed[1] + transposed[4] ) / S ) - ); -} - -/// \brief Returns \p self concatenated with the rotation transform produced by \p rotation. -/// The concatenated rotation occurs before \p self. -inline Matrix4 matrix4_rotated_by_quaternion( const Matrix4& self, const Quaternion& rotation ){ - return matrix4_multiplied_by_matrix4( self, matrix4_rotation_for_quaternion( rotation ) ); -} - -/// \brief Concatenates \p self with the rotation transform produced by \p rotation. -/// The concatenated rotation occurs before \p self. -inline void matrix4_rotate_by_quaternion( Matrix4& self, const Quaternion& rotation ){ - self = matrix4_rotated_by_quaternion( self, rotation ); -} - -/// \brief Rotates \p self by \p rotation, using \p pivotpoint. -inline void matrix4_pivoted_rotate_by_quaternion( Matrix4& self, const Quaternion& rotation, const Vector3& pivotpoint ){ - matrix4_translate_by_vec3( self, pivotpoint ); - matrix4_rotate_by_quaternion( self, rotation ); - matrix4_translate_by_vec3( self, vector3_negated( pivotpoint ) ); -} - -inline Vector3 quaternion_transformed_point( const Quaternion& quaternion, const Vector3& point ){ - double xx = quaternion.x() * quaternion.x(); - double yy = quaternion.y() * quaternion.y(); - double zz = quaternion.z() * quaternion.z(); - double ww = quaternion.w() * quaternion.w(); - - double xy2 = quaternion.x() * quaternion.y() * 2; - double xz2 = quaternion.x() * quaternion.z() * 2; - double xw2 = quaternion.x() * quaternion.w() * 2; - double yz2 = quaternion.y() * quaternion.z() * 2; - double yw2 = quaternion.y() * quaternion.w() * 2; - double zw2 = quaternion.z() * quaternion.w() * 2; - - return Vector3( - static_cast( ww * point.x() + yw2 * point.z() - zw2 * point.y() + xx * point.x() + xy2 * point.y() + xz2 * point.z() - zz * point.x() - yy * point.x() ), - static_cast( xy2 * point.x() + yy * point.y() + yz2 * point.z() + zw2 * point.x() - zz * point.y() + ww * point.y() - xw2 * point.z() - xx * point.y() ), - static_cast( xz2 * point.x() + yz2 * point.y() + zz * point.z() - yw2 * point.x() - yy * point.z() + xw2 * point.y() - xx * point.z() + ww * point.z() ) - ); -} - -/// \brief Constructs a pure-rotation transform from \p axis and \p angle (radians). -inline Matrix4 matrix4_rotation_for_axisangle( const Vector3& axis, double angle ){ - return matrix4_rotation_for_quaternion( quaternion_for_axisangle( axis, angle ) ); -} - -/// \brief Rotates \p self about \p axis by \p angle. -inline void matrix4_rotate_by_axisangle( Matrix4& self, const Vector3& axis, double angle ){ - matrix4_multiply_by_matrix4( self, matrix4_rotation_for_axisangle( axis, angle ) ); -} - -/// \brief Rotates \p self about \p axis by \p angle using \p pivotpoint. -inline void matrix4_pivoted_rotate_by_axisangle( Matrix4& self, const Vector3& axis, double angle, const Vector3& pivotpoint ){ - matrix4_translate_by_vec3( self, pivotpoint ); - matrix4_rotate_by_axisangle( self, axis, angle ); - matrix4_translate_by_vec3( self, vector3_negated( pivotpoint ) ); -} - - -#endif diff --git a/tools/urt/libs/math/vector.cpp b/tools/urt/libs/math/vector.cpp deleted file mode 100644 index fbafd53..0000000 --- a/tools/urt/libs/math/vector.cpp +++ /dev/null @@ -1,2 +0,0 @@ - -#include "vector.h" diff --git a/tools/urt/libs/math/vector.h b/tools/urt/libs/math/vector.h deleted file mode 100644 index acde26b..0000000 --- a/tools/urt/libs/math/vector.h +++ /dev/null @@ -1,794 +0,0 @@ - -#if !defined( INCLUDED_MATH_VECTOR_H ) -#define INCLUDED_MATH_VECTOR_H - -/// \file -/// \brief Vector data types and related operations. - -#if 0 - -#define lrint( dbl ) ( (int)( ( dbl ) + 0.5 ) ) -#define lrintf( flt ) ( (int)( ( flt ) + 0.5 ) ) - -#endif - -#if defined ( _MSC_VER ) - -inline int lrint( double flt ){ - int i; - - _asm - { - fld flt - fistp i - }; - - return i; -} - -#else // lrint is part of ISO C99 - -#define _ISOC9X_SOURCE 1 -#define _ISOC99_SOURCE 1 - -#define __USE_ISOC9X 1 -#define __USE_ISOC99 1 - -#endif - -#include -#include -#include -#include - -//#include "debugging/debugging.h" - -/// \brief Returns true if \p self is equal to other \p other within \p epsilon. -template -inline bool float_equal_epsilon( const Element& self, const OtherElement& other, const Element& epsilon ){ - return fabs( other - self ) < epsilon; -} - -/// \brief Returns the value midway between \p self and \p other. -template -inline Element float_mid( const Element& self, const Element& other ){ - return Element( ( self + other ) * 0.5 ); -} - -/// \brief Returns \p f rounded to the nearest integer. Note that this is not the same behaviour as casting from float to int. -template -inline int float_to_integer( const Element& f ){ - return lrint( f ); -} - -/// \brief Returns \p f rounded to the nearest multiple of \snap. -template -inline Element float_snapped( const Element& f, const OtherElement& snap ){ - return Element( float_to_integer( f / snap ) * snap ); -} - -/// \brief Returns true if \p f has no decimal fraction part. -template -inline bool float_is_integer( const Element& f ){ - return f == Element( float_to_integer( f ) ); -} - -/// \brief Returns \p self modulated by the range [0, \p modulus) -/// \p self must be in the range [\p -modulus, \p modulus) -template -inline Element float_mod_range( const Element& self, const ModulusElement& modulus ){ - return Element( ( self < 0.0 ) ? self + modulus : self ); -} - -/// \brief Returns \p self modulated by the range [0, \p modulus) -template -inline Element float_mod( const Element& self, const ModulusElement& modulus ){ - return float_mod_range( Element( fmod( static_cast( self ), static_cast( modulus ) ) ), modulus ); -} - - -template -class BasicVector2 -{ -Element m_elements[2]; -public: -BasicVector2(){ -} -BasicVector2( const Element& x_, const Element& y_ ){ - x() = x_; - y() = y_; -} - -Element& x(){ - return m_elements[0]; -} -const Element& x() const { - return m_elements[0]; -} -Element& y(){ - return m_elements[1]; -} -const Element& y() const { - return m_elements[1]; -} - -const Element& operator[]( std::size_t i ) const { - return m_elements[i]; -} -Element& operator[]( std::size_t i ){ - return m_elements[i]; -} -}; - - -template -inline BasicVector2 vector2_added( const BasicVector2& self, const BasicVector2& other ){ - return BasicVector2( - Element( self.x() + other.x() ), - Element( self.y() + other.y() ) - ); -} -template -inline BasicVector2 operator+( const BasicVector2& self, const BasicVector2& other ){ - return vector2_added( self, other ); -} -template -inline void vector2_add( BasicVector2& self, const BasicVector2& other ){ - self.x() += Element( other.x() ); - self.y() += Element( other.y() ); -} -template -inline void operator+=( BasicVector2& self, const BasicVector2& other ){ - vector2_add( self, other ); -} - - -template -inline BasicVector2 vector2_subtracted( const BasicVector2& self, const BasicVector2& other ){ - return BasicVector2( - Element( self.x() - other.x() ), - Element( self.y() - other.y() ) - ); -} -template -inline BasicVector2 operator-( const BasicVector2& self, const BasicVector2& other ){ - return vector2_subtracted( self, other ); -} -template -inline void vector2_subtract( BasicVector2& self, const BasicVector2& other ){ - self.x() -= Element( other.x() ); - self.y() -= lement( other.y() ); -} -template -inline void operator-=( BasicVector2& self, const BasicVector2& other ){ - vector2_subtract( self, other ); -} - - -template -inline BasicVector2 vector2_scaled( const BasicVector2& self, OtherElement other ){ - return BasicVector2( - Element( self.x() * other ), - Element( self.y() * other ) - ); -} -template -inline BasicVector2 operator*( const BasicVector2& self, OtherElement other ){ - return vector2_scaled( self, other ); -} -template -inline void vector2_scale( BasicVector2& self, OtherElement other ){ - self.x() *= Element( other ); - self.y() *= Element( other ); -} -template -inline void operator*=( BasicVector2& self, OtherElement other ){ - vector2_scale( self, other ); -} - - -template -inline BasicVector2 vector2_scaled( const BasicVector2& self, const BasicVector2& other ){ - return BasicVector2( - Element( self.x() * other.x() ), - Element( self.y() * other.y() ) - ); -} -template -inline BasicVector2 operator*( const BasicVector2& self, const BasicVector2& other ){ - return vector2_scaled( self, other ); -} -template -inline void vector2_scale( BasicVector2& self, const BasicVector2& other ){ - self.x() *= Element( other.x() ); - self.y() *= Element( other.y() ); -} -template -inline void operator*=( BasicVector2& self, const BasicVector2& other ){ - vector2_scale( self, other ); -} - -template -inline BasicVector2 vector2_divided( const BasicVector2& self, const BasicVector2& other ){ - return BasicVector2( - Element( self.x() / other.x() ), - Element( self.y() / other.y() ) - ); -} -template -inline BasicVector2 operator/( const BasicVector2& self, const BasicVector2& other ){ - return vector2_divided( self, other ); -} -template -inline void vector2_divide( BasicVector2& self, const BasicVector2& other ){ - self.x() /= Element( other.x() ); - self.y() /= Element( other.y() ); -} -template -inline void operator/=( BasicVector2& self, const BasicVector2& other ){ - vector2_divide( self, other ); -} - - -template -inline BasicVector2 vector2_divided( const BasicVector2& self, OtherElement other ){ - return BasicVector2( - Element( self.x() / other ), - Element( self.y() / other ) - ); -} -template -inline BasicVector2 operator/( const BasicVector2& self, OtherElement other ){ - return vector2_divided( self, other ); -} -template -inline void vector2_divide( BasicVector2& self, OtherElement other ){ - self.x() /= Element( other ); - self.y() /= Element( other ); -} -template -inline void operator/=( BasicVector2& self, OtherElement other ){ - vector2_divide( self, other ); -} - -template -inline double vector2_dot( const BasicVector2& self, const BasicVector2& other ){ - return self.x() * other.x() + self.y() * other.y(); -} - -template -inline double vector2_length_squared( const BasicVector2& self ){ - return vector2_dot( self, self ); -} - - -typedef BasicVector2 Vector2; - -/// \brief A 3-element vector. -template -class BasicVector3 -{ -Element m_elements[3]; -public: - -BasicVector3(){ -} -template -BasicVector3( const BasicVector3& other ){ - x() = static_cast( other.x() ); - y() = static_cast( other.y() ); - z() = static_cast( other.z() ); -} -BasicVector3( const Element& x_, const Element& y_, const Element& z_ ){ - x() = x_; - y() = y_; - z() = z_; -} - -Element& x(){ - return m_elements[0]; -} -const Element& x() const { - return m_elements[0]; -} -Element& y(){ - return m_elements[1]; -} -const Element& y() const { - return m_elements[1]; -} -Element& z(){ - return m_elements[2]; -} -const Element& z() const { - return m_elements[2]; -} - -const Element& operator[]( std::size_t i ) const { - return m_elements[i]; -} -Element& operator[]( std::size_t i ){ - return m_elements[i]; -} - -operator BasicVector2&( ) -{ - return reinterpret_cast&>( *this ); -} -operator const BasicVector2&( ) const -{ - return reinterpret_cast&>( *this ); -} -}; - -/// \brief A 3-element vector stored in single-precision floating-point. -typedef BasicVector3 Vector3; - -const Vector3 g_vector3_identity( 0, 0, 0 ); -const Vector3 g_vector3_max = Vector3( FLT_MAX, FLT_MAX, FLT_MAX ); -const Vector3 g_vector3_axis_x( 1, 0, 0 ); -const Vector3 g_vector3_axis_y( 0, 1, 0 ); -const Vector3 g_vector3_axis_z( 0, 0, 1 ); - -const Vector3 g_vector3_axes[3] = { g_vector3_axis_x, g_vector3_axis_y, g_vector3_axis_z }; - -template -inline Element* vector3_to_array( BasicVector3& self ){ - return reinterpret_cast( &self ); -} -template -inline const Element* vector3_to_array( const BasicVector3& self ){ - return reinterpret_cast( &self ); -} - -template -inline void vector3_swap( BasicVector3& self, BasicVector3& other ){ - std::swap( self.x(), other.x() ); - std::swap( self.y(), other.y() ); - std::swap( self.z(), other.z() ); -} - -template -inline bool vector3_equal( const BasicVector3& self, const BasicVector3& other ){ - return self.x() == other.x() && self.y() == other.y() && self.z() == other.z(); -} -template -inline bool operator==( const BasicVector3& self, const BasicVector3& other ){ - return vector3_equal( self, other ); -} -template -inline bool operator!=( const BasicVector3& self, const BasicVector3& other ){ - return !vector3_equal( self, other ); -} - - -template -inline bool vector3_equal_epsilon( const BasicVector3& self, const BasicVector3& other, Epsilon epsilon ){ - return float_equal_epsilon( self.x(), other.x(), epsilon ) - && float_equal_epsilon( self.y(), other.y(), epsilon ) - && float_equal_epsilon( self.z(), other.z(), epsilon ); -} - - - -template -inline BasicVector3 vector3_added( const BasicVector3& self, const BasicVector3& other ){ - return BasicVector3( - Element( self.x() + other.x() ), - Element( self.y() + other.y() ), - Element( self.z() + other.z() ) - ); -} -template -inline BasicVector3 operator+( const BasicVector3& self, const BasicVector3& other ){ - return vector3_added( self, other ); -} -template -inline void vector3_add( BasicVector3& self, const BasicVector3& other ){ - self.x() += static_cast( other.x() ); - self.y() += static_cast( other.y() ); - self.z() += static_cast( other.z() ); -} -template -inline void operator+=( BasicVector3& self, const BasicVector3& other ){ - vector3_add( self, other ); -} - -template -inline BasicVector3 vector3_subtracted( const BasicVector3& self, const BasicVector3& other ){ - return BasicVector3( - Element( self.x() - other.x() ), - Element( self.y() - other.y() ), - Element( self.z() - other.z() ) - ); -} -template -inline BasicVector3 operator-( const BasicVector3& self, const BasicVector3& other ){ - return vector3_subtracted( self, other ); -} -template -inline void vector3_subtract( BasicVector3& self, const BasicVector3& other ){ - self.x() -= static_cast( other.x() ); - self.y() -= static_cast( other.y() ); - self.z() -= static_cast( other.z() ); -} -template -inline void operator-=( BasicVector3& self, const BasicVector3& other ){ - vector3_subtract( self, other ); -} - -template -inline BasicVector3 vector3_scaled( const BasicVector3& self, const BasicVector3& other ){ - return BasicVector3( - Element( self.x() * other.x() ), - Element( self.y() * other.y() ), - Element( self.z() * other.z() ) - ); -} -template -inline BasicVector3 operator*( const BasicVector3& self, const BasicVector3& other ){ - return vector3_scaled( self, other ); -} -template -inline void vector3_scale( BasicVector3& self, const BasicVector3& other ){ - self.x() *= static_cast( other.x() ); - self.y() *= static_cast( other.y() ); - self.z() *= static_cast( other.z() ); -} -template -inline void operator*=( BasicVector3& self, const BasicVector3& other ){ - vector3_scale( self, other ); -} - -template -inline BasicVector3 vector3_scaled( const BasicVector3& self, const OtherElement& scale ){ - return BasicVector3( - Element( self.x() * scale ), - Element( self.y() * scale ), - Element( self.z() * scale ) - ); -} -template -inline BasicVector3 operator*( const BasicVector3& self, const OtherElement& scale ){ - return vector3_scaled( self, scale ); -} -template -inline void vector3_scale( BasicVector3& self, const OtherElement& scale ){ - self.x() *= static_cast( scale ); - self.y() *= static_cast( scale ); - self.z() *= static_cast( scale ); -} -template -inline void operator*=( BasicVector3& self, const OtherElement& scale ){ - vector3_scale( self, scale ); -} - -template -inline BasicVector3 vector3_divided( const BasicVector3& self, const BasicVector3& other ){ - return BasicVector3( - Element( self.x() / other.x() ), - Element( self.y() / other.y() ), - Element( self.z() / other.z() ) - ); -} -template -inline BasicVector3 operator/( const BasicVector3& self, const BasicVector3& other ){ - return vector3_divided( self, other ); -} -template -inline void vector3_divide( BasicVector3& self, const BasicVector3& other ){ - self.x() /= static_cast( other.x() ); - self.y() /= static_cast( other.y() ); - self.z() /= static_cast( other.z() ); -} -template -inline void operator/=( BasicVector3& self, const BasicVector3& other ){ - vector3_divide( self, other ); -} - -template -inline BasicVector3 vector3_divided( const BasicVector3& self, const OtherElement& divisor ){ - return BasicVector3( - Element( self.x() / divisor ), - Element( self.y() / divisor ), - Element( self.z() / divisor ) - ); -} -template -inline BasicVector3 operator/( const BasicVector3& self, const OtherElement& divisor ){ - return vector3_divided( self, divisor ); -} -template -inline void vector3_divide( BasicVector3& self, const OtherElement& divisor ){ - self.x() /= static_cast( divisor ); - self.y() /= static_cast( divisor ); - self.z() /= static_cast( divisor ); -} -template -inline void operator/=( BasicVector3& self, const OtherElement& divisor ){ - vector3_divide( self, divisor ); -} - -template -inline double vector3_dot( const BasicVector3& self, const BasicVector3& other ){ - return self.x() * other.x() + self.y() * other.y() + self.z() * other.z(); -} - -template -inline BasicVector3 vector3_mid( const BasicVector3& begin, const BasicVector3& end ){ - return vector3_scaled( vector3_added( begin, end ), 0.5 ); -} - -template -inline BasicVector3 vector3_cross( const BasicVector3& self, const BasicVector3& other ){ - return BasicVector3( - Element( self.y() * other.z() - self.z() * other.y() ), - Element( self.z() * other.x() - self.x() * other.z() ), - Element( self.x() * other.y() - self.y() * other.x() ) - ); -} - -template -inline BasicVector3 vector3_negated( const BasicVector3& self ){ - return BasicVector3( -self.x(), -self.y(), -self.z() ); -} - -template -inline void vector3_negate( BasicVector3& self ){ - self = vector3_negated( self ); -} - -template -inline double vector3_length_squared( const BasicVector3& self ){ - return vector3_dot( self, self ); -} - -template -inline double vector3_length( const BasicVector3& self ){ - return sqrt( vector3_length_squared( self ) ); -} - -template -inline Element float_divided( Element f, Element other ){ - //ASSERT_MESSAGE(other != 0, "float_divided: invalid divisor"); - return f / other; -} - -template -inline BasicVector3 vector3_normalised( const BasicVector3& self ){ - return vector3_scaled( self, float_divided( 1.0, vector3_length( self ) ) ); -} - -template -inline void vector3_normalise( BasicVector3& self ){ - self = vector3_normalised( self ); -} - - -template -inline BasicVector3 vector3_snapped( const BasicVector3& self ){ - return BasicVector3( - Element( float_to_integer( self.x() ) ), - Element( float_to_integer( self.y() ) ), - Element( float_to_integer( self.z() ) ) - ); -} -template -inline void vector3_snap( BasicVector3& self ){ - self = vector3_snapped( self ); -} -template -inline BasicVector3 vector3_snapped( const BasicVector3& self, const OtherElement& snap ){ - return BasicVector3( - Element( float_snapped( self.x(), snap ) ), - Element( float_snapped( self.y(), snap ) ), - Element( float_snapped( self.z(), snap ) ) - ); -} -template -inline void vector3_snap( BasicVector3& self, const OtherElement& snap ){ - self = vector3_snapped( self, snap ); -} - -inline Vector3 vector3_for_spherical( double theta, double phi ){ - return Vector3( - static_cast( cos( theta ) * cos( phi ) ), - static_cast( sin( theta ) * cos( phi ) ), - static_cast( sin( phi ) ) - ); -} - - -/// \brief A 4-element vector stored in single-precision floating-point. -class Vector4 -{ -float m_elements[4]; -public: - -Vector4(){ -} -Vector4( float x_, float y_, float z_, float w_ ){ - x() = x_; - y() = y_; - z() = z_; - w() = w_; -} -Vector4( const Vector3& self, float w_ ){ - x() = self.x(); - y() = self.y(); - z() = self.z(); - w() = w_; -} - -float& x(){ - return m_elements[0]; -} -float x() const { - return m_elements[0]; -} -float& y(){ - return m_elements[1]; -} -float y() const { - return m_elements[1]; -} -float& z(){ - return m_elements[2]; -} -float z() const { - return m_elements[2]; -} -float& w(){ - return m_elements[3]; -} -float w() const { - return m_elements[3]; -} - -float index( std::size_t i ) const { - return m_elements[i]; -} -float& index( std::size_t i ){ - return m_elements[i]; -} -float operator[]( std::size_t i ) const { - return m_elements[i]; -} -float& operator[]( std::size_t i ){ - return m_elements[i]; -} - -operator Vector3&() -{ - return reinterpret_cast( *this ); -} -operator const Vector3&() const -{ - return reinterpret_cast( *this ); -} - -bool operator==( const Vector4& other ) const { - return x() == other.x() && y() == other.y() && z() == other.z() && w() == other.w(); -} -}; - -inline float* vector4_to_array( Vector4& self ){ - return reinterpret_cast( &self ); -} -inline const float* vector4_to_array( const Vector4& self ){ - return reinterpret_cast( &self ); -} - -inline Vector3& vector4_to_vector3( Vector4& self ){ - return reinterpret_cast( self ); -} -inline const Vector3& vector4_to_vector3( const Vector4& self ){ - return reinterpret_cast( self ); -} - -inline Vector4 vector4_added( const Vector4& self, const Vector4& other ){ - return Vector4( - float(self.x() + other.x() ), - float(self.y() + other.y() ), - float(self.z() + other.z() ), - float(self.w() + other.w() ) - ); -} -inline Vector4 operator+( const Vector4& self, const Vector4& other ){ - return vector4_added( self, other ); -} -inline void vector4_add( Vector4& self, const Vector4& other ){ - self.x() += static_cast( other.x() ); - self.y() += static_cast( other.y() ); - self.z() += static_cast( other.z() ); - self.w() += static_cast( other.w() ); -} -inline void operator+=( Vector4& self, const Vector4& other ){ - vector4_add( self, other ); -} - -inline Vector4 vector4_subtracted( const Vector4& self, const Vector4& other ){ - return Vector4( - float(self.x() - other.x() ), - float(self.y() - other.y() ), - float(self.z() - other.z() ), - float(self.w() - other.w() ) - ); -} -inline Vector4 operator-( const Vector4& self, const Vector4& other ){ - return vector4_subtracted( self, other ); -} -inline void vector4_subtract( Vector4& self, const Vector4& other ){ - self.x() -= static_cast( other.x() ); - self.y() -= static_cast( other.y() ); - self.z() -= static_cast( other.z() ); - self.w() -= static_cast( other.w() ); -} -inline void operator-=( Vector4& self, const Vector4& other ){ - vector4_subtract( self, other ); -} - -inline Vector4 vector4_scaled( const Vector4& self, const Vector4& other ){ - return Vector4( - float(self.x() * other.x() ), - float(self.y() * other.y() ), - float(self.z() * other.z() ), - float(self.w() * other.w() ) - ); -} -inline Vector4 operator*( const Vector4& self, const Vector4& other ){ - return vector4_scaled( self, other ); -} -inline void vector4_scale( Vector4& self, const Vector4& other ){ - self.x() *= static_cast( other.x() ); - self.y() *= static_cast( other.y() ); - self.z() *= static_cast( other.z() ); - self.w() *= static_cast( other.w() ); -} -inline void operator*=( Vector4& self, const Vector4& other ){ - vector4_scale( self, other ); -} - -inline Vector4 vector4_scaled( const Vector4& self, const float& scale ){ - return Vector4( - float(self.x() * scale), - float(self.y() * scale), - float(self.z() * scale), - float(self.w() * scale) - ); -} -inline Vector4 operator*( const Vector4& self, const float& scale ){ - return vector4_scaled( self, scale ); -} -inline void vector4_scale( Vector4& self, const float& scale ){ - self.x() *= static_cast( scale ); - self.y() *= static_cast( scale ); - self.z() *= static_cast( scale ); - self.w() *= static_cast( scale ); -} -inline void operator*=( Vector4& self, const float& scale ){ - vector4_scale( self, scale ); -} - -inline Vector4 vector4_divided( const Vector4& self, const float& divisor ){ - return Vector4( - float(self.x() / divisor), - float(self.y() / divisor), - float(self.z() / divisor), - float(self.w() / divisor) - ); -} -inline Vector4 operator/( const Vector4& self, const float& divisor ){ - return vector4_divided( self, divisor ); -} -inline void vector4_divide( Vector4& self, const float& divisor ){ - self.x() /= static_cast( divisor ); - self.y() /= static_cast( divisor ); - self.z() /= static_cast( divisor ); - self.w() /= static_cast( divisor ); -} -inline void operator/=( Vector4& self, const float& divisor ){ - vector4_divide( self, divisor ); -} - -#endif diff --git a/tools/urt/libs/mathlib.h b/tools/urt/libs/mathlib.h deleted file mode 100644 index d567da0..0000000 --- a/tools/urt/libs/mathlib.h +++ /dev/null @@ -1,422 +0,0 @@ -/* - Copyright (C) 1999-2007 id Software, Inc. and contributors. - For a list of contributors, see the accompanying CONTRIBUTORS file. - - This file is part of GtkRadiant. - - GtkRadiant is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - GtkRadiant is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with GtkRadiant; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - */ - -#ifndef __MATHLIB__ -#define __MATHLIB__ - -// mathlib.h -#include - -#ifdef __cplusplus - -// start declarations of functions defined in C library. -extern "C" -{ - -#endif - -#include "bytebool.h" - -typedef float vec_t; -typedef vec_t vec3_t[3]; -typedef vec_t vec5_t[5]; -typedef vec_t vec4_t[4]; - -#define SIDE_FRONT 0 -#define SIDE_ON 2 -#define SIDE_BACK 1 -#define SIDE_CROSS -2 - -// plane types are used to speed some tests -// 0-2 are axial planes -#define PLANE_X 0 -#define PLANE_Y 1 -#define PLANE_Z 2 -#define PLANE_NON_AXIAL 3 - -#define Q_PI 3.14159265358979323846f - -extern const vec3_t vec3_origin; - -extern const vec3_t g_vec3_axis_x; -extern const vec3_t g_vec3_axis_y; -extern const vec3_t g_vec3_axis_z; - -#define EQUAL_EPSILON 0.001 - -#define DotProduct( x,y ) ( ( x )[0] * ( y )[0] + ( x )[1] * ( y )[1] + ( x )[2] * ( y )[2] ) -#define VectorSubtract( a,b,c ) ( ( c )[0] = ( a )[0] - ( b )[0],( c )[1] = ( a )[1] - ( b )[1],( c )[2] = ( a )[2] - ( b )[2] ) -#define VectorAdd( a,b,c ) ( ( c )[0] = ( a )[0] + ( b )[0],( c )[1] = ( a )[1] + ( b )[1],( c )[2] = ( a )[2] + ( b )[2] ) -#define VectorIncrement( a,b ) ( ( b )[0] += ( a )[0],( b )[1] += ( a )[1],( b )[2] += ( a )[2] ) -#define VectorCopy( a,b ) ( ( b )[0] = ( a )[0],( b )[1] = ( a )[1],( b )[2] = ( a )[2] ) -#define VectorSet( v, a, b, c ) ( ( v )[0] = ( a ),( v )[1] = ( b ),( v )[2] = ( c ) ) -#define VectorScale( a,b,c ) ( ( c )[0] = ( b ) * ( a )[0],( c )[1] = ( b ) * ( a )[1],( c )[2] = ( b ) * ( a )[2] ) -#define VectorMid( a,b,c ) ( ( c )[0] = ( ( a )[0] + ( b )[0] ) * 0.5f,( c )[1] = ( ( a )[1] + ( b )[1] ) * 0.5f,( c )[2] = ( ( a )[2] + ( b )[2] ) * 0.5f ) -#define VectorNegate( a,b ) ( ( b )[0] = -( a )[0],( b )[1] = -( a )[1],( b )[2] = -( a )[2] ) -#define CrossProduct( a,b,c ) ( ( c )[0] = ( a )[1] * ( b )[2] - ( a )[2] * ( b )[1],( c )[1] = ( a )[2] * ( b )[0] - ( a )[0] * ( b )[2],( c )[2] = ( a )[0] * ( b )[1] - ( a )[1] * ( b )[0] ) -#define VectorClear( x ) ( ( x )[0] = ( x )[1] = ( x )[2] = 0 ) - -#define FLOAT_SNAP( f,snap ) ( (float)( floor( ( f ) / ( snap ) + 0.5 ) * ( snap ) ) ) -#define FLOAT_TO_INTEGER( f ) ( (float)( floor( ( f ) + 0.5 ) ) ) - -#define Q_rint( in ) ( (vec_t)floor( in + 0.5 ) ) - -qboolean VectorCompare( const vec3_t v1, const vec3_t v2 ); - -vec_t VectorLength( const vec3_t v ); - -void VectorMA( const vec3_t va, vec_t scale, const vec3_t vb, vec3_t vc ); - -void _CrossProduct( vec3_t v1, vec3_t v2, vec3_t cross ); -vec_t VectorNormalize( const vec3_t in, vec3_t out ); -vec_t ColorNormalize( const vec3_t in, vec3_t out ); -void VectorInverse( vec3_t v ); -void VectorPolar( vec3_t v, float radius, float theta, float phi ); - -// default snapping, to 1 -void VectorSnap( vec3_t v ); - -// integer snapping -void VectorISnap( vec3_t point, int snap ); - -// Gef: added snap to float for sub-integer grid sizes -// TTimo: we still use the int version of VectorSnap when possible -// to avoid potential rounding issues -// TTimo: renaming to VectorFSnap for C implementation -void VectorFSnap( vec3_t point, float snap ); - -// NOTE: added these from Ritual's Q3Radiant -void ClearBounds( vec3_t mins, vec3_t maxs ); -void AddPointToBounds( vec3_t v, vec3_t mins, vec3_t maxs ); - - -#define PITCH 0 // up / down -#define YAW 1 // left / right -#define ROLL 2 // fall over - -void AngleVectors( vec3_t angles, vec3_t forward, vec3_t right, vec3_t up ); -void VectorToAngles( vec3_t vec, vec3_t angles ); - -#define ZERO_EPSILON 1.0E-6 -#define RAD2DEGMULT 57.29577951308232f -#define DEG2RADMULT 0.01745329251994329f -#define RAD2DEG( a ) ( ( a ) * RAD2DEGMULT ) -#define DEG2RAD( a ) ( ( a ) * DEG2RADMULT ) - -void VectorRotate( vec3_t vIn, vec3_t vRotation, vec3_t out ); -void VectorRotateOrigin( vec3_t vIn, vec3_t vRotation, vec3_t vOrigin, vec3_t out ); - -// some function merged from tools mathlib code - -qboolean PlaneFromPoints( vec4_t plane, const vec3_t a, const vec3_t b, const vec3_t c ); -void NormalToLatLong( const vec3_t normal, byte bytes[2] ); -int PlaneTypeForNormal( vec3_t normal ); -void RotatePointAroundVector( vec3_t dst, const vec3_t dir, const vec3_t point, float degrees ); - - -/*! - \todo - FIXME test calls such as intersect tests should be named test_ - */ - -typedef vec_t m3x3_t[9]; -/*!NOTE - m4x4 looks like this.. - - x y z - x axis ( 0 1 2) - y axis ( 4 5 6) - z axis ( 8 9 10) - translation (12 13 14) - scale ( 0 5 10) - */ -typedef vec_t m4x4_t[16]; - -#define M4X4_INDEX( m,row,col ) ( m[( col << 2 ) + row] ) - -typedef enum { eXYZ, eYZX, eZXY, eXZY, eYXZ, eZYX } eulerOrder_t; - -#define CLIP_PASS 0x00 // 000000 -#define CLIP_LT_X 0x01 // 000001 -#define CLIP_GT_X 0x02 // 000010 -#define CLIP_LT_Y 0x04 // 000100 -#define CLIP_GT_Y 0x08 // 001000 -#define CLIP_LT_Z 0x10 // 010000 -#define CLIP_GT_Z 0x20 // 100000 -#define CLIP_FAIL 0x3F // 111111 -typedef unsigned char clipmask_t; - -extern const m4x4_t g_m4x4_identity; - -#define M4X4_COPY( dst,src ) ( \ - ( dst )[0] = ( src )[0], \ - ( dst )[1] = ( src )[1], \ - ( dst )[2] = ( src )[2], \ - ( dst )[3] = ( src )[3], \ - ( dst )[4] = ( src )[4], \ - ( dst )[5] = ( src )[5], \ - ( dst )[6] = ( src )[6], \ - ( dst )[7] = ( src )[7], \ - ( dst )[8] = ( src )[8], \ - ( dst )[9] = ( src )[9], \ - ( dst )[10] = ( src )[10], \ - ( dst )[11] = ( src )[11], \ - ( dst )[12] = ( src )[12], \ - ( dst )[13] = ( src )[13], \ - ( dst )[14] = ( src )[14], \ - ( dst )[15] = ( src )[15] ) - -typedef enum -{ - eRightHanded = 0, - eLeftHanded = 1, -} -m4x4Handedness_t; - -m4x4Handedness_t m4x4_handedness( const m4x4_t matrix ); - -/*! assign other m4x4 to this m4x4 */ -void m4x4_assign( m4x4_t matrix, const m4x4_t other ); - -// constructors -/*! create m4x4 as identity matrix */ -void m4x4_identity( m4x4_t matrix ); -/*! create m4x4 as a translation matrix, for a translation vec3 */ -void m4x4_translation_for_vec3( m4x4_t matrix, const vec3_t translation ); -/*! create m4x4 as a rotation matrix, for an euler angles (degrees) vec3 */ -void m4x4_rotation_for_vec3( m4x4_t matrix, const vec3_t euler, eulerOrder_t order ); -/*! create m4x4 as a scaling matrix, for a scale vec3 */ -void m4x4_scale_for_vec3( m4x4_t matrix, const vec3_t scale ); -/*! create m4x4 as a rotation matrix, for a quaternion vec4 */ -void m4x4_rotation_for_quat( m4x4_t matrix, const vec4_t rotation ); -/*! create m4x4 as a rotation matrix, for an axis vec3 and an angle (radians) */ -void m4x4_rotation_for_axisangle( m4x4_t matrix, const vec3_t axis, double angle ); -/*! generate a perspective matrix by specifying the view frustum */ -void m4x4_frustum( m4x4_t matrix, vec_t left, vec_t right, vec_t bottom, vec_t top, vec_t nearval, vec_t farval ); - -// a valid m4x4 to access is always first argument -/*! extract translation vec3 from matrix */ -void m4x4_get_translation_vec3( const m4x4_t matrix, vec3_t translation ); -/*! extract euler rotation angles from a rotation-only matrix */ -void m4x4_get_rotation_vec3( const m4x4_t matrix, vec3_t euler, eulerOrder_t order ); -/*! extract scale vec3 from matrix */ -void m4x4_get_scale_vec3( const m4x4_t matrix, vec3_t scale ); -/*! extract translation/euler/scale from an orthogonal matrix. NOTE: requires right-handed axis-base */ -void m4x4_get_transform_vec3( const m4x4_t matrix, vec3_t translation, vec3_t euler, eulerOrder_t order, vec3_t scale ); - -// a valid m4x4 to be modified is always first argument -/*! translate m4x4 by a translation vec3 */ -void m4x4_translate_by_vec3( m4x4_t matrix, const vec3_t translation ); -/*! rotate m4x4 by a euler (degrees) vec3 */ -void m4x4_rotate_by_vec3( m4x4_t matrix, const vec3_t euler, eulerOrder_t order ); -/*! scale m4x4 by a scaling vec3 */ -void m4x4_scale_by_vec3( m4x4_t matrix, const vec3_t scale ); -/*! rotate m4x4 by a quaternion vec4 */ -void m4x4_rotate_by_quat( m4x4_t matrix, const vec4_t rotation ); -/*! rotate m4x4 by an axis vec3 and an angle (radians) */ -void m4x4_rotate_by_axisangle( m4x4_t matrix, const vec3_t axis, double angle ); -/*! transform m4x4 by translation/eulerZYX/scaling vec3 (transform = scale * eulerZ * eulerY * eulerX * translation) */ -void m4x4_transform_by_vec3( m4x4_t matrix, const vec3_t translation, const vec3_t euler, eulerOrder_t order, const vec3_t scale ); -/*! rotate m4x4 around a pivot point by eulerZYX vec3 */ -void m4x4_pivoted_rotate_by_vec3( m4x4_t matrix, const vec3_t euler, eulerOrder_t order, const vec3_t pivotpoint ); -/*! scale m4x4 around a pivot point by scaling vec3 */ -void m4x4_pivoted_scale_by_vec3( m4x4_t matrix, const vec3_t scale, const vec3_t pivotpoint ); -/*! transform m4x4 around a pivot point by translation/eulerZYX/scaling vec3 */ -void m4x4_pivoted_transform_by_vec3( m4x4_t matrix, const vec3_t translation, const vec3_t euler, eulerOrder_t order, const vec3_t scale, const vec3_t pivotpoint ); -/*! transform m4x4 around a pivot point by translation/rotation/scaling vec3 */ -void m4x4_pivoted_transform_by_rotation( m4x4_t matrix, const vec3_t translation, const m4x4_t rotation, const vec3_t scale, const vec3_t pivotpoint ); -/*! rotate m4x4 around a pivot point by quaternion vec4 */ -void m4x4_pivoted_rotate_by_quat( m4x4_t matrix, const vec4_t quat, const vec3_t pivotpoint ); -/*! rotate m4x4 around a pivot point by axis vec3 and angle (radians) */ -void m4x4_pivoted_rotate_by_axisangle( m4x4_t matrix, const vec3_t axis, double angle, const vec3_t pivotpoint ); - -/*! postmultiply m4x4 by another m4x4 */ -void m4x4_multiply_by_m4x4( m4x4_t matrix, const m4x4_t matrix_src ); -/*! premultiply m4x4 by another m4x4 */ -void m4x4_premultiply_by_m4x4( m4x4_t matrix, const m4x4_t matrix_src ); -/*! postmultiply orthogonal m4x4 by another orthogonal m4x4 */ -void m4x4_orthogonal_multiply_by_m4x4( m4x4_t matrix, const m4x4_t matrix_src ); -/*! premultiply orthogonal m4x4 by another orthogonal m4x4 */ -void m4x4_orthogonal_premultiply_by_m4x4( m4x4_t matrix, const m4x4_t matrix_src ); - -/*! multiply a point (x,y,z,1) by matrix */ -void m4x4_transform_point( const m4x4_t matrix, vec3_t point ); -/*! multiply a normal (x,y,z,0) by matrix */ -void m4x4_transform_normal( const m4x4_t matrix, vec3_t normal ); -/*! multiply a vec4 (x,y,z,w) by matrix */ -void m4x4_transform_vec4( const m4x4_t matrix, vec4_t vector ); - -/*! multiply a point (x,y,z,1) by matrix */ -void m4x4_transform_point( const m4x4_t matrix, vec3_t point ); -/*! multiply a normal (x,y,z,0) by matrix */ -void m4x4_transform_normal( const m4x4_t matrix, vec3_t normal ); - -/*! transpose a m4x4 */ -void m4x4_transpose( m4x4_t matrix ); -/*! invert an orthogonal 4x3 subset of a 4x4 matrix */ -int m4x4_orthogonal_invert( m4x4_t matrix ); -/*! invert any m4x4 using Kramer's rule.. return 1 if matrix is singular, else return 0 */ -int m4x4_invert( m4x4_t matrix ); - -/*! clip a point (x,y,z,1) by canonical matrix */ -clipmask_t m4x4_clip_point( const m4x4_t matrix, const vec3_t point, vec4_t clipped ); -/*! device-space polygon for clipped triangle */ -unsigned int m4x4_clip_triangle( const m4x4_t matrix, const vec3_t p0, const vec3_t p1, const vec3_t p2, vec4_t clipped[9] ); -/*! device-space line for clipped line */ -unsigned int m4x4_clip_line( const m4x4_t matrix, const vec3_t p0, const vec3_t p1, vec4_t clipped[2] ); - - -//! quaternion identity -void quat_identity( vec4_t quat ); -//! quaternion from two unit vectors -void quat_for_unit_vectors( vec4_t quat, const vec3_t from, const vec3_t to ); -//! quaternion from axis and angle (radians) -void quat_for_axisangle( vec4_t quat, const vec3_t axis, double angle ); -//! concatenates two rotations.. equivalent to m4x4_multiply_by_m4x4 .. postmultiply.. the right-hand side is the first rotation performed -void quat_multiply_by_quat( vec4_t quat, const vec4_t other ); -//! negate a quaternion -void quat_conjugate( vec4_t quat ); -//! normalise a quaternion -void quat_normalise( vec4_t quat ); - - - -/*! - \todo object/ray intersection functions should maybe return a point rather than a distance? - */ - -/*! - aabb_t - "axis-aligned" bounding box... - origin: centre of bounding box... - extents: +/- extents of box from origin... - */ -typedef struct aabb_s -{ - vec3_t origin; - vec3_t extents; -} aabb_t; - -extern const aabb_t g_aabb_null; - -/*! - bbox_t - oriented bounding box... - aabb: axis-aligned bounding box... - axes: orientation axes... - */ -typedef struct bbox_s -{ - aabb_t aabb; - vec3_t axes[3]; - vec_t radius; -} bbox_t; - -/*! - ray_t - origin point and direction unit-vector - */ -typedef struct ray_s -{ - vec3_t origin; - vec3_t direction; -} ray_t; - -/*! - line_t - centre point and displacement of end point from centre - */ -typedef struct line_s -{ - vec3_t origin; - vec3_t extents; -} line_t; - - -/*! Generate line from start/end points. */ -void line_construct_for_vec3( line_t* line, const vec3_t start, const vec3_t end ); -/*! Return 2 if line is behind plane, else return 1 if line intersects plane, else return 0. */ -int line_test_plane( const line_t* line, const vec4_t plane ); - -/*! Generate AABB from min/max. */ -void aabb_construct_for_vec3( aabb_t* aabb, const vec3_t min, const vec3_t max ); -/*! Initialise AABB to negative size. */ -void aabb_clear( aabb_t* aabb ); - -/*! Extend AABB to include point. */ -void aabb_extend_by_point( aabb_t* aabb, const vec3_t point ); -/*! Extend AABB to include aabb_src. */ -void aabb_extend_by_aabb( aabb_t* aabb, const aabb_t* aabb_src ); -/*! Extend AABB by +/- extension vector. */ -void aabb_extend_by_vec3( aabb_t* aabb, vec3_t extension ); - -/*! Return 2 if point is inside, else 1 if point is on surface, else 0. */ -int aabb_test_point( const aabb_t* aabb, const vec3_t point ); -/*! Return 2 if aabb_src intersects, else 1 if aabb_src touches exactly, else 0. */ -int aabb_test_aabb( const aabb_t* aabb, const aabb_t* aabb_src ); -/*! Return 2 if aabb is behind plane, else 1 if aabb intersects plane, else 0. */ -int aabb_test_plane( const aabb_t* aabb, const float* plane ); -/*! Return 1 if aabb intersects ray, else 0... dist = closest intersection. */ -int aabb_intersect_ray( const aabb_t* aabb, const ray_t* ray, vec3_t intersection ); -/*! Return 1 if aabb intersects ray, else 0. Faster, but does not provide point of intersection */ -int aabb_test_ray( const aabb_t* aabb, const ray_t* ray ); - -/*! Return 2 if oriented aabb is behind plane, else 1 if aabb intersects plane, else 0. */ -int aabb_oriented_intersect_plane( const aabb_t* aabb, const m4x4_t transform, const vec_t* plane ); - -/*! Calculate the corners of the aabb. */ -void aabb_corners( const aabb_t * aabb, vec3_t corners[8] ); - -/*! (deprecated) Generate AABB from oriented bounding box. */ -void aabb_for_bbox( aabb_t* aabb, const bbox_t* bbox ); -/*! (deprecated) Generate AABB from 2-dimensions of min/max, specified by axis. */ -void aabb_for_area( aabb_t* aabb, vec3_t area_tl, vec3_t area_br, int axis ); -/*! Generate AABB to contain src* transform. NOTE: transform must be orthogonal */ -void aabb_for_transformed_aabb( aabb_t* dst, const aabb_t* src, const m4x4_t transform ); - -/*! Update bounding-sphere radius. */ -void bbox_update_radius( bbox_t* bbox ); -/*! Generate oriented bounding box from AABB and transformation matrix. */ -/*!\todo Remove need to specify eulerZYX/scale. */ -void bbox_for_oriented_aabb( bbox_t* bbox, const aabb_t* aabb, - const m4x4_t matrix, const vec3_t eulerZYX, const vec3_t scale ); -/*! Return 2 if bbox is behind plane, else return 1 if bbox intersects plane, else return 0. */ -int bbox_intersect_plane( const bbox_t* bbox, const vec_t* plane ); - - -/*! Generate a ray from an origin point and a direction unit-vector */ -void ray_construct_for_vec3( ray_t* ray, const vec3_t origin, const vec3_t direction ); - -/*! Transform a ray */ -void ray_transform( ray_t* ray, const m4x4_t matrix ); - -/*! distance from ray origin in ray direction to point. FLT_MAX if no intersection. */ -vec_t ray_intersect_point( const ray_t* ray, const vec3_t point, vec_t epsilon, vec_t divergence ); -/*! distance from ray origin in ray direction to triangle. FLT_MAX if no intersection. */ -vec_t ray_intersect_triangle( const ray_t* ray, qboolean bCullBack, const vec3_t vert0, const vec3_t vert1, const vec3_t vert2 ); -/*! distance from ray origin in ray direction to plane. */ -vec_t ray_intersect_plane( const ray_t* ray, const vec3_t normal, vec_t dist ); - - -int plane_intersect_planes( const vec4_t plane1, const vec4_t plane2, const vec4_t plane3, vec3_t intersection ); - - -#ifdef __cplusplus -} -#endif - -#endif /* __MATHLIB__ */ diff --git a/tools/urt/libs/mathlib/bbox.c b/tools/urt/libs/mathlib/bbox.c deleted file mode 100644 index b46b5f2..0000000 --- a/tools/urt/libs/mathlib/bbox.c +++ /dev/null @@ -1,456 +0,0 @@ -/* - Copyright (C) 1999-2007 id Software, Inc. and contributors. - For a list of contributors, see the accompanying CONTRIBUTORS file. - - This file is part of GtkRadiant. - - GtkRadiant is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - GtkRadiant is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with GtkRadiant; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - */ - -#include - -#include "mathlib.h" - -const aabb_t g_aabb_null = { - { 0, 0, 0, }, - { -FLT_MAX, -FLT_MAX, -FLT_MAX, }, -}; - -void aabb_construct_for_vec3( aabb_t *aabb, const vec3_t min, const vec3_t max ){ - VectorMid( min, max, aabb->origin ); - VectorSubtract( max, aabb->origin, aabb->extents ); -} - -void aabb_clear( aabb_t *aabb ){ - VectorCopy( g_aabb_null.origin, aabb->origin ); - VectorCopy( g_aabb_null.extents, aabb->extents ); -} - -void aabb_extend_by_point( aabb_t *aabb, const vec3_t point ){ -#if 1 - int i; - vec_t min, max, displacement; - for ( i = 0; i < 3; i++ ) - { - displacement = point[i] - aabb->origin[i]; - if ( fabs( displacement ) > aabb->extents[i] ) { - if ( aabb->extents[i] < 0 ) { // degenerate - min = max = point[i]; - } - else if ( displacement > 0 ) { - min = aabb->origin[i] - aabb->extents[i]; - max = aabb->origin[i] + displacement; - } - else - { - max = aabb->origin[i] + aabb->extents[i]; - min = aabb->origin[i] + displacement; - } - aabb->origin[i] = ( min + max ) * 0.5f; - aabb->extents[i] = max - aabb->origin[i]; - } - } -#else - unsigned int i; - for ( i = 0; i < 3; ++i ) - { - if ( aabb->extents[i] < 0 ) { // degenerate - aabb->origin[i] = point[i]; - aabb->extents[i] = 0; - } - else - { - vec_t displacement = point[i] - aabb->origin[i]; - vec_t increment = (vec_t)fabs( displacement ) - aabb->extents[i]; - if ( increment > 0 ) { - increment *= (vec_t)( ( displacement > 0 ) ? 0.5 : -0.5 ); - aabb->extents[i] += increment; - aabb->origin[i] += increment; - } - } - } -#endif -} - -void aabb_extend_by_aabb( aabb_t *aabb, const aabb_t *aabb_src ){ - int i; - vec_t min, max, displacement, difference; - for ( i = 0; i < 3; i++ ) - { - displacement = aabb_src->origin[i] - aabb->origin[i]; - difference = aabb_src->extents[i] - aabb->extents[i]; - if ( aabb->extents[i] < 0 - || difference >= fabs( displacement ) ) { - // 2nd contains 1st - aabb->extents[i] = aabb_src->extents[i]; - aabb->origin[i] = aabb_src->origin[i]; - } - else if ( aabb_src->extents[i] < 0 - || -difference >= fabs( displacement ) ) { - // 1st contains 2nd - continue; - } - else - { - // not contained - if ( displacement > 0 ) { - min = aabb->origin[i] - aabb->extents[i]; - max = aabb_src->origin[i] + aabb_src->extents[i]; - } - else - { - min = aabb_src->origin[i] - aabb_src->extents[i]; - max = aabb->origin[i] + aabb->extents[i]; - } - aabb->origin[i] = ( min + max ) * 0.5f; - aabb->extents[i] = max - aabb->origin[i]; - } - } -} - -void aabb_extend_by_vec3( aabb_t *aabb, vec3_t extension ){ - VectorAdd( aabb->extents, extension, aabb->extents ); -} - -int aabb_test_point( const aabb_t *aabb, const vec3_t point ){ - int i; - for ( i = 0; i < 3; i++ ) - if ( fabs( point[i] - aabb->origin[i] ) >= aabb->extents[i] ) { - return 0; - } - return 1; -} - -int aabb_test_aabb( const aabb_t *aabb, const aabb_t *aabb_src ){ - int i; - for ( i = 0; i < 3; i++ ) - if ( fabs( aabb_src->origin[i] - aabb->origin[i] ) > ( fabs( aabb->extents[i] ) + fabs( aabb_src->extents[i] ) ) ) { - return 0; - } - return 1; -} - -int aabb_test_plane( const aabb_t *aabb, const float *plane ){ - float fDist, fIntersect; - - // calc distance of origin from plane - fDist = DotProduct( plane, aabb->origin ) + plane[3]; - - // calc extents distance relative to plane normal - fIntersect = (vec_t)( fabs( plane[0] * aabb->extents[0] ) + fabs( plane[1] * aabb->extents[1] ) + fabs( plane[2] * aabb->extents[2] ) ); - // accept if origin is less than or equal to this distance - if ( fabs( fDist ) < fIntersect ) { - return 1; // partially inside - } - else if ( fDist < 0 ) { - return 2; // totally inside - } - return 0; // totally outside -} - -/* - Fast Ray-Box Intersection - by Andrew Woo - from "Graphics Gems", Academic Press, 1990 - */ - -#define NUMDIM 3 -#define RIGHT 0 -#define LEFT 1 -#define MIDDLE 2 - -int aabb_intersect_ray( const aabb_t *aabb, const ray_t *ray, vec3_t intersection ){ - int inside = 1; - char quadrant[NUMDIM]; - register int i; - int whichPlane; - double maxT[NUMDIM]; - double candidatePlane[NUMDIM]; - - const float *origin = ray->origin; - const float *direction = ray->direction; - - /* Find candidate planes; this loop can be avoided if - rays cast all from the eye(assume perpsective view) */ - for ( i = 0; i < NUMDIM; i++ ) - { - if ( origin[i] < ( aabb->origin[i] - aabb->extents[i] ) ) { - quadrant[i] = LEFT; - candidatePlane[i] = ( aabb->origin[i] - aabb->extents[i] ); - inside = 0; - } - else if ( origin[i] > ( aabb->origin[i] + aabb->extents[i] ) ) { - quadrant[i] = RIGHT; - candidatePlane[i] = ( aabb->origin[i] + aabb->extents[i] ); - inside = 0; - } - else - { - quadrant[i] = MIDDLE; - } - } - - /* Ray origin inside bounding box */ - if ( inside == 1 ) { - VectorCopy( ray->origin, intersection ); - return 1; - } - - - /* Calculate T distances to candidate planes */ - for ( i = 0; i < NUMDIM; i++ ) - { - if ( quadrant[i] != MIDDLE && direction[i] != 0. ) { - maxT[i] = ( candidatePlane[i] - origin[i] ) / direction[i]; - } - else{ - maxT[i] = -1.; - } - } - - /* Get largest of the maxT's for final choice of intersection */ - whichPlane = 0; - for ( i = 1; i < NUMDIM; i++ ) - if ( maxT[whichPlane] < maxT[i] ) { - whichPlane = i; - } - - /* Check final candidate actually inside box */ - if ( maxT[whichPlane] < 0. ) { - return 0; - } - for ( i = 0; i < NUMDIM; i++ ) - { - if ( whichPlane != i ) { - intersection[i] = (vec_t)( origin[i] + maxT[whichPlane] * direction[i] ); - if ( fabs( intersection[i] - aabb->origin[i] ) > aabb->extents[i] ) { - return 0; - } - } - else - { - intersection[i] = (vec_t)candidatePlane[i]; - } - } - - return 1; /* ray hits box */ -} - -int aabb_test_ray( const aabb_t* aabb, const ray_t* ray ){ - vec3_t displacement, ray_absolute; - vec_t f; - - displacement[0] = ray->origin[0] - aabb->origin[0]; - if ( fabs( displacement[0] ) > aabb->extents[0] && displacement[0] * ray->direction[0] >= 0.0f ) { - return 0; - } - - displacement[1] = ray->origin[1] - aabb->origin[1]; - if ( fabs( displacement[1] ) > aabb->extents[1] && displacement[1] * ray->direction[1] >= 0.0f ) { - return 0; - } - - displacement[2] = ray->origin[2] - aabb->origin[2]; - if ( fabs( displacement[2] ) > aabb->extents[2] && displacement[2] * ray->direction[2] >= 0.0f ) { - return 0; - } - - ray_absolute[0] = (float)fabs( ray->direction[0] ); - ray_absolute[1] = (float)fabs( ray->direction[1] ); - ray_absolute[2] = (float)fabs( ray->direction[2] ); - - f = ray->direction[1] * displacement[2] - ray->direction[2] * displacement[1]; - if ( (float)fabs( f ) > aabb->extents[1] * ray_absolute[2] + aabb->extents[2] * ray_absolute[1] ) { - return 0; - } - - f = ray->direction[2] * displacement[0] - ray->direction[0] * displacement[2]; - if ( (float)fabs( f ) > aabb->extents[0] * ray_absolute[2] + aabb->extents[2] * ray_absolute[0] ) { - return 0; - } - - f = ray->direction[0] * displacement[1] - ray->direction[1] * displacement[0]; - if ( (float)fabs( f ) > aabb->extents[0] * ray_absolute[1] + aabb->extents[1] * ray_absolute[0] ) { - return 0; - } - - return 1; -} - -void aabb_orthogonal_transform( aabb_t* dst, const aabb_t* src, const m4x4_t transform ){ - VectorCopy( src->origin, dst->origin ); - m4x4_transform_point( transform, dst->origin ); - - dst->extents[0] = (vec_t)( fabs( transform[0] * src->extents[0] ) - + fabs( transform[4] * src->extents[1] ) - + fabs( transform[8] * src->extents[2] ) ); - dst->extents[1] = (vec_t)( fabs( transform[1] * src->extents[0] ) - + fabs( transform[5] * src->extents[1] ) - + fabs( transform[9] * src->extents[2] ) ); - dst->extents[2] = (vec_t)( fabs( transform[2] * src->extents[0] ) - + fabs( transform[6] * src->extents[1] ) - + fabs( transform[10] * src->extents[2] ) ); -} - -void aabb_for_bbox( aabb_t *aabb, const bbox_t *bbox ){ - int i; - vec3_t temp[3]; - - VectorCopy( bbox->aabb.origin, aabb->origin ); - - // calculate the AABB extents in local coord space from the OBB extents and axes - VectorScale( bbox->axes[0], bbox->aabb.extents[0], temp[0] ); - VectorScale( bbox->axes[1], bbox->aabb.extents[1], temp[1] ); - VectorScale( bbox->axes[2], bbox->aabb.extents[2], temp[2] ); - for ( i = 0; i < 3; i++ ) aabb->extents[i] = (vec_t)( fabs( temp[0][i] ) + fabs( temp[1][i] ) + fabs( temp[2][i] ) ); -} - -void aabb_for_area( aabb_t *aabb, vec3_t area_tl, vec3_t area_br, int axis ){ - aabb_clear( aabb ); - aabb->extents[axis] = FLT_MAX; - aabb_extend_by_point( aabb, area_tl ); - aabb_extend_by_point( aabb, area_br ); -} - -int aabb_oriented_intersect_plane( const aabb_t *aabb, const m4x4_t transform, const vec_t* plane ){ - vec_t fDist, fIntersect; - - // calc distance of origin from plane - fDist = DotProduct( plane, aabb->origin ) + plane[3]; - - // calc extents distance relative to plane normal - fIntersect = (vec_t)( fabs( aabb->extents[0] * DotProduct( plane, transform ) ) - + fabs( aabb->extents[1] * DotProduct( plane, transform + 4 ) ) - + fabs( aabb->extents[2] * DotProduct( plane, transform + 8 ) ) ); - // accept if origin is less than this distance - if ( fabs( fDist ) < fIntersect ) { - return 1; // partially inside - } - else if ( fDist < 0 ) { - return 2; // totally inside - } - return 0; // totally outside -} - -void aabb_corners( const aabb_t* aabb, vec3_t corners[8] ){ - vec3_t min, max; - VectorSubtract( aabb->origin, aabb->extents, min ); - VectorAdd( aabb->origin, aabb->extents, max ); - VectorSet( corners[0], min[0], max[1], max[2] ); - VectorSet( corners[1], max[0], max[1], max[2] ); - VectorSet( corners[2], max[0], min[1], max[2] ); - VectorSet( corners[3], min[0], min[1], max[2] ); - VectorSet( corners[4], min[0], max[1], min[2] ); - VectorSet( corners[5], max[0], max[1], min[2] ); - VectorSet( corners[6], max[0], min[1], min[2] ); - VectorSet( corners[7], min[0], min[1], min[2] ); -} - - -void bbox_update_radius( bbox_t *bbox ){ - bbox->radius = VectorLength( bbox->aabb.extents ); -} - -void aabb_for_transformed_aabb( aabb_t* dst, const aabb_t* src, const m4x4_t transform ){ - if ( src->extents[0] < 0 - || src->extents[1] < 0 - || src->extents[2] < 0 ) { - aabb_clear( dst ); - return; - } - - VectorCopy( src->origin, dst->origin ); - m4x4_transform_point( transform, dst->origin ); - - dst->extents[0] = (vec_t)( fabs( transform[0] * src->extents[0] ) - + fabs( transform[4] * src->extents[1] ) - + fabs( transform[8] * src->extents[2] ) ); - dst->extents[1] = (vec_t)( fabs( transform[1] * src->extents[0] ) - + fabs( transform[5] * src->extents[1] ) - + fabs( transform[9] * src->extents[2] ) ); - dst->extents[2] = (vec_t)( fabs( transform[2] * src->extents[0] ) - + fabs( transform[6] * src->extents[1] ) - + fabs( transform[10] * src->extents[2] ) ); -} - -void bbox_for_oriented_aabb( bbox_t *bbox, const aabb_t *aabb, const m4x4_t matrix, const vec3_t euler, const vec3_t scale ){ - double rad[3]; - double pi_180 = Q_PI / 180; - double A, B, C, D, E, F, AD, BD; - - VectorCopy( aabb->origin, bbox->aabb.origin ); - - m4x4_transform_point( matrix, bbox->aabb.origin ); - - bbox->aabb.extents[0] = aabb->extents[0] * scale[0]; - bbox->aabb.extents[1] = aabb->extents[1] * scale[1]; - bbox->aabb.extents[2] = aabb->extents[2] * scale[2]; - - rad[0] = euler[0] * pi_180; - rad[1] = euler[1] * pi_180; - rad[2] = euler[2] * pi_180; - - A = cos( rad[0] ); - B = sin( rad[0] ); - C = cos( rad[1] ); - D = sin( rad[1] ); - E = cos( rad[2] ); - F = sin( rad[2] ); - - AD = A * -D; - BD = B * -D; - - bbox->axes[0][0] = (vec_t)( C * E ); - bbox->axes[0][1] = (vec_t)( -BD * E + A * F ); - bbox->axes[0][2] = (vec_t)( AD * E + B * F ); - bbox->axes[1][0] = (vec_t)( -C * F ); - bbox->axes[1][1] = (vec_t)( BD * F + A * E ); - bbox->axes[1][2] = (vec_t)( -AD * F + B * E ); - bbox->axes[2][0] = (vec_t)D; - bbox->axes[2][1] = (vec_t)( -B * C ); - bbox->axes[2][2] = (vec_t)( A * C ); - - bbox_update_radius( bbox ); -} - -int bbox_intersect_plane( const bbox_t *bbox, const vec_t* plane ){ - vec_t fDist, fIntersect; - - // calc distance of origin from plane - fDist = DotProduct( plane, bbox->aabb.origin ) + plane[3]; - - // trivial accept/reject using bounding sphere - if ( fabs( fDist ) > bbox->radius ) { - if ( fDist < 0 ) { - return 2; // totally inside - } - else{ - return 0; // totally outside - } - } - - // calc extents distance relative to plane normal - fIntersect = (vec_t)( fabs( bbox->aabb.extents[0] * DotProduct( plane, bbox->axes[0] ) ) - + fabs( bbox->aabb.extents[1] * DotProduct( plane, bbox->axes[1] ) ) - + fabs( bbox->aabb.extents[2] * DotProduct( plane, bbox->axes[2] ) ) ); - // accept if origin is less than this distance - if ( fabs( fDist ) < fIntersect ) { - return 1; // partially inside - } - else if ( fDist < 0 ) { - return 2; // totally inside - } - return 0; // totally outside -} diff --git a/tools/urt/libs/mathlib/line.c b/tools/urt/libs/mathlib/line.c deleted file mode 100644 index 8e19276..0000000 --- a/tools/urt/libs/mathlib/line.c +++ /dev/null @@ -1,43 +0,0 @@ -/* - Copyright (C) 1999-2007 id Software, Inc. and contributors. - For a list of contributors, see the accompanying CONTRIBUTORS file. - - This file is part of GtkRadiant. - - GtkRadiant is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - GtkRadiant is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with GtkRadiant; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - */ - -#include "mathlib.h" - -void line_construct_for_vec3( line_t *line, const vec3_t start, const vec3_t end ){ - VectorMid( start, end, line->origin ); - VectorSubtract( end, line->origin, line->extents ); -} - -int line_test_plane( const line_t* line, const vec4_t plane ){ - float fDist; - - // calc distance of origin from plane - fDist = DotProduct( plane, line->origin ) + plane[3]; - - // accept if origin is less than or equal to this distance - if ( fabs( fDist ) < fabs( DotProduct( plane, line->extents ) ) ) { - return 1; // partially inside - } - else if ( fDist < 0 ) { - return 2; // totally inside - } - return 0; // totally outside -} diff --git a/tools/urt/libs/mathlib/m4x4.c b/tools/urt/libs/mathlib/m4x4.c deleted file mode 100644 index 7b2f077..0000000 --- a/tools/urt/libs/mathlib/m4x4.c +++ /dev/null @@ -1,1847 +0,0 @@ -/* - Copyright (C) 1999-2007 id Software, Inc. and contributors. - For a list of contributors, see the accompanying CONTRIBUTORS file. - - This file is part of GtkRadiant. - - GtkRadiant is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - GtkRadiant is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with GtkRadiant; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - */ - -#include "mathlib.h" - -const m4x4_t g_m4x4_identity = { - 1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1, -}; - -void m4x4_identity( m4x4_t matrix ){ - matrix[1] = matrix[2] = matrix[3] = - matrix[4] = matrix[6] = matrix[7] = - matrix[8] = matrix[9] = matrix[11] = - matrix[12] = matrix[13] = matrix[14] = 0; - - matrix[0] = matrix[5] = matrix[10] = matrix[15] = 1; -} - -m4x4Handedness_t m4x4_handedness( const m4x4_t matrix ){ - vec3_t cross; - CrossProduct( matrix + 0, matrix + 4, cross ); - return ( DotProduct( matrix + 8, cross ) < 0 ) ? eLeftHanded : eRightHanded; -} - -void m4x4_assign( m4x4_t matrix, const m4x4_t other ){ - M4X4_COPY( matrix, other ); -} - -void m4x4_translation_for_vec3( m4x4_t matrix, const vec3_t translation ){ - matrix[1] = matrix[2] = matrix[3] = - matrix[4] = matrix[6] = matrix[7] = - matrix[8] = matrix[9] = matrix[11] = 0; - - matrix[0] = matrix[5] = matrix[10] = matrix[15] = 1; - - matrix[12] = translation[0]; - matrix[13] = translation[1]; - matrix[14] = translation[2]; -} - -/* - clockwise rotation around X, Y, Z, facing along axis - 1 0 0 cy 0 sy cz sz 0 - 0 cx sx 0 1 0 -sz cz 0 - 0 -sx cx -sy 0 cy 0 0 1 - - rows of Z by cols of Y - cy*cz -sy*cz+sz -sy*sz+cz - -sz*cy -sz*sy+cz - - .. or something like that.. - - final rotation is Z * Y * X - cy*cz -sx*-sy*cz+cx*sz cx*-sy*sz+sx*cz - -cy*sz sx*sy*sz+cx*cz -cx*-sy*sz+sx*cz - sy -sx*cy cx*cy - */ - -/* transposed - | cy.cz + 0.sz + sy.0 cy.-sz + 0 .cz + sy.0 cy.0 + 0 .0 + sy.1 | - | sx.sy.cz + cx.sz + -sx.cy.0 sx.sy.-sz + cx.cz + -sx.cy.0 sx.sy.0 + cx.0 + -sx.cy.1 | - | -cx.sy.cz + sx.sz + cx.cy.0 -cx.sy.-sz + sx.cz + cx.cy.0 -cx.sy.0 + 0 .0 + cx.cy.1 | - */ -void m4x4_rotation_for_vec3( m4x4_t matrix, const vec3_t euler, eulerOrder_t order ){ - double cx, sx, cy, sy, cz, sz; - - cx = cos( DEG2RAD( euler[0] ) ); - sx = sin( DEG2RAD( euler[0] ) ); - cy = cos( DEG2RAD( euler[1] ) ); - sy = sin( DEG2RAD( euler[1] ) ); - cz = cos( DEG2RAD( euler[2] ) ); - sz = sin( DEG2RAD( euler[2] ) ); - - switch ( order ) - { - case eXYZ: - -#if 1 - - { - matrix[0] = (vec_t)( cy * cz ); - matrix[1] = (vec_t)( cy * sz ); - matrix[2] = (vec_t)-sy; - matrix[4] = (vec_t)( sx * sy * cz + cx * -sz ); - matrix[5] = (vec_t)( sx * sy * sz + cx * cz ); - matrix[6] = (vec_t)( sx * cy ); - matrix[8] = (vec_t)( cx * sy * cz + sx * sz ); - matrix[9] = (vec_t)( cx * sy * sz + -sx * cz ); - matrix[10] = (vec_t)( cx * cy ); - } - - matrix[12] = matrix[13] = matrix[14] = matrix[3] = matrix[7] = matrix[11] = 0; - matrix[15] = 1; - -#else - - m4x4_identity( matrix ); - matrix[5] = (vec_t) cx; matrix[6] = (vec_t) sx; - matrix[9] = (vec_t)-sx; matrix[10] = (vec_t) cx; - - { - m4x4_t temp; - m4x4_identity( temp ); - temp[0] = (vec_t) cy; temp[2] = (vec_t)-sy; - temp[8] = (vec_t) sy; temp[10] = (vec_t) cy; - m4x4_premultiply_by_m4x4( matrix, temp ); - m4x4_identity( temp ); - temp[0] = (vec_t) cz; temp[1] = (vec_t) sz; - temp[4] = (vec_t)-sz; temp[5] = (vec_t) cz; - m4x4_premultiply_by_m4x4( matrix, temp ); - } -#endif - - break; - - case eYZX: - m4x4_identity( matrix ); - matrix[0] = (vec_t) cy; matrix[2] = (vec_t)-sy; - matrix[8] = (vec_t) sy; matrix[10] = (vec_t) cy; - - { - m4x4_t temp; - m4x4_identity( temp ); - temp[5] = (vec_t) cx; temp[6] = (vec_t) sx; - temp[9] = (vec_t)-sx; temp[10] = (vec_t) cx; - m4x4_premultiply_by_m4x4( matrix, temp ); - m4x4_identity( temp ); - temp[0] = (vec_t) cz; temp[1] = (vec_t) sz; - temp[4] = (vec_t)-sz; temp[5] = (vec_t) cz; - m4x4_premultiply_by_m4x4( matrix, temp ); - } - break; - - case eZXY: - m4x4_identity( matrix ); - matrix[0] = (vec_t) cz; matrix[1] = (vec_t) sz; - matrix[4] = (vec_t)-sz; matrix[5] = (vec_t) cz; - - { - m4x4_t temp; - m4x4_identity( temp ); - temp[5] = (vec_t) cx; temp[6] = (vec_t) sx; - temp[9] = (vec_t)-sx; temp[10] = (vec_t) cx; - m4x4_premultiply_by_m4x4( matrix, temp ); - m4x4_identity( temp ); - temp[0] = (vec_t) cy; temp[2] = (vec_t)-sy; - temp[8] = (vec_t) sy; temp[10] = (vec_t) cy; - m4x4_premultiply_by_m4x4( matrix, temp ); - } - break; - - case eXZY: - m4x4_identity( matrix ); - matrix[5] = (vec_t) cx; matrix[6] = (vec_t) sx; - matrix[9] = (vec_t)-sx; matrix[10] = (vec_t) cx; - - { - m4x4_t temp; - m4x4_identity( temp ); - temp[0] = (vec_t) cz; temp[1] = (vec_t) sz; - temp[4] = (vec_t)-sz; temp[5] = (vec_t) cz; - m4x4_premultiply_by_m4x4( matrix, temp ); - m4x4_identity( temp ); - temp[0] = (vec_t) cy; temp[2] = (vec_t)-sy; - temp[8] = (vec_t) sy; temp[10] = (vec_t) cy; - m4x4_premultiply_by_m4x4( matrix, temp ); - } - break; - - case eYXZ: - -/* transposed - | cy.cz + sx.sy.-sz + -cx.sy.0 0.cz + cx.-sz + sx.0 sy.cz + -sx.cy.-sz + cx.cy.0 | - | cy.sz + sx.sy.cz + -cx.sy.0 0.sz + cx.cz + sx.0 sy.sz + -sx.cy.cz + cx.cy.0 | - | cy.0 + sx.sy.0 + -cx.sy.1 0.0 + cx.0 + sx.1 sy.0 + -sx.cy.0 + cx.cy.1 | - */ - -#if 1 - - { - matrix[0] = (vec_t)( cy * cz + sx * sy * -sz ); - matrix[1] = (vec_t)( cy * sz + sx * sy * cz ); - matrix[2] = (vec_t)( -cx * sy ); - matrix[4] = (vec_t)( cx * -sz ); - matrix[5] = (vec_t)( cx * cz ); - matrix[6] = (vec_t)( sx ); - matrix[8] = (vec_t)( sy * cz + -sx * cy * -sz ); - matrix[9] = (vec_t)( sy * sz + -sx * cy * cz ); - matrix[10] = (vec_t)( cx * cy ); - } - - matrix[12] = matrix[13] = matrix[14] = matrix[3] = matrix[7] = matrix[11] = 0; - matrix[15] = 1; - -#else - - m4x4_identity( matrix ); - matrix[0] = (vec_t) cy; matrix[2] = (vec_t)-sy; - matrix[8] = (vec_t) sy; matrix[10] = (vec_t) cy; - - { - m4x4_t temp; - m4x4_identity( temp ); - temp[5] = (vec_t) cx; temp[6] = (vec_t) sx; - temp[9] = (vec_t)-sx; temp[10] = (vec_t) cx; - m4x4_premultiply_by_m4x4( matrix, temp ); - m4x4_identity( temp ); - temp[0] = (vec_t) cz; temp[1] = (vec_t) sz; - temp[4] = (vec_t)-sz; temp[5] = (vec_t) cz; - m4x4_premultiply_by_m4x4( matrix, temp ); - } -#endif - break; - - case eZYX: -#if 1 - - { - matrix[0] = (vec_t)( cy * cz ); - matrix[4] = (vec_t)( cy * -sz ); - matrix[8] = (vec_t)sy; - matrix[1] = (vec_t)( sx * sy * cz + cx * sz ); - matrix[5] = (vec_t)( sx * sy * -sz + cx * cz ); - matrix[9] = (vec_t)( -sx * cy ); - matrix[2] = (vec_t)( cx * -sy * cz + sx * sz ); - matrix[6] = (vec_t)( cx * -sy * -sz + sx * cz ); - matrix[10] = (vec_t)( cx * cy ); - } - - matrix[12] = matrix[13] = matrix[14] = matrix[3] = matrix[7] = matrix[11] = 0; - matrix[15] = 1; - -#else - - m4x4_identity( matrix ); - matrix[0] = (vec_t) cz; matrix[1] = (vec_t) sz; - matrix[4] = (vec_t)-sz; matrix[5] = (vec_t) cz; - { - m4x4_t temp; - m4x4_identity( temp ); - temp[0] = (vec_t) cy; temp[2] = (vec_t)-sy; - temp[8] = (vec_t) sy; temp[10] = (vec_t) cy; - m4x4_premultiply_by_m4x4( matrix, temp ); - m4x4_identity( temp ); - temp[5] = (vec_t) cx; temp[6] = (vec_t) sx; - temp[9] = (vec_t)-sx; temp[10] = (vec_t) cx; - m4x4_premultiply_by_m4x4( matrix, temp ); - } - -#endif - break; - - } -} - -void m4x4_scale_for_vec3( m4x4_t matrix, const vec3_t scale ){ - matrix[1] = matrix[2] = matrix[3] = - matrix[4] = matrix[6] = matrix[7] = - matrix[8] = matrix[9] = matrix[11] = - matrix[12] = matrix[13] = matrix[14] = 0; - - matrix[15] = 1; - - matrix[0] = scale[0]; - matrix[5] = scale[1]; - matrix[10] = scale[2]; -} - -void m4x4_rotation_for_quat( m4x4_t matrix, const vec4_t quat ){ -#if 0 - const double xx = quat[0] * quat[0]; - const double xy = quat[0] * quat[1]; - const double xz = quat[0] * quat[2]; - const double xw = quat[0] * quat[3]; - - const double yy = quat[1] * quat[1]; - const double yz = quat[1] * quat[2]; - const double yw = quat[1] * quat[3]; - - const double zz = quat[2] * quat[2]; - const double zw = quat[2] * quat[3]; - - matrix[0] = 1 - 2 * ( yy + zz ); - matrix[4] = 2 * ( xy - zw ); - matrix[8] = 2 * ( xz + yw ); - - matrix[1] = 2 * ( xy + zw ); - matrix[5] = 1 - 2 * ( xx + zz ); - matrix[9] = 2 * ( yz - xw ); - - matrix[2] = 2 * ( xz - yw ); - matrix[6] = 2 * ( yz + xw ); - matrix[10] = 1 - 2 * ( xx + yy ); -#else - const double x2 = quat[0] + quat[0]; - const double y2 = quat[1] + quat[1]; - const double z2 = quat[2] + quat[2]; - const double xx = quat[0] * x2; - const double xy = quat[0] * y2; - const double xz = quat[0] * z2; - const double yy = quat[1] * y2; - const double yz = quat[1] * z2; - const double zz = quat[2] * z2; - const double wx = quat[3] * x2; - const double wy = quat[3] * y2; - const double wz = quat[3] * z2; - - matrix[0] = (vec_t)( 1.0 - ( yy + zz ) ); - matrix[4] = (vec_t)( xy - wz ); - matrix[8] = (vec_t)( xz + wy ); - - matrix[1] = (vec_t)( xy + wz ); - matrix[5] = (vec_t)( 1.0 - ( xx + zz ) ); - matrix[9] = (vec_t)( yz - wx ); - - matrix[2] = (vec_t)( xz - wy ); - matrix[6] = (vec_t)( yz + wx ); - matrix[10] = (vec_t)( 1.0 - ( xx + yy ) ); -#endif - - matrix[3] = matrix[7] = matrix[11] = matrix[12] = matrix[13] = matrix[14] = 0; - matrix[15] = 1; -} - -void m4x4_rotation_for_axisangle( m4x4_t matrix, const vec3_t axis, double angle ){ - vec4_t quat; - quat_for_axisangle( quat, axis, angle ); - m4x4_rotation_for_quat( matrix, quat ); -} - -void m4x4_frustum( m4x4_t matrix, - vec_t left, vec_t right, - vec_t bottom, vec_t top, - vec_t nearval, vec_t farval ){ - matrix[0] = (vec_t)( ( 2 * nearval ) / ( right - left ) ); - matrix[1] = 0; - matrix[2] = 0; - matrix[3] = 0; - - matrix[4] = 0; - matrix[5] = (vec_t)( ( 2 * nearval ) / ( top - bottom ) ); - matrix[6] = 0; - matrix[7] = 0; - - matrix[8] = (vec_t)( ( right + left ) / ( right - left ) ); - matrix[9] = (vec_t)( ( top + bottom ) / ( top - bottom ) ); - matrix[10] = (vec_t)( -( farval + nearval ) / ( farval - nearval ) ); - matrix[11] = -1; - - matrix[12] = 0; - matrix[13] = 0; - matrix[14] = (vec_t)( -( 2 * farval * nearval ) / ( farval - nearval ) ); - matrix[15] = 0; -} - - -void m4x4_get_translation_vec3( const m4x4_t matrix, vec3_t translation ){ - translation[0] = matrix[12]; - translation[1] = matrix[13]; - translation[2] = matrix[14]; -} - -void m4x4_get_rotation_vec3( const m4x4_t matrix, vec3_t euler, eulerOrder_t order ){ - double a, ca; - - switch ( order ) - { - case eXYZ: - a = asin( -matrix[2] ); - ca = cos( a ); - euler[1] = (vec_t)RAD2DEG( a ); /* Calculate Y-axis angle */ - - if ( fabs( ca ) > 0.005 ) { /* Gimbal lock? */ - /* No, so get Z-axis angle */ - euler[2] = (vec_t)RAD2DEG( atan2( matrix[1] / ca, matrix[0] / ca ) ); - - /* Get X-axis angle */ - euler[0] = (vec_t)RAD2DEG( atan2( matrix[6] / ca, matrix[10] / ca ) ); - } - else /* Gimbal lock has occurred */ - { - /* Set Z-axis angle to zero */ - euler[2] = 0; - - /* And calculate X-axis angle */ - euler[0] = (vec_t)RAD2DEG( atan2( -matrix[9], matrix[5] ) ); - } - break; - case eYZX: - /* NOT IMPLEMENTED */ - break; - case eZXY: - /* NOT IMPLEMENTED */ - break; - case eXZY: - /* NOT IMPLEMENTED */ - break; - case eYXZ: - a = asin( matrix[6] ); - ca = cos( a ); - euler[0] = (vec_t)RAD2DEG( a ); /* Calculate X-axis angle */ - - if ( fabs( ca ) > 0.005 ) { /* Gimbal lock? */ - /* No, so get Y-axis angle */ - euler[1] = (vec_t)RAD2DEG( atan2( -matrix[2] / ca, matrix[10] / ca ) ); - - /* Get Z-axis angle */ - euler[2] = (vec_t)RAD2DEG( atan2( -matrix[4] / ca, matrix[5] / ca ) ); - } - else /* Gimbal lock has occurred */ - { - /* Set Z-axis angle to zero */ - euler[2] = 0; - - /* And calculate Y-axis angle */ - euler[1] = (vec_t)RAD2DEG( atan2( matrix[8], matrix[0] ) ); - } - break; - case eZYX: - a = asin( matrix[8] ); - ca = cos( a ); - euler[1] = (vec_t)RAD2DEG( a ); /* Calculate Y-axis angle */ - - if ( fabs( ca ) > 0.005 ) { /* Gimbal lock? */ - /* No, so get X-axis angle */ - euler[0] = (vec_t)RAD2DEG( atan2( -matrix[9] / ca, matrix[10] / ca ) ); - - /* Get Z-axis angle */ - euler[2] = (vec_t)RAD2DEG( atan2( -matrix[4] / ca, matrix[0] / ca ) ); - } - else /* Gimbal lock has occurred */ - { - /* Set X-axis angle to zero */ - euler[0] = 0; - - /* And calculate Z-axis angle */ - euler[2] = (vec_t)RAD2DEG( atan2( matrix[1], matrix[5] ) ); - } - break; - } - - /* return only positive angles in [0,360] */ - if ( euler[0] < 0 ) { - euler[0] += 360; - } - if ( euler[1] < 0 ) { - euler[1] += 360; - } - if ( euler[2] < 0 ) { - euler[2] += 360; - } -} - -void m4x4_get_scale_vec3( const m4x4_t matrix, vec3_t scale ){ - scale[0] = VectorLength( matrix + 0 ); - scale[1] = VectorLength( matrix + 4 ); - scale[2] = VectorLength( matrix + 8 ); -} - -void m4x4_get_transform_vec3( const m4x4_t matrix, vec3_t translation, vec3_t euler, eulerOrder_t order, vec3_t scale ){ - m4x4_t normalised; - m4x4_assign( normalised, matrix ); - scale[0] = VectorNormalize( normalised + 0, normalised + 0 ); - scale[1] = VectorNormalize( normalised + 4, normalised + 4 ); - scale[2] = VectorNormalize( normalised + 8, normalised + 8 ); - if ( m4x4_handedness( normalised ) == eLeftHanded ) { - VectorNegate( normalised + 0, normalised + 0 ); - VectorNegate( normalised + 4, normalised + 4 ); - VectorNegate( normalised + 8, normalised + 8 ); - scale[0] = -scale[0]; - scale[1] = -scale[1]; - scale[2] = -scale[2]; - } - m4x4_get_rotation_vec3( normalised, euler, order ); - m4x4_get_translation_vec3( matrix, translation ); -} - -void m4x4_translate_by_vec3( m4x4_t matrix, const vec3_t translation ){ - m4x4_t temp; - m4x4_translation_for_vec3( temp, translation ); - m4x4_multiply_by_m4x4( matrix, temp ); -} - -void m4x4_rotate_by_vec3( m4x4_t matrix, const vec3_t euler, eulerOrder_t order ){ - m4x4_t temp; - m4x4_rotation_for_vec3( temp, euler, order ); - m4x4_multiply_by_m4x4( matrix, temp ); -} - -void m4x4_scale_by_vec3( m4x4_t matrix, const vec3_t scale ){ - m4x4_t temp; - m4x4_scale_for_vec3( temp, scale ); - m4x4_multiply_by_m4x4( matrix, temp ); -} - -void m4x4_rotate_by_quat( m4x4_t matrix, const vec4_t rotation ){ - m4x4_t temp; - m4x4_rotation_for_quat( temp, rotation ); - m4x4_multiply_by_m4x4( matrix, temp ); -} - -void m4x4_rotate_by_axisangle( m4x4_t matrix, const vec3_t axis, double angle ){ - m4x4_t temp; - m4x4_rotation_for_axisangle( temp, axis, angle ); - m4x4_multiply_by_m4x4( matrix, temp ); -} - -void m4x4_transform_by_vec3( m4x4_t matrix, const vec3_t translation, const vec3_t euler, eulerOrder_t order, const vec3_t scale ){ - m4x4_translate_by_vec3( matrix, translation ); - m4x4_rotate_by_vec3( matrix, euler, order ); - m4x4_scale_by_vec3( matrix, scale ); -} - -void m4x4_pivoted_rotate_by_vec3( m4x4_t matrix, const vec3_t euler, eulerOrder_t order, const vec3_t pivotpoint ){ - vec3_t vec3_temp; - VectorNegate( pivotpoint, vec3_temp ); - - m4x4_translate_by_vec3( matrix, pivotpoint ); - m4x4_rotate_by_vec3( matrix, euler, order ); - m4x4_translate_by_vec3( matrix, vec3_temp ); -} - -void m4x4_pivoted_scale_by_vec3( m4x4_t matrix, const vec3_t scale, const vec3_t pivotpoint ){ - vec3_t vec3_temp; - VectorNegate( pivotpoint, vec3_temp ); - - m4x4_translate_by_vec3( matrix, pivotpoint ); - m4x4_scale_by_vec3( matrix, scale ); - m4x4_translate_by_vec3( matrix, vec3_temp ); -} - -void m4x4_pivoted_transform_by_vec3( m4x4_t matrix, const vec3_t translation, const vec3_t euler, eulerOrder_t order, const vec3_t scale, const vec3_t pivotpoint ){ - vec3_t vec3_temp; - - VectorAdd( pivotpoint, translation, vec3_temp ); - m4x4_translate_by_vec3( matrix, vec3_temp ); - m4x4_rotate_by_vec3( matrix, euler, order ); - m4x4_scale_by_vec3( matrix, scale ); - VectorNegate( pivotpoint, vec3_temp ); - m4x4_translate_by_vec3( matrix, vec3_temp ); -} - -void m4x4_pivoted_transform_by_rotation( m4x4_t matrix, const vec3_t translation, const m4x4_t rotation, const vec3_t scale, const vec3_t pivotpoint ){ - vec3_t vec3_temp; - - VectorAdd( pivotpoint, translation, vec3_temp ); - m4x4_translate_by_vec3( matrix, vec3_temp ); - m4x4_multiply_by_m4x4( matrix, rotation ); - m4x4_scale_by_vec3( matrix, scale ); - VectorNegate( pivotpoint, vec3_temp ); - m4x4_translate_by_vec3( matrix, vec3_temp ); -} - -void m4x4_pivoted_rotate_by_quat( m4x4_t matrix, const vec4_t rotation, const vec3_t pivotpoint ){ - vec3_t vec3_temp; - VectorNegate( pivotpoint, vec3_temp ); - - m4x4_translate_by_vec3( matrix, pivotpoint ); - m4x4_rotate_by_quat( matrix, rotation ); - m4x4_translate_by_vec3( matrix, vec3_temp ); -} - -void m4x4_pivoted_rotate_by_axisangle( m4x4_t matrix, const vec3_t axis, double angle, const vec3_t pivotpoint ){ - vec3_t vec3_temp; - VectorNegate( pivotpoint, vec3_temp ); - - m4x4_translate_by_vec3( matrix, pivotpoint ); - m4x4_rotate_by_axisangle( matrix, axis, angle ); - m4x4_translate_by_vec3( matrix, vec3_temp ); -} - -/* - A = A.B - - A0 = B0 * A0 + B1 * A4 + B2 * A8 + B3 * A12 - A4 = B4 * A0 + B5 * A4 + B6 * A8 + B7 * A12 - A8 = B8 * A0 + B9 * A4 + B10* A8 + B11* A12 - A12= B12* A0 + B13* A4 + B14* A8 + B15* A12 - - A1 = B0 * A1 + B1 * A5 + B2 * A9 + B3 * A13 - A5 = B4 * A1 + B5 * A5 + B6 * A9 + B7 * A13 - A9 = B8 * A1 + B9 * A5 + B10* A9 + B11* A13 - A13= B12* A1 + B13* A5 + B14* A9 + B15* A13 - - A2 = B0 * A2 + B1 * A6 + B2 * A10+ B3 * A14 - A6 = B4 * A2 + B5 * A6 + B6 * A10+ B7 * A14 - A10= B8 * A2 + B9 * A6 + B10* A10+ B11* A14 - A14= B12* A2 + B13* A6 + B14* A10+ B15* A14 - - A3 = B0 * A3 + B1 * A7 + B2 * A11+ B3 * A15 - A7 = B4 * A3 + B5 * A7 + B6 * A11+ B7 * A15 - A11= B8 * A3 + B9 * A7 + B10* A11+ B11* A15 - A15= B12* A3 + B13* A7 + B14* A11+ B15* A15 - */ - -void m4x4_multiply_by_m4x4( m4x4_t dst, const m4x4_t src ){ - vec_t dst0, dst1, dst2, dst3; - -#if 1 - - dst0 = src[0] * dst[0] + src[1] * dst[4] + src[2] * dst[8] + src[3] * dst[12]; - dst1 = src[4] * dst[0] + src[5] * dst[4] + src[6] * dst[8] + src[7] * dst[12]; - dst2 = src[8] * dst[0] + src[9] * dst[4] + src[10] * dst[8] + src[11] * dst[12]; - dst3 = src[12] * dst[0] + src[13] * dst[4] + src[14] * dst[8] + src[15] * dst[12]; - dst[0] = dst0; dst[4] = dst1; dst[8] = dst2; dst[12] = dst3; - - dst0 = src[0] * dst[1] + src[1] * dst[5] + src[2] * dst[9] + src[3] * dst[13]; - dst1 = src[4] * dst[1] + src[5] * dst[5] + src[6] * dst[9] + src[7] * dst[13]; - dst2 = src[8] * dst[1] + src[9] * dst[5] + src[10] * dst[9] + src[11] * dst[13]; - dst3 = src[12] * dst[1] + src[13] * dst[5] + src[14] * dst[9] + src[15] * dst[13]; - dst[1] = dst0; dst[5] = dst1; dst[9] = dst2; dst[13] = dst3; - - dst0 = src[0] * dst[2] + src[1] * dst[6] + src[2] * dst[10] + src[3] * dst[14]; - dst1 = src[4] * dst[2] + src[5] * dst[6] + src[6] * dst[10] + src[7] * dst[14]; - dst2 = src[8] * dst[2] + src[9] * dst[6] + src[10] * dst[10] + src[11] * dst[14]; - dst3 = src[12] * dst[2] + src[13] * dst[6] + src[14] * dst[10] + src[15] * dst[14]; - dst[2] = dst0; dst[6] = dst1; dst[10] = dst2; dst[14] = dst3; - - dst0 = src[0] * dst[3] + src[1] * dst[7] + src[2] * dst[11] + src[3] * dst[15]; - dst1 = src[4] * dst[3] + src[5] * dst[7] + src[6] * dst[11] + src[7] * dst[15]; - dst2 = src[8] * dst[3] + src[9] * dst[7] + src[10] * dst[11] + src[11] * dst[15]; - dst3 = src[12] * dst[3] + src[13] * dst[7] + src[14] * dst[11] + src[15] * dst[15]; - dst[3] = dst0; dst[7] = dst1; dst[11] = dst2; dst[15] = dst3; - -#else - - vec_t * p = dst; - for ( int i = 0; i < 4; i++ ) - { - dst1 = src[0] * p[0]; - dst1 += src[1] * p[4]; - dst1 += src[2] * p[8]; - dst1 += src[3] * p[12]; - dst2 = src[4] * p[0]; - dst2 += src[5] * p[4]; - dst2 += src[6] * p[8]; - dst2 += src[7] * p[12]; - dst3 = src[8] * p[0]; - dst3 += src[9] * p[4]; - dst3 += src[10] * p[8]; - dst3 += src[11] * p[12]; - dst4 = src[12] * p[0]; - dst4 += src[13] * p[4]; - dst4 += src[14] * p[8]; - dst4 += src[15] * p[12]; - - p[0] = dst1; - p[4] = dst2; - p[8] = dst3; - p[12] = dst4; - p++; - } - -#endif -} - -/* - A = B.A - - A0 = A0 * B0 + A1 * B4 + A2 * B8 + A3 * B12 - A1 = A0 * B1 + A1 * B5 + A2 * B9 + A3 * B13 - A2 = A0 * B2 + A1 * B6 + A2 * B10+ A3 * B14 - A3 = A0 * B3 + A1 * B7 + A2 * B11+ A3 * B15 - - A4 = A4 * B0 + A5 * B4 + A6 * B8 + A7 * B12 - A5 = A4 * B1 + A5 * B5 + A6 * B9 + A7 * B13 - A6 = A4 * B2 + A5 * B6 + A6 * B10+ A7 * B14 - A7 = A4 * B3 + A5 * B7 + A6 * B11+ A7 * B15 - - A8 = A8 * B0 + A9 * B4 + A10* B8 + A11* B12 - A9 = A8 * B1 + A9 * B5 + A10* B9 + A11* B13 - A10= A8 * B2 + A9 * B6 + A10* B10+ A11* B14 - A11= A8 * B3 + A9 * B7 + A10* B11+ A11* B15 - - A12= A12* B0 + A13* B4 + A14* B8 + A15* B12 - A13= A12* B1 + A13* B5 + A14* B9 + A15* B13 - A14= A12* B2 + A13* B6 + A14* B10+ A15* B14 - A15= A12* B3 + A13* B7 + A14* B11+ A15* B15 - */ - -void m4x4_premultiply_by_m4x4( m4x4_t dst, const m4x4_t src ){ - vec_t dst0, dst1, dst2, dst3; - -#if 1 - - dst0 = dst[0] * src[0] + dst[1] * src[4] + dst[2] * src[8] + dst[3] * src[12]; - dst1 = dst[0] * src[1] + dst[1] * src[5] + dst[2] * src[9] + dst[3] * src[13]; - dst2 = dst[0] * src[2] + dst[1] * src[6] + dst[2] * src[10] + dst[3] * src[14]; - dst3 = dst[0] * src[3] + dst[1] * src[7] + dst[2] * src[11] + dst[3] * src[15]; - dst[0] = dst0; dst[1] = dst1; dst[2] = dst2; dst[3] = dst3; - - dst0 = dst[4] * src[0] + dst[5] * src[4] + dst[6] * src[8] + dst[7] * src[12]; - dst1 = dst[4] * src[1] + dst[5] * src[5] + dst[6] * src[9] + dst[7] * src[13]; - dst2 = dst[4] * src[2] + dst[5] * src[6] + dst[6] * src[10] + dst[7] * src[14]; - dst3 = dst[4] * src[3] + dst[5] * src[7] + dst[6] * src[11] + dst[7] * src[15]; - dst[4] = dst0; dst[5] = dst1; dst[6] = dst2; dst[7] = dst3; - - dst0 = dst[8] * src[0] + dst[9] * src[4] + dst[10] * src[8] + dst[11] * src[12]; - dst1 = dst[8] * src[1] + dst[9] * src[5] + dst[10] * src[9] + dst[11] * src[13]; - dst2 = dst[8] * src[2] + dst[9] * src[6] + dst[10] * src[10] + dst[11] * src[14]; - dst3 = dst[8] * src[3] + dst[9] * src[7] + dst[10] * src[11] + dst[11] * src[15]; - dst[8] = dst0; dst[9] = dst1; dst[10] = dst2; dst[11] = dst3; - - dst0 = dst[12] * src[0] + dst[13] * src[4] + dst[14] * src[8] + dst[15] * src[12]; - dst1 = dst[12] * src[1] + dst[13] * src[5] + dst[14] * src[9] + dst[15] * src[13]; - dst2 = dst[12] * src[2] + dst[13] * src[6] + dst[14] * src[10] + dst[15] * src[14]; - dst3 = dst[12] * src[3] + dst[13] * src[7] + dst[14] * src[11] + dst[15] * src[15]; - dst[12] = dst0; dst[13] = dst1; dst[14] = dst2; dst[15] = dst3; - -#else - - vec_t* p = dst; - for ( int i = 0; i < 4; i++ ) - { - dst1 = src[0] * p[0]; - dst2 = src[1] * p[0]; - dst3 = src[2] * p[0]; - dst4 = src[3] * p[0]; - dst1 += src[4] * p[1]; - dst2 += src[5] * p[1]; - dst3 += src[6] * p[1]; - dst4 += src[7] * p[1]; - dst1 += src[8] * p[2]; - dst2 += src[9] * p[2]; - dst4 += src[11] * p[2]; - dst3 += src[10] * p[2]; - dst1 += src[12] * p[3]; - dst2 += src[13] * p[3]; - dst3 += src[14] * p[3]; - dst4 += src[15] * p[3]; - - *p++ = dst1; - *p++ = dst2; - *p++ = dst3; - *p++ = dst4; - } - -#endif -} - -void m4x4_orthogonal_multiply_by_m4x4( m4x4_t dst, const m4x4_t src ){ - vec_t dst0, dst1, dst2, dst3; - - dst0 = src[0] * dst[0] + src[1] * dst[4] + src[2] * dst[8]; - dst1 = src[4] * dst[0] + src[5] * dst[4] + src[6] * dst[8]; - dst2 = src[8] * dst[0] + src[9] * dst[4] + src[10] * dst[8]; - dst3 = src[12] * dst[0] + src[13] * dst[4] + src[14] * dst[8] + dst[12]; - dst[0] = dst0; dst[4] = dst1; dst[8] = dst2; dst[12] = dst3; - - dst0 = src[0] * dst[1] + src[1] * dst[5] + src[2] * dst[9]; - dst1 = src[4] * dst[1] + src[5] * dst[5] + src[6] * dst[9]; - dst2 = src[8] * dst[1] + src[9] * dst[5] + src[10] * dst[9]; - dst3 = src[12] * dst[1] + src[13] * dst[5] + src[14] * dst[9] + dst[13]; - dst[1] = dst0; dst[5] = dst1; dst[9] = dst2; dst[13] = dst3; - - dst0 = src[0] * dst[2] + src[1] * dst[6] + src[2] * dst[10]; - dst1 = src[4] * dst[2] + src[5] * dst[6] + src[6] * dst[10]; - dst2 = src[8] * dst[2] + src[9] * dst[6] + src[10] * dst[10]; - dst3 = src[12] * dst[2] + src[13] * dst[6] + src[14] * dst[10] + dst[14]; - dst[2] = dst0; dst[6] = dst1; dst[10] = dst2; dst[14] = dst3; -} - -void m4x4_orthogonal_premultiply_by_m4x4( m4x4_t dst, const m4x4_t src ){ - vec_t dst0, dst1, dst2; - - dst0 = dst[0] * src[0] + dst[1] * src[4] + dst[2] * src[8]; - dst1 = dst[0] * src[1] + dst[1] * src[5] + dst[2] * src[9]; - dst2 = dst[0] * src[2] + dst[1] * src[6] + dst[2] * src[10]; - dst[0] = dst0; dst[1] = dst1; dst[2] = dst2; - - dst0 = dst[4] * src[0] + dst[5] * src[4] + dst[6] * src[8]; - dst1 = dst[4] * src[1] + dst[5] * src[5] + dst[6] * src[9]; - dst2 = dst[4] * src[2] + dst[5] * src[6] + dst[6] * src[10]; - dst[4] = dst0; dst[5] = dst1; dst[6] = dst2; - - dst0 = dst[8] * src[0] + dst[9] * src[4] + dst[10] * src[8]; - dst1 = dst[8] * src[1] + dst[9] * src[5] + dst[10] * src[9]; - dst2 = dst[8] * src[2] + dst[9] * src[6] + dst[10] * src[10]; - dst[8] = dst0; dst[9] = dst1; dst[10] = dst2; - - dst0 = dst[12] * src[0] + dst[13] * src[4] + dst[14] * src[8] + dst[15] * src[12]; - dst1 = dst[12] * src[1] + dst[13] * src[5] + dst[14] * src[9] + dst[15] * src[13]; - dst2 = dst[12] * src[2] + dst[13] * src[6] + dst[14] * src[10] + dst[15] * src[14]; - dst[12] = dst0; dst[13] = dst1; dst[14] = dst2; -} - -void m4x4_transform_point( const m4x4_t matrix, vec3_t point ){ - float out1, out2, out3; - - out1 = matrix[0] * point[0] + matrix[4] * point[1] + matrix[8] * point[2] + matrix[12]; - out2 = matrix[1] * point[0] + matrix[5] * point[1] + matrix[9] * point[2] + matrix[13]; - out3 = matrix[2] * point[0] + matrix[6] * point[1] + matrix[10] * point[2] + matrix[14]; - - point[0] = out1; - point[1] = out2; - point[2] = out3; -} - -void m4x4_transform_normal( const m4x4_t matrix, vec3_t normal ){ - float out1, out2, out3; - - out1 = matrix[0] * normal[0] + matrix[4] * normal[1] + matrix[8] * normal[2]; - out2 = matrix[1] * normal[0] + matrix[5] * normal[1] + matrix[9] * normal[2]; - out3 = matrix[2] * normal[0] + matrix[6] * normal[1] + matrix[10] * normal[2]; - - normal[0] = out1; - normal[1] = out2; - normal[2] = out3; -} - -void m4x4_transform_vec4( const m4x4_t matrix, vec4_t vector ){ - float out1, out2, out3, out4; - - out1 = matrix[0] * vector[0] + matrix[4] * vector[1] + matrix[8] * vector[2] + matrix[12] * vector[3]; - out2 = matrix[1] * vector[0] + matrix[5] * vector[1] + matrix[9] * vector[2] + matrix[13] * vector[3]; - out3 = matrix[2] * vector[0] + matrix[6] * vector[1] + matrix[10] * vector[2] + matrix[14] * vector[3]; - out4 = matrix[3] * vector[0] + matrix[7] * vector[1] + matrix[11] * vector[2] + matrix[15] * vector[3]; - - vector[0] = out1; - vector[1] = out2; - vector[2] = out3; - vector[3] = out4; -} - -#define CLIP_X_LT_W( p ) ( ( p )[0] < ( p )[3] ) -#define CLIP_X_GT_W( p ) ( ( p )[0] > -( p )[3] ) -#define CLIP_Y_LT_W( p ) ( ( p )[1] < ( p )[3] ) -#define CLIP_Y_GT_W( p ) ( ( p )[1] > -( p )[3] ) -#define CLIP_Z_LT_W( p ) ( ( p )[2] < ( p )[3] ) -#define CLIP_Z_GT_W( p ) ( ( p )[2] > -( p )[3] ) - -clipmask_t homogenous_clip_point( const vec4_t clipped ){ - clipmask_t result = CLIP_FAIL; - if ( CLIP_X_LT_W( clipped ) ) { - result &= ~CLIP_LT_X; // X < W - } - if ( CLIP_X_GT_W( clipped ) ) { - result &= ~CLIP_GT_X; // X > -W - } - if ( CLIP_Y_LT_W( clipped ) ) { - result &= ~CLIP_LT_Y; // Y < W - } - if ( CLIP_Y_GT_W( clipped ) ) { - result &= ~CLIP_GT_Y; // Y > -W - } - if ( CLIP_Z_LT_W( clipped ) ) { - result &= ~CLIP_LT_Z; // Z < W - } - if ( CLIP_Z_GT_W( clipped ) ) { - result &= ~CLIP_GT_Z; // Z > -W - } - return result; -} - -clipmask_t m4x4_clip_point( const m4x4_t matrix, const vec3_t point, vec4_t clipped ){ - clipped[0] = point[0]; - clipped[1] = point[1]; - clipped[2] = point[2]; - clipped[3] = 1; - m4x4_transform_vec4( matrix, clipped ); - return homogenous_clip_point( clipped ); -} - - -unsigned int homogenous_clip_triangle( vec4_t clipped[9] ){ - vec4_t buffer[9]; - unsigned int rcount = 3; - unsigned int wcount = 0; - vec_t const* rptr = clipped[0]; - vec_t* wptr = buffer[0]; - const vec_t* p0; - const vec_t* p1; - unsigned char b0, b1; - - unsigned int i; - double scale; - - p0 = rptr; - b0 = CLIP_X_LT_W( p0 ); - for ( i = 0; i < rcount; ++i ) - { - p1 = ( i + 1 != rcount ) ? p0 + 4 : rptr; - b1 = CLIP_X_LT_W( p1 ); - if ( b0 ^ b1 ) { - wptr[0] = p1[0] - p0[0]; - wptr[1] = p1[1] - p0[1]; - wptr[2] = p1[2] - p0[2]; - wptr[3] = p1[3] - p0[3]; - - scale = ( p0[0] - p0[3] ) / ( wptr[3] - wptr[0] ); - - wptr[0] = (vec_t)( p0[0] + scale * ( wptr[0] ) ); - wptr[1] = (vec_t)( p0[1] + scale * ( wptr[1] ) ); - wptr[2] = (vec_t)( p0[2] + scale * ( wptr[2] ) ); - wptr[3] = (vec_t)( p0[3] + scale * ( wptr[3] ) ); - - wptr += 4; - ++wcount; - } - - if ( b1 ) { - wptr[0] = p1[0]; - wptr[1] = p1[1]; - wptr[2] = p1[2]; - wptr[3] = p1[3]; - - wptr += 4; - ++wcount; - } - - p0 = p1; - b0 = b1; - } - - rcount = wcount; - wcount = 0; - rptr = buffer[0]; - wptr = clipped[0]; - p0 = rptr; - b0 = CLIP_X_GT_W( p0 ); - - for ( i = 0; i < rcount; ++i ) - { - p1 = ( i + 1 != rcount ) ? p0 + 4 : rptr; - b1 = CLIP_X_GT_W( p1 ); - if ( b0 ^ b1 ) { - wptr[0] = p1[0] - p0[0]; - wptr[1] = p1[1] - p0[1]; - wptr[2] = p1[2] - p0[2]; - wptr[3] = p1[3] - p0[3]; - - scale = ( p0[0] + p0[3] ) / ( -wptr[3] - wptr[0] ); - - wptr[0] = (vec_t)( p0[0] + scale * ( wptr[0] ) ); - wptr[1] = (vec_t)( p0[1] + scale * ( wptr[1] ) ); - wptr[2] = (vec_t)( p0[2] + scale * ( wptr[2] ) ); - wptr[3] = (vec_t)( p0[3] + scale * ( wptr[3] ) ); - - wptr += 4; - ++wcount; - } - - if ( b1 ) { - wptr[0] = p1[0]; - wptr[1] = p1[1]; - wptr[2] = p1[2]; - wptr[3] = p1[3]; - - wptr += 4; - ++wcount; - } - - p0 = p1; - b0 = b1; - } - - rcount = wcount; - wcount = 0; - rptr = clipped[0]; - wptr = buffer[0]; - p0 = rptr; - b0 = CLIP_Y_LT_W( p0 ); - - for ( i = 0; i < rcount; ++i ) - { - p1 = ( i + 1 != rcount ) ? p0 + 4 : rptr; - b1 = CLIP_Y_LT_W( p1 ); - if ( b0 ^ b1 ) { - wptr[0] = p1[0] - p0[0]; - wptr[1] = p1[1] - p0[1]; - wptr[2] = p1[2] - p0[2]; - wptr[3] = p1[3] - p0[3]; - - scale = ( p0[1] - p0[3] ) / ( wptr[3] - wptr[1] ); - - wptr[0] = (vec_t)( p0[0] + scale * ( wptr[0] ) ); - wptr[1] = (vec_t)( p0[1] + scale * ( wptr[1] ) ); - wptr[2] = (vec_t)( p0[2] + scale * ( wptr[2] ) ); - wptr[3] = (vec_t)( p0[3] + scale * ( wptr[3] ) ); - - wptr += 4; - ++wcount; - } - - if ( b1 ) { - wptr[0] = p1[0]; - wptr[1] = p1[1]; - wptr[2] = p1[2]; - wptr[3] = p1[3]; - - wptr += 4; - ++wcount; - } - - p0 = p1; - b0 = b1; - } - - rcount = wcount; - wcount = 0; - rptr = buffer[0]; - wptr = clipped[0]; - p0 = rptr; - b0 = CLIP_Y_GT_W( p0 ); - - for ( i = 0; i < rcount; ++i ) - { - p1 = ( i + 1 != rcount ) ? p0 + 4 : rptr; - b1 = CLIP_Y_GT_W( p1 ); - if ( b0 ^ b1 ) { - wptr[0] = p1[0] - p0[0]; - wptr[1] = p1[1] - p0[1]; - wptr[2] = p1[2] - p0[2]; - wptr[3] = p1[3] - p0[3]; - - scale = ( p0[1] + p0[3] ) / ( -wptr[3] - wptr[1] ); - - wptr[0] = (vec_t)( p0[0] + scale * ( wptr[0] ) ); - wptr[1] = (vec_t)( p0[1] + scale * ( wptr[1] ) ); - wptr[2] = (vec_t)( p0[2] + scale * ( wptr[2] ) ); - wptr[3] = (vec_t)( p0[3] + scale * ( wptr[3] ) ); - - wptr += 4; - ++wcount; - } - - if ( b1 ) { - wptr[0] = p1[0]; - wptr[1] = p1[1]; - wptr[2] = p1[2]; - wptr[3] = p1[3]; - - wptr += 4; - ++wcount; - } - - p0 = p1; - b0 = b1; - } - - rcount = wcount; - wcount = 0; - rptr = clipped[0]; - wptr = buffer[0]; - p0 = rptr; - b0 = CLIP_Z_LT_W( p0 ); - - for ( i = 0; i < rcount; ++i ) - { - p1 = ( i + 1 != rcount ) ? p0 + 4 : rptr; - b1 = CLIP_Z_LT_W( p1 ); - if ( b0 ^ b1 ) { - wptr[0] = p1[0] - p0[0]; - wptr[1] = p1[1] - p0[1]; - wptr[2] = p1[2] - p0[2]; - wptr[3] = p1[3] - p0[3]; - - scale = ( p0[2] - p0[3] ) / ( wptr[3] - wptr[2] ); - - wptr[0] = (vec_t)( p0[0] + scale * ( wptr[0] ) ); - wptr[1] = (vec_t)( p0[1] + scale * ( wptr[1] ) ); - wptr[2] = (vec_t)( p0[2] + scale * ( wptr[2] ) ); - wptr[3] = (vec_t)( p0[3] + scale * ( wptr[3] ) ); - - wptr += 4; - ++wcount; - } - - if ( b1 ) { - wptr[0] = p1[0]; - wptr[1] = p1[1]; - wptr[2] = p1[2]; - wptr[3] = p1[3]; - - wptr += 4; - ++wcount; - } - - p0 = p1; - b0 = b1; - } - - rcount = wcount; - wcount = 0; - rptr = buffer[0]; - wptr = clipped[0]; - p0 = rptr; - b0 = CLIP_Z_GT_W( p0 ); - - for ( i = 0; i < rcount; ++i ) - { - p1 = ( i + 1 != rcount ) ? p0 + 4 : rptr; - b1 = CLIP_Z_GT_W( p1 ); - if ( b0 ^ b1 ) { - wptr[0] = p1[0] - p0[0]; - wptr[1] = p1[1] - p0[1]; - wptr[2] = p1[2] - p0[2]; - wptr[3] = p1[3] - p0[3]; - - scale = ( p0[2] + p0[3] ) / ( -wptr[3] - wptr[2] ); - - wptr[0] = (vec_t)( p0[0] + scale * ( wptr[0] ) ); - wptr[1] = (vec_t)( p0[1] + scale * ( wptr[1] ) ); - wptr[2] = (vec_t)( p0[2] + scale * ( wptr[2] ) ); - wptr[3] = (vec_t)( p0[3] + scale * ( wptr[3] ) ); - - wptr += 4; - ++wcount; - } - - if ( b1 ) { - wptr[0] = p1[0]; - wptr[1] = p1[1]; - wptr[2] = p1[2]; - wptr[3] = p1[3]; - - wptr += 4; - ++wcount; - } - - p0 = p1; - b0 = b1; - } - - return wcount; -} - -unsigned int m4x4_clip_triangle( const m4x4_t matrix, const vec3_t p0, const vec3_t p1, const vec3_t p2, vec4_t clipped[9] ){ - clipped[0][0] = p0[0]; - clipped[0][1] = p0[1]; - clipped[0][2] = p0[2]; - clipped[0][3] = 1; - clipped[1][0] = p1[0]; - clipped[1][1] = p1[1]; - clipped[1][2] = p1[2]; - clipped[1][3] = 1; - clipped[2][0] = p2[0]; - clipped[2][1] = p2[1]; - clipped[2][2] = p2[2]; - clipped[2][3] = 1; - - m4x4_transform_vec4( matrix, clipped[0] ); - m4x4_transform_vec4( matrix, clipped[1] ); - m4x4_transform_vec4( matrix, clipped[2] ); - - return homogenous_clip_triangle( clipped ); -} - -unsigned int homogenous_clip_line( vec4_t clipped[2] ){ - vec4_t clip; - double scale; - const vec_t* const p0 = clipped[0]; - const vec_t* const p1 = clipped[1]; - - // early out - { - clipmask_t mask0 = homogenous_clip_point( clipped[0] ); - clipmask_t mask1 = homogenous_clip_point( clipped[1] ); - - if ( ( mask0 | mask1 ) == CLIP_PASS ) { // both points passed all planes - return 2; - } - - if ( mask0 & mask1 ) { // both points failed any one plane - return 0; - } - } - - { - const unsigned int index = CLIP_X_LT_W( p0 ); - if ( index ^ CLIP_X_LT_W( p1 ) ) { - clip[0] = p1[0] - p0[0]; - clip[1] = p1[1] - p0[1]; - clip[2] = p1[2] - p0[2]; - clip[3] = p1[3] - p0[3]; - - scale = ( p0[0] - p0[3] ) / ( clip[3] - clip[0] ); - - clip[0] = (vec_t)( p0[0] + scale * ( clip[0] ) ); - clip[1] = (vec_t)( p0[1] + scale * ( clip[1] ) ); - clip[2] = (vec_t)( p0[2] + scale * ( clip[2] ) ); - clip[3] = (vec_t)( p0[3] + scale * ( clip[3] ) ); - - clipped[index][0] = clip[0]; - clipped[index][1] = clip[1]; - clipped[index][2] = clip[2]; - clipped[index][3] = clip[3]; - } - else if ( index == 0 ) { - return 0; - } - } - - { - const unsigned int index = CLIP_X_GT_W( p0 ); - if ( index ^ CLIP_X_GT_W( p1 ) ) { - clip[0] = p1[0] - p0[0]; - clip[1] = p1[1] - p0[1]; - clip[2] = p1[2] - p0[2]; - clip[3] = p1[3] - p0[3]; - - scale = ( p0[0] + p0[3] ) / ( -clip[3] - clip[0] ); - - clip[0] = (vec_t)( p0[0] + scale * ( clip[0] ) ); - clip[1] = (vec_t)( p0[1] + scale * ( clip[1] ) ); - clip[2] = (vec_t)( p0[2] + scale * ( clip[2] ) ); - clip[3] = (vec_t)( p0[3] + scale * ( clip[3] ) ); - - clipped[index][0] = clip[0]; - clipped[index][1] = clip[1]; - clipped[index][2] = clip[2]; - clipped[index][3] = clip[3]; - } - else if ( index == 0 ) { - return 0; - } - } - - { - const unsigned int index = CLIP_Y_LT_W( p0 ); - if ( index ^ CLIP_Y_LT_W( p1 ) ) { - clip[0] = p1[0] - p0[0]; - clip[1] = p1[1] - p0[1]; - clip[2] = p1[2] - p0[2]; - clip[3] = p1[3] - p0[3]; - - scale = ( p0[1] - p0[3] ) / ( clip[3] - clip[1] ); - - clip[0] = (vec_t)( p0[0] + scale * ( clip[0] ) ); - clip[1] = (vec_t)( p0[1] + scale * ( clip[1] ) ); - clip[2] = (vec_t)( p0[2] + scale * ( clip[2] ) ); - clip[3] = (vec_t)( p0[3] + scale * ( clip[3] ) ); - - clipped[index][0] = clip[0]; - clipped[index][1] = clip[1]; - clipped[index][2] = clip[2]; - clipped[index][3] = clip[3]; - } - else if ( index == 0 ) { - return 0; - } - } - - { - const unsigned int index = CLIP_Y_GT_W( p0 ); - if ( index ^ CLIP_Y_GT_W( p1 ) ) { - clip[0] = p1[0] - p0[0]; - clip[1] = p1[1] - p0[1]; - clip[2] = p1[2] - p0[2]; - clip[3] = p1[3] - p0[3]; - - scale = ( p0[1] + p0[3] ) / ( -clip[3] - clip[1] ); - - clip[0] = (vec_t)( p0[0] + scale * ( clip[0] ) ); - clip[1] = (vec_t)( p0[1] + scale * ( clip[1] ) ); - clip[2] = (vec_t)( p0[2] + scale * ( clip[2] ) ); - clip[3] = (vec_t)( p0[3] + scale * ( clip[3] ) ); - - clipped[index][0] = clip[0]; - clipped[index][1] = clip[1]; - clipped[index][2] = clip[2]; - clipped[index][3] = clip[3]; - } - else if ( index == 0 ) { - return 0; - } - } - - { - const unsigned int index = CLIP_Z_LT_W( p0 ); - if ( index ^ CLIP_Z_LT_W( p1 ) ) { - clip[0] = p1[0] - p0[0]; - clip[1] = p1[1] - p0[1]; - clip[2] = p1[2] - p0[2]; - clip[3] = p1[3] - p0[3]; - - scale = ( p0[2] - p0[3] ) / ( clip[3] - clip[2] ); - - clip[0] = (vec_t)( p0[0] + scale * ( clip[0] ) ); - clip[1] = (vec_t)( p0[1] + scale * ( clip[1] ) ); - clip[2] = (vec_t)( p0[2] + scale * ( clip[2] ) ); - clip[3] = (vec_t)( p0[3] + scale * ( clip[3] ) ); - - clipped[index][0] = clip[0]; - clipped[index][1] = clip[1]; - clipped[index][2] = clip[2]; - clipped[index][3] = clip[3]; - } - else if ( index == 0 ) { - return 0; - } - } - - { - const unsigned int index = CLIP_Z_GT_W( p0 ); - if ( index ^ CLIP_Z_GT_W( p1 ) ) { - clip[0] = p1[0] - p0[0]; - clip[1] = p1[1] - p0[1]; - clip[2] = p1[2] - p0[2]; - clip[3] = p1[3] - p0[3]; - - scale = ( p0[2] + p0[3] ) / ( -clip[3] - clip[2] ); - - clip[0] = (vec_t)( p0[0] + scale * ( clip[0] ) ); - clip[1] = (vec_t)( p0[1] + scale * ( clip[1] ) ); - clip[2] = (vec_t)( p0[2] + scale * ( clip[2] ) ); - clip[3] = (vec_t)( p0[3] + scale * ( clip[3] ) ); - - clipped[index][0] = clip[0]; - clipped[index][1] = clip[1]; - clipped[index][2] = clip[2]; - clipped[index][3] = clip[3]; - } - else if ( index == 0 ) { - return 0; - } - } - - return 2; -} - -unsigned int m4x4_clip_line( const m4x4_t matrix, const vec3_t p0, const vec3_t p1, vec4_t clipped[2] ){ - clipped[0][0] = p0[0]; - clipped[0][1] = p0[1]; - clipped[0][2] = p0[2]; - clipped[0][3] = 1; - clipped[1][0] = p1[0]; - clipped[1][1] = p1[1]; - clipped[1][2] = p1[2]; - clipped[1][3] = 1; - - m4x4_transform_vec4( matrix, clipped[0] ); - m4x4_transform_vec4( matrix, clipped[1] ); - - return homogenous_clip_line( clipped ); -} - -void m4x4_transpose( m4x4_t matrix ){ - int i, j; - float temp, *p1, *p2; - - for ( i = 1; i < 4; i++ ) { - for ( j = 0; j < i; j++ ) { - p1 = matrix + ( j * 4 + i ); - p2 = matrix + ( i * 4 + j ); - temp = *p1; - *p1 = *p2; - *p2 = temp; - } - } -} - -/* adapted from Graphics Gems 2 - invert a 3d matrix (4x3) */ -int m4x4_orthogonal_invert( m4x4_t matrix ){ - m4x4_t temp; - vec_t* src = temp; - - m4x4_assign( src, matrix ); - - /* Calculate the determinant of upper left 3x3 submatrix and - * determine if the matrix is singular. - */ - { -#if 0 - float pos = 0.0f; - float neg = 0.0f; - float det = src[0] * src[5] * src[10]; - if ( det >= 0.0 ) { - pos += det; - } - else{ neg += det; } - - det = src[1] * src[6] * src[8]; - if ( det >= 0.0 ) { - pos += det; - } - else{ neg += det; } - - det = src[2] * src[4] * src[9]; - if ( det >= 0.0 ) { - pos += det; - } - else{ neg += det; } - - det = -src[2] * src[5] * src[8]; - if ( det >= 0.0 ) { - pos += det; - } - else{ neg += det; } - - det = -src[1] * src[4] * src[10]; - if ( det >= 0.0 ) { - pos += det; - } - else{ neg += det; } - - det = -src[0] * src[6] * src[9]; - if ( det >= 0.0 ) { - pos += det; - } - else{ neg += det; } - - det = pos + neg; -#elif 0 - float det - = ( src[0] * src[5] * src[10] ) - + ( src[1] * src[6] * src[8] ) - + ( src[2] * src[4] * src[9] ) - - ( src[2] * src[5] * src[8] ) - - ( src[1] * src[4] * src[10] ) - - ( src[0] * src[6] * src[9] ); -#else - float det - = src[0] * ( src[5] * src[10] - src[9] * src[6] ) - - src[1] * ( src[4] * src[10] - src[8] * src[6] ) - + src[2] * ( src[4] * src[9] - src[8] * src[5] ); - -#endif - - if ( det * det < 1e-25 ) { - return 1; - } - - det = 1.0f / det; - matrix[0] = ( ( src[5] * src[10] - src[6] * src[9] ) * det ); - matrix[1] = ( -( src[1] * src[10] - src[2] * src[9] ) * det ); - matrix[2] = ( ( src[1] * src[6] - src[2] * src[5] ) * det ); - matrix[4] = ( -( src[4] * src[10] - src[6] * src[8] ) * det ); - matrix[5] = ( ( src[0] * src[10] - src[2] * src[8] ) * det ); - matrix[6] = ( -( src[0] * src[6] - src[2] * src[4] ) * det ); - matrix[8] = ( ( src[4] * src[9] - src[5] * src[8] ) * det ); - matrix[9] = ( -( src[0] * src[9] - src[1] * src[8] ) * det ); - matrix[10] = ( ( src[0] * src[5] - src[1] * src[4] ) * det ); - } - - /* Do the translation part */ - matrix[12] = -( src[12] * matrix[0] + - src[13] * matrix[4] + - src[14] * matrix[8] ); - matrix[13] = -( src[12] * matrix[1] + - src[13] * matrix[5] + - src[14] * matrix[9] ); - matrix[14] = -( src[12] * matrix[2] + - src[13] * matrix[6] + - src[14] * matrix[10] ); - - return 0; -} - -void quat_identity( vec4_t quat ){ - quat[0] = quat[1] = quat[2] = 0; - quat[3] = 1; -} - -void quat_multiply_by_quat( vec4_t quat, const vec4_t other ){ - const vec_t x = quat[3] * other[0] + quat[0] * other[3] + quat[1] * other[2] - quat[2] * other[1]; - const vec_t y = quat[3] * other[1] + quat[1] * other[3] + quat[2] * other[0] - quat[0] * other[2]; - const vec_t z = quat[3] * other[2] + quat[2] * other[3] + quat[0] * other[1] - quat[1] * other[0]; - const vec_t w = quat[3] * other[3] - quat[0] * other[0] - quat[1] * other[1] - quat[2] * other[2]; - quat[0] = x; - quat[1] = y; - quat[2] = z; - quat[3] = w; -} - -void quat_conjugate( vec4_t quat ){ - VectorNegate( quat, quat ); -} - -//! quaternion from two unit vectors -void quat_for_unit_vectors( vec4_t quat, const vec3_t from, const vec3_t to ){ - CrossProduct( from, to, quat ); - quat[3] = DotProduct( from, to ); -} - -void quat_normalise( vec4_t quat ){ - const vec_t n = 1 / ( quat[0] * quat[0] + quat[1] * quat[1] + quat[2] * quat[2] + quat[3] * quat[3] ); - quat[0] *= n; - quat[1] *= n; - quat[2] *= n; - quat[3] *= n; -} - -void quat_for_axisangle( vec4_t quat, const vec3_t axis, double angle ){ - angle *= 0.5; - - quat[3] = (float)sin( angle ); - - quat[0] = axis[0] * quat[3]; - quat[1] = axis[1] * quat[3]; - quat[2] = axis[2] * quat[3]; - quat[3] = (float)cos( angle ); -} - -void m3x3_multiply_by_m3x3( m3x3_t matrix, const m3x3_t matrix_src ){ - float *pDest = matrix; - float out1, out2, out3; - int i; - - for ( i = 0; i < 3; i++ ) - { - out1 = matrix_src[0] * pDest[0]; - out1 += matrix_src[1] * pDest[3]; - out1 += matrix_src[2] * pDest[6]; - out2 = matrix_src[3] * pDest[0]; - out2 += matrix_src[4] * pDest[3]; - out2 += matrix_src[5] * pDest[6]; - out3 = matrix_src[6] * pDest[0]; - out3 += matrix_src[7] * pDest[3]; - out3 += matrix_src[8] * pDest[6]; - - pDest[0] = out1; - pDest[3] = out2; - pDest[6] = out3; - - pDest++; - } -} - -void m3x3_transform_vec3( const m3x3_t matrix, vec3_t vector ){ - float out1, out2, out3; - - out1 = matrix[0] * vector[0]; - out1 += matrix[3] * vector[1]; - out1 += matrix[6] * vector[2]; - out2 = matrix[1] * vector[0]; - out2 += matrix[4] * vector[1]; - out2 += matrix[7] * vector[2]; - out3 = matrix[2] * vector[0]; - out3 += matrix[5] * vector[1]; - out3 += matrix[8] * vector[2]; - - vector[0] = out1; - vector[1] = out2; - vector[2] = out3; -} - -float m3_det( m3x3_t mat ){ - float det; - - det = mat[0] * ( mat[4] * mat[8] - mat[7] * mat[5] ) - - mat[1] * ( mat[3] * mat[8] - mat[6] * mat[5] ) - + mat[2] * ( mat[3] * mat[7] - mat[6] * mat[4] ); - - return( det ); -} - -int m3_inverse( m3x3_t mr, m3x3_t ma ){ - float det = m3_det( ma ); - - if ( det == 0 ) { - return 1; - } - - - mr[0] = ma[4] * ma[8] - ma[5] * ma[7] / det; - mr[1] = -( ma[1] * ma[8] - ma[7] * ma[2] ) / det; - mr[2] = ma[1] * ma[5] - ma[4] * ma[2] / det; - - mr[3] = -( ma[3] * ma[8] - ma[5] * ma[6] ) / det; - mr[4] = ma[0] * ma[8] - ma[6] * ma[2] / det; - mr[5] = -( ma[0] * ma[5] - ma[3] * ma[2] ) / det; - - mr[6] = ma[3] * ma[7] - ma[6] * ma[4] / det; - mr[7] = -( ma[0] * ma[7] - ma[6] * ma[1] ) / det; - mr[8] = ma[0] * ma[4] - ma[1] * ma[3] / det; - - return 0; -} - -void m4_submat( m4x4_t mr, m3x3_t mb, int i, int j ){ - int ti, tj, idst, jdst; - - for ( ti = 0; ti < 4; ti++ ) - { - if ( ti < i ) { - idst = ti; - } - else - if ( ti > i ) { - idst = ti - 1; - } - - for ( tj = 0; tj < 4; tj++ ) - { - if ( tj < j ) { - jdst = tj; - } - else - if ( tj > j ) { - jdst = tj - 1; - } - - if ( ti != i && tj != j ) { - mb[idst * 3 + jdst] = mr[ti * 4 + tj ]; - } - } - } -} - -float m4_det( m4x4_t mr ){ - float det, result = 0, i = 1; - m3x3_t msub3; - int n; - - for ( n = 0; n < 4; n++, i *= -1 ) - { - m4_submat( mr, msub3, 0, n ); - - det = m3_det( msub3 ); - result += mr[n] * det * i; - } - - return result; -} - -int m4x4_invert( m4x4_t matrix ){ - float mdet = m4_det( matrix ); - m3x3_t mtemp; - int i, j, sign; - m4x4_t m4x4_temp; - -#if 0 - if ( fabs( mdet ) < 0.0000000001 ) { - return 1; - } -#endif - - m4x4_assign( m4x4_temp, matrix ); - - for ( i = 0; i < 4; i++ ) - for ( j = 0; j < 4; j++ ) - { - sign = 1 - ( ( i + j ) % 2 ) * 2; - - m4_submat( m4x4_temp, mtemp, i, j ); - - matrix[i + j * 4] = ( m3_det( mtemp ) * sign ) / mdet; /* FIXME: try using * inverse det and see if speed/accuracy are good enough */ - } - - return 0; -} -#if 0 -void m4x4_solve_ge( m4x4_t matrix, vec4_t x ){ - int indx[4]; - int c,r; - int i; - int best; - float scale[4]; - float f, pivot; - float aug[4]; - float recip, ratio; - float* p; - - for ( r = 0; r < 4; r++ ) - { - aug[r] = 0; - indx[r] = r; - } - - for ( r = 0; r < 4; r++ ) - { - scale[r] = 0; - for ( c = 0; c < 4; c++, p++ ) - { - if ( fabs( *p ) > scale[r] ) { - scale[r] = (float)fabs( *p ); - } - } - } - - for ( c = 0; c < 3; c++ ) - { - pivot = 0; - for ( r = c; r < 4; r++ ) - { - f = (float)fabs( matrix[( indx[r] << 2 ) + c] ) / scale[indx[r]]; - if ( f > pivot ) { - pivot = f; - best = r; - } - } - - i = indx[c]; - indx[c] = indx[best]; - indx[best] = i; - - recip = 1 / matrix[( indx[c] << 2 ) + c]; - - for ( r = c + 1; r < 4; r++ ) - { - p = matrix + ( indx[r] << 2 ); - ratio = p[c] * recip; - - for ( i = c + 1; i < 4; i++ ) - p[i] -= ratio * matrix[( indx[c] << 2 ) + i]; - aug[indx[r]] -= ratio * aug[indx[c]]; - } - } - - x[indx[3]] = aug[indx[3]] / matrix[( indx[3] << 2 ) + 3]; - for ( r = 2; r >= 0; r-- ) - { - f = aug[indx[r]]; - p = matrix + ( indx[r] << 2 ); - recip = 1 / p[r]; - for ( c = ( r + 1 ); c < 4; c++ ) - { - f -= ( p[c] * x[indx[c]] ); - } - x[indx[r]] = f * recip; - } -} -#endif - -#define N 3 - -int matrix_solve_ge( vec_t* matrix, vec_t* aug, vec3_t x ){ - int indx[N]; - int c,r; - int i; - int best; - float scale[N]; - float f, pivot; - float ratio; - float* p; - - for ( r = 0; r < N; r++ ) - { - indx[r] = r; - } - - for ( r = 0; r < N; r++ ) - { - p = matrix + r; - scale[r] = 0; - for ( c = 0; c < N; c++, p++ ) - { - if ( fabs( *p ) > scale[r] ) { - scale[r] = (float)fabs( *p ); - } - } - } - - for ( c = 0; c < N; c++ ) - { - pivot = 0; - best = -1; - for ( r = c; r < N; r++ ) - { - f = (float)fabs( matrix[( indx[r] * N ) + c] ) / scale[indx[r]]; - if ( f > pivot ) { - pivot = f; - best = r; - } - } - - if ( best == -1 ) { - return 1; - } - - i = indx[c]; - indx[c] = indx[best]; - indx[best] = i; - - for ( r = c + 1; r < N; r++ ) - { - p = matrix + ( indx[r] * N ); - ratio = p[c] / matrix[( indx[c] * N ) + c]; - - for ( i = c + 1; i < N; i++ ) p[i] -= ratio * matrix[( indx[c] * N ) + i]; - aug[indx[r]] -= ratio * aug[indx[c]]; - } - } - - x[N - 1] = aug[indx[N - 1]] / matrix[( indx[N - 1] * N ) + N - 1]; - for ( r = 1; r >= 0; r-- ) - { - f = aug[indx[r]]; - p = matrix + ( indx[r] * N ); - for ( c = ( r + 1 ); c < N; c++ ) f -= ( p[c] * x[c] ); - x[r] = f / p[r]; - } - return 0; -} - -#ifdef YOU_WANT_IT_TO_BORK -/* Gaussian elimination */ -for ( i = 0; i < 4; i++ ) -{ - for ( j = ( i + 1 ); j < 4; j++ ) - { - ratio = matrix[j][i] / matrix[i][i]; - for ( count = i; count < n; count++ ) { - matrix[j][count] -= ( ratio * matrix[i][count] ); - } - b[j] -= ( ratio * b[i] ); - } -} - -/* Back substitution */ -x[n - 1] = b[n - 1] / matrix[n - 1][n - 1]; -for ( i = ( n - 2 ); i >= 0; i-- ) -{ - temp = b[i]; - for ( j = ( i + 1 ); j < n; j++ ) - { - temp -= ( matrix[i][j] * x[j] ); - } - x[i] = temp / matrix[i][i]; -} -#endif - -int plane_intersect_planes( const vec4_t plane1, const vec4_t plane2, const vec4_t plane3, vec3_t intersection ){ - m3x3_t planes; - vec3_t b; - VectorCopy( plane1, planes + 0 ); - b[0] = plane1[3]; - VectorCopy( plane2, planes + 3 ); - b[1] = plane2[3]; - VectorCopy( plane3, planes + 6 ); - b[2] = plane3[3]; - - return matrix_solve_ge( planes, b, intersection ); -} diff --git a/tools/urt/libs/mathlib/mathlib.c b/tools/urt/libs/mathlib/mathlib.c deleted file mode 100644 index adc0848..0000000 --- a/tools/urt/libs/mathlib/mathlib.c +++ /dev/null @@ -1,553 +0,0 @@ -/* - Copyright (C) 1999-2007 id Software, Inc. and contributors. - For a list of contributors, see the accompanying CONTRIBUTORS file. - - This file is part of GtkRadiant. - - GtkRadiant is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - GtkRadiant is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with GtkRadiant; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - */ - -// mathlib.c -- math primitives -#include "mathlib.h" -// we use memcpy and memset -#include - -const vec3_t vec3_origin = {0.0f,0.0f,0.0f}; - -const vec3_t g_vec3_axis_x = { 1, 0, 0, }; -const vec3_t g_vec3_axis_y = { 0, 1, 0, }; -const vec3_t g_vec3_axis_z = { 0, 0, 1, }; - -/* - ================ - MakeNormalVectors - - Given a normalized forward vector, create two - other perpendicular vectors - ================ - */ -void MakeNormalVectors( vec3_t forward, vec3_t right, vec3_t up ){ - float d; - - // this rotate and negate guarantees a vector - // not colinear with the original - right[1] = -forward[0]; - right[2] = forward[1]; - right[0] = forward[2]; - - d = DotProduct( right, forward ); - VectorMA( right, -d, forward, right ); - VectorNormalize( right, right ); - CrossProduct( right, forward, up ); -} - -vec_t VectorLength( const vec3_t v ){ - int i; - float length; - - length = 0.0f; - for ( i = 0 ; i < 3 ; i++ ) - length += v[i] * v[i]; - length = (float)sqrt( length ); - - return length; -} - -qboolean VectorCompare( const vec3_t v1, const vec3_t v2 ){ - int i; - - for ( i = 0 ; i < 3 ; i++ ) - if ( fabs( v1[i] - v2[i] ) > EQUAL_EPSILON ) { - return qfalse; - } - - return qtrue; -} - -void VectorMA( const vec3_t va, vec_t scale, const vec3_t vb, vec3_t vc ){ - vc[0] = va[0] + scale * vb[0]; - vc[1] = va[1] + scale * vb[1]; - vc[2] = va[2] + scale * vb[2]; -} - -void _CrossProduct( vec3_t v1, vec3_t v2, vec3_t cross ){ - cross[0] = v1[1] * v2[2] - v1[2] * v2[1]; - cross[1] = v1[2] * v2[0] - v1[0] * v2[2]; - cross[2] = v1[0] * v2[1] - v1[1] * v2[0]; -} - -vec_t _DotProduct( vec3_t v1, vec3_t v2 ){ - return v1[0] * v2[0] + v1[1] * v2[1] + v1[2] * v2[2]; -} - -void _VectorSubtract( vec3_t va, vec3_t vb, vec3_t out ){ - out[0] = va[0] - vb[0]; - out[1] = va[1] - vb[1]; - out[2] = va[2] - vb[2]; -} - -void _VectorAdd( vec3_t va, vec3_t vb, vec3_t out ){ - out[0] = va[0] + vb[0]; - out[1] = va[1] + vb[1]; - out[2] = va[2] + vb[2]; -} - -void _VectorCopy( vec3_t in, vec3_t out ){ - out[0] = in[0]; - out[1] = in[1]; - out[2] = in[2]; -} - -vec_t VectorNormalize( const vec3_t in, vec3_t out ) { - vec_t length, ilength; - - length = (vec_t)sqrt( in[0] * in[0] + in[1] * in[1] + in[2] * in[2] ); - if ( length == 0 ) { - VectorClear( out ); - return 0; - } - - ilength = 1.0f / length; - out[0] = in[0] * ilength; - out[1] = in[1] * ilength; - out[2] = in[2] * ilength; - - return length; -} - -vec_t ColorNormalize( const vec3_t in, vec3_t out ) { - float max, scale; - - max = in[0]; - if ( in[1] > max ) { - max = in[1]; - } - if ( in[2] > max ) { - max = in[2]; - } - - if ( max == 0 ) { - out[0] = out[1] = out[2] = 1.0; - return 0; - } - - scale = 1.0f / max; - - VectorScale( in, scale, out ); - - return max; -} - -void VectorInverse( vec3_t v ){ - v[0] = -v[0]; - v[1] = -v[1]; - v[2] = -v[2]; -} - -/* - void VectorScale (vec3_t v, vec_t scale, vec3_t out) - { - out[0] = v[0] * scale; - out[1] = v[1] * scale; - out[2] = v[2] * scale; - } - */ - -void VectorRotate( vec3_t vIn, vec3_t vRotation, vec3_t out ){ - vec3_t vWork, va; - int nIndex[3][2]; - int i; - - VectorCopy( vIn, va ); - VectorCopy( va, vWork ); - nIndex[0][0] = 1; nIndex[0][1] = 2; - nIndex[1][0] = 2; nIndex[1][1] = 0; - nIndex[2][0] = 0; nIndex[2][1] = 1; - - for ( i = 0; i < 3; i++ ) - { - if ( vRotation[i] != 0 ) { - float dAngle = vRotation[i] * Q_PI / 180.0f; - float c = (vec_t)cos( dAngle ); - float s = (vec_t)sin( dAngle ); - vWork[nIndex[i][0]] = va[nIndex[i][0]] * c - va[nIndex[i][1]] * s; - vWork[nIndex[i][1]] = va[nIndex[i][0]] * s + va[nIndex[i][1]] * c; - } - VectorCopy( vWork, va ); - } - VectorCopy( vWork, out ); -} - -void VectorRotateOrigin( vec3_t vIn, vec3_t vRotation, vec3_t vOrigin, vec3_t out ){ - vec3_t vTemp, vTemp2; - - VectorSubtract( vIn, vOrigin, vTemp ); - VectorRotate( vTemp, vRotation, vTemp2 ); - VectorAdd( vTemp2, vOrigin, out ); -} - -void VectorPolar( vec3_t v, float radius, float theta, float phi ){ - v[0] = (float)( radius * cos( theta ) * cos( phi ) ); - v[1] = (float)( radius * sin( theta ) * cos( phi ) ); - v[2] = (float)( radius * sin( phi ) ); -} - -void VectorSnap( vec3_t v ){ - int i; - for ( i = 0; i < 3; i++ ) - { - v[i] = (vec_t)FLOAT_TO_INTEGER( v[i] ); - } -} - -void VectorISnap( vec3_t point, int snap ){ - int i; - for ( i = 0 ; i < 3 ; i++ ) - { - point[i] = (vec_t)FLOAT_SNAP( point[i], snap ); - } -} - -void VectorFSnap( vec3_t point, float snap ){ - int i; - for ( i = 0 ; i < 3 ; i++ ) - { - point[i] = (vec_t)FLOAT_SNAP( point[i], snap ); - } -} - -void _Vector5Add( vec5_t va, vec5_t vb, vec5_t out ){ - out[0] = va[0] + vb[0]; - out[1] = va[1] + vb[1]; - out[2] = va[2] + vb[2]; - out[3] = va[3] + vb[3]; - out[4] = va[4] + vb[4]; -} - -void _Vector5Scale( vec5_t v, vec_t scale, vec5_t out ){ - out[0] = v[0] * scale; - out[1] = v[1] * scale; - out[2] = v[2] * scale; - out[3] = v[3] * scale; - out[4] = v[4] * scale; -} - -void _Vector53Copy( vec5_t in, vec3_t out ){ - out[0] = in[0]; - out[1] = in[1]; - out[2] = in[2]; -} - -// NOTE: added these from Ritual's Q3Radiant -void ClearBounds( vec3_t mins, vec3_t maxs ){ - mins[0] = mins[1] = mins[2] = 99999; - maxs[0] = maxs[1] = maxs[2] = -99999; -} - -void AddPointToBounds( vec3_t v, vec3_t mins, vec3_t maxs ){ - int i; - vec_t val; - - for ( i = 0 ; i < 3 ; i++ ) - { - val = v[i]; - if ( val < mins[i] ) { - mins[i] = val; - } - if ( val > maxs[i] ) { - maxs[i] = val; - } - } -} - -void AngleVectors( vec3_t angles, vec3_t forward, vec3_t right, vec3_t up ){ - float angle; - static float sr, sp, sy, cr, cp, cy; - // static to help MS compiler fp bugs - - angle = angles[YAW] * ( Q_PI * 2.0f / 360.0f ); - sy = (vec_t)sin( angle ); - cy = (vec_t)cos( angle ); - angle = angles[PITCH] * ( Q_PI * 2.0f / 360.0f ); - sp = (vec_t)sin( angle ); - cp = (vec_t)cos( angle ); - angle = angles[ROLL] * ( Q_PI * 2.0f / 360.0f ); - sr = (vec_t)sin( angle ); - cr = (vec_t)cos( angle ); - - if ( forward ) { - forward[0] = cp * cy; - forward[1] = cp * sy; - forward[2] = -sp; - } - if ( right ) { - right[0] = -sr * sp * cy + cr * sy; - right[1] = -sr * sp * sy - cr * cy; - right[2] = -sr * cp; - } - if ( up ) { - up[0] = cr * sp * cy + sr * sy; - up[1] = cr * sp * sy - sr * cy; - up[2] = cr * cp; - } -} - -void VectorToAngles( vec3_t vec, vec3_t angles ){ - float forward; - float yaw, pitch; - - if ( ( vec[ 0 ] == 0 ) && ( vec[ 1 ] == 0 ) ) { - yaw = 0; - if ( vec[ 2 ] > 0 ) { - pitch = 90; - } - else - { - pitch = 270; - } - } - else - { - yaw = (vec_t)atan2( vec[ 1 ], vec[ 0 ] ) * 180 / Q_PI; - if ( yaw < 0 ) { - yaw += 360; - } - - forward = ( float )sqrt( vec[ 0 ] * vec[ 0 ] + vec[ 1 ] * vec[ 1 ] ); - pitch = (vec_t)atan2( vec[ 2 ], forward ) * 180 / Q_PI; - if ( pitch < 0 ) { - pitch += 360; - } - } - - angles[ 0 ] = pitch; - angles[ 1 ] = yaw; - angles[ 2 ] = 0; -} - -/* - ===================== - PlaneFromPoints - - Returns false if the triangle is degenrate. - The normal will point out of the clock for clockwise ordered points - ===================== - */ -qboolean PlaneFromPoints( vec4_t plane, const vec3_t a, const vec3_t b, const vec3_t c ) { - vec3_t d1, d2; - - VectorSubtract( b, a, d1 ); - VectorSubtract( c, a, d2 ); - CrossProduct( d2, d1, plane ); - if ( VectorNormalize( plane, plane ) == 0 ) { - return qfalse; - } - - plane[3] = DotProduct( a, plane ); - return qtrue; -} - -/* -** NormalToLatLong -** -** We use two byte encoded normals in some space critical applications. -** Lat = 0 at (1,0,0) to 360 (-1,0,0), encoded in 8-bit sine table format -** Lng = 0 at (0,0,1) to 180 (0,0,-1), encoded in 8-bit sine table format -** -*/ -void NormalToLatLong( const vec3_t normal, byte bytes[2] ) { - // check for singularities - if ( normal[0] == 0 && normal[1] == 0 ) { - if ( normal[2] > 0 ) { - bytes[0] = 0; - bytes[1] = 0; // lat = 0, long = 0 - } - else { - bytes[0] = 128; - bytes[1] = 0; // lat = 0, long = 128 - } - } - else { - int a, b; - - a = (int)( RAD2DEG( atan2( normal[1], normal[0] ) ) * ( 255.0f / 360.0f ) ); - a &= 0xff; - - b = (int)( RAD2DEG( acos( normal[2] ) ) * ( 255.0f / 360.0f ) ); - b &= 0xff; - - bytes[0] = b; // longitude - bytes[1] = a; // lattitude - } -} - -/* - ================= - PlaneTypeForNormal - ================= - */ -int PlaneTypeForNormal( vec3_t normal ) { - if ( normal[0] == 1.0 || normal[0] == -1.0 ) { - return PLANE_X; - } - if ( normal[1] == 1.0 || normal[1] == -1.0 ) { - return PLANE_Y; - } - if ( normal[2] == 1.0 || normal[2] == -1.0 ) { - return PLANE_Z; - } - - return PLANE_NON_AXIAL; -} - -/* - ================ - MatrixMultiply - ================ - */ -void MatrixMultiply( float in1[3][3], float in2[3][3], float out[3][3] ) { - out[0][0] = in1[0][0] * in2[0][0] + in1[0][1] * in2[1][0] + - in1[0][2] * in2[2][0]; - out[0][1] = in1[0][0] * in2[0][1] + in1[0][1] * in2[1][1] + - in1[0][2] * in2[2][1]; - out[0][2] = in1[0][0] * in2[0][2] + in1[0][1] * in2[1][2] + - in1[0][2] * in2[2][2]; - out[1][0] = in1[1][0] * in2[0][0] + in1[1][1] * in2[1][0] + - in1[1][2] * in2[2][0]; - out[1][1] = in1[1][0] * in2[0][1] + in1[1][1] * in2[1][1] + - in1[1][2] * in2[2][1]; - out[1][2] = in1[1][0] * in2[0][2] + in1[1][1] * in2[1][2] + - in1[1][2] * in2[2][2]; - out[2][0] = in1[2][0] * in2[0][0] + in1[2][1] * in2[1][0] + - in1[2][2] * in2[2][0]; - out[2][1] = in1[2][0] * in2[0][1] + in1[2][1] * in2[1][1] + - in1[2][2] * in2[2][1]; - out[2][2] = in1[2][0] * in2[0][2] + in1[2][1] * in2[1][2] + - in1[2][2] * in2[2][2]; -} - -void ProjectPointOnPlane( vec3_t dst, const vec3_t p, const vec3_t normal ){ - float d; - vec3_t n; - float inv_denom; - - inv_denom = 1.0F / DotProduct( normal, normal ); - - d = DotProduct( normal, p ) * inv_denom; - - n[0] = normal[0] * inv_denom; - n[1] = normal[1] * inv_denom; - n[2] = normal[2] * inv_denom; - - dst[0] = p[0] - d * n[0]; - dst[1] = p[1] - d * n[1]; - dst[2] = p[2] - d * n[2]; -} - -/* -** assumes "src" is normalized -*/ -void PerpendicularVector( vec3_t dst, const vec3_t src ){ - int pos; - int i; - vec_t minelem = 1.0F; - vec3_t tempvec; - - /* - ** find the smallest magnitude axially aligned vector - */ - for ( pos = 0, i = 0; i < 3; i++ ) - { - if ( fabs( src[i] ) < minelem ) { - pos = i; - minelem = (vec_t)fabs( src[i] ); - } - } - tempvec[0] = tempvec[1] = tempvec[2] = 0.0F; - tempvec[pos] = 1.0F; - - /* - ** project the point onto the plane defined by src - */ - ProjectPointOnPlane( dst, tempvec, src ); - - /* - ** normalize the result - */ - VectorNormalize( dst, dst ); -} - -/* - =============== - RotatePointAroundVector - - This is not implemented very well... - =============== - */ -void RotatePointAroundVector( vec3_t dst, const vec3_t dir, const vec3_t point, - float degrees ) { - float m[3][3]; - float im[3][3]; - float zrot[3][3]; - float tmpmat[3][3]; - float rot[3][3]; - int i; - vec3_t vr, vup, vf; - float rad; - - vf[0] = dir[0]; - vf[1] = dir[1]; - vf[2] = dir[2]; - - PerpendicularVector( vr, dir ); - CrossProduct( vr, vf, vup ); - - m[0][0] = vr[0]; - m[1][0] = vr[1]; - m[2][0] = vr[2]; - - m[0][1] = vup[0]; - m[1][1] = vup[1]; - m[2][1] = vup[2]; - - m[0][2] = vf[0]; - m[1][2] = vf[1]; - m[2][2] = vf[2]; - - memcpy( im, m, sizeof( im ) ); - - im[0][1] = m[1][0]; - im[0][2] = m[2][0]; - im[1][0] = m[0][1]; - im[1][2] = m[2][1]; - im[2][0] = m[0][2]; - im[2][1] = m[1][2]; - - memset( zrot, 0, sizeof( zrot ) ); - zrot[0][0] = zrot[1][1] = zrot[2][2] = 1.0F; - - rad = (float)DEG2RAD( degrees ); - zrot[0][0] = (vec_t)cos( rad ); - zrot[0][1] = (vec_t)sin( rad ); - zrot[1][0] = (vec_t)-sin( rad ); - zrot[1][1] = (vec_t)cos( rad ); - - MatrixMultiply( m, zrot, tmpmat ); - MatrixMultiply( tmpmat, im, rot ); - - for ( i = 0; i < 3; i++ ) { - dst[i] = rot[i][0] * point[0] + rot[i][1] * point[1] + rot[i][2] * point[2]; - } -} diff --git a/tools/urt/libs/mathlib/mathlib.dsp b/tools/urt/libs/mathlib/mathlib.dsp deleted file mode 100644 index 358da21..0000000 --- a/tools/urt/libs/mathlib/mathlib.dsp +++ /dev/null @@ -1,126 +0,0 @@ -# Microsoft Developer Studio Project File - Name="mathlib" - Package Owner=<4> -# Microsoft Developer Studio Generated Build File, Format Version 6.00 -# ** DO NOT EDIT ** - -# TARGTYPE "Win32 (x86) Static Library" 0x0104 - -CFG=mathlib - Win32 Debug -!MESSAGE This is not a valid makefile. To build this project using NMAKE, -!MESSAGE use the Export Makefile command and run -!MESSAGE -!MESSAGE NMAKE /f "mathlib.mak". -!MESSAGE -!MESSAGE You can specify a configuration when running NMAKE -!MESSAGE by defining the macro CFG on the command line. For example: -!MESSAGE -!MESSAGE NMAKE /f "mathlib.mak" CFG="mathlib - Win32 Debug" -!MESSAGE -!MESSAGE Possible choices for configuration are: -!MESSAGE -!MESSAGE "mathlib - Win32 Release" (based on "Win32 (x86) Static Library") -!MESSAGE "mathlib - Win32 Debug" (based on "Win32 (x86) Static Library") -!MESSAGE - -# Begin Project -# PROP AllowPerConfigDependencies 0 -# PROP Scc_ProjName "mathlib" -# PROP Scc_LocalPath ".." -CPP=cl.exe -RSC=rc.exe - -!IF "$(CFG)" == "mathlib - Win32 Release" - -# PROP BASE Use_MFC 0 -# PROP BASE Use_Debug_Libraries 0 -# PROP BASE Output_Dir "Release" -# PROP BASE Intermediate_Dir "Release" -# PROP BASE Target_Dir "" -# PROP Use_MFC 0 -# PROP Use_Debug_Libraries 0 -# PROP Output_Dir "Release" -# PROP Intermediate_Dir "Release" -# PROP Target_Dir "" -MTL=midl.exe -F90=df.exe -# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_MBCS" /D "_LIB" /YX /FD /c -# ADD CPP /nologo /MD /W3 /O2 /I ".." /D "WIN32" /D "NDEBUG" /D "_MBCS" /D "_LIB" /FD /c -# SUBTRACT CPP /YX -# ADD BASE RSC /l 0x40c /d "NDEBUG" -# ADD RSC /l 0x40c /d "NDEBUG" -BSC32=bscmake.exe -# ADD BASE BSC32 /nologo -# ADD BSC32 /nologo -LIB32=link.exe -lib -# ADD BASE LIB32 /nologo -# ADD LIB32 /nologo - -!ELSEIF "$(CFG)" == "mathlib - Win32 Debug" - -# PROP BASE Use_MFC 0 -# PROP BASE Use_Debug_Libraries 1 -# PROP BASE Output_Dir "Debug" -# PROP BASE Intermediate_Dir "Debug" -# PROP BASE Target_Dir "" -# PROP Use_MFC 0 -# PROP Use_Debug_Libraries 1 -# PROP Output_Dir "Debug" -# PROP Intermediate_Dir "Debug" -# PROP Target_Dir "" -MTL=midl.exe -F90=df.exe -# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_MBCS" /D "_LIB" /YX /FD /GZ /c -# ADD CPP /nologo /MDd /W3 /Gm /ZI /Od /I ".." /D "WIN32" /D "_DEBUG" /D "_MBCS" /D "_LIB" /FR /FD /GZ /c -# SUBTRACT CPP /YX -# ADD BASE RSC /l 0x40c /d "_DEBUG" -# ADD RSC /l 0x40c /d "_DEBUG" -BSC32=bscmake.exe -# ADD BASE BSC32 /nologo -# ADD BSC32 /nologo -LIB32=link.exe -lib -# ADD BASE LIB32 /nologo -# ADD LIB32 /nologo - -!ENDIF - -# Begin Target - -# Name "mathlib - Win32 Release" -# Name "mathlib - Win32 Debug" -# Begin Group "Source Files" - -# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat" -# Begin Source File - -SOURCE=.\bbox.c -# End Source File -# Begin Source File - -SOURCE=.\line.c -# End Source File -# Begin Source File - -SOURCE=.\linear.c -# End Source File -# Begin Source File - -SOURCE=.\m4x4.c -# End Source File -# Begin Source File - -SOURCE=.\mathlib.c -# End Source File -# Begin Source File - -SOURCE=.\ray.c -# End Source File -# End Group -# Begin Group "Header Files" - -# PROP Default_Filter "h;hpp;hxx;hm;inl" -# Begin Source File - -SOURCE=..\mathlib.h -# End Source File -# End Group -# End Target -# End Project diff --git a/tools/urt/libs/mathlib/mathlib.vcproj b/tools/urt/libs/mathlib/mathlib.vcproj deleted file mode 100644 index b371ccf..0000000 --- a/tools/urt/libs/mathlib/mathlib.vcproj +++ /dev/null @@ -1,298 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/tools/urt/libs/mathlib/ray.c b/tools/urt/libs/mathlib/ray.c deleted file mode 100644 index c0fbf72..0000000 --- a/tools/urt/libs/mathlib/ray.c +++ /dev/null @@ -1,143 +0,0 @@ -/* - Copyright (C) 1999-2007 id Software, Inc. and contributors. - For a list of contributors, see the accompanying CONTRIBUTORS file. - - This file is part of GtkRadiant. - - GtkRadiant is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - GtkRadiant is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with GtkRadiant; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - */ - -#include "mathlib.h" -#include - -vec3_t identity = { 0,0,0 }; - -void ray_construct_for_vec3( ray_t *ray, const vec3_t origin, const vec3_t direction ){ - VectorCopy( origin, ray->origin ); - VectorCopy( direction, ray->direction ); -} - -void ray_transform( ray_t *ray, const m4x4_t matrix ){ - m4x4_transform_point( matrix, ray->origin ); - m4x4_transform_normal( matrix, ray->direction ); -} - -vec_t ray_intersect_point( const ray_t *ray, const vec3_t point, vec_t epsilon, vec_t divergence ){ - vec3_t displacement; - vec_t depth; - - // calc displacement of test point from ray origin - VectorSubtract( point, ray->origin, displacement ); - // calc length of displacement vector along ray direction - depth = DotProduct( displacement, ray->direction ); - if ( depth < 0.0f ) { - return (vec_t)FLT_MAX; - } - // calc position of closest point on ray to test point - VectorMA( ray->origin, depth, ray->direction, displacement ); - // calc displacement of test point from closest point - VectorSubtract( point, displacement, displacement ); - // calc length of displacement, subtract depth-dependant epsilon - if ( VectorLength( displacement ) - ( epsilon + ( depth * divergence ) ) > 0.0f ) { - return (vec_t)FLT_MAX; - } - return depth; -} - -// Tomas Moller and Ben Trumbore. Fast, minimum storage ray-triangle intersection. Journal of graphics tools, 2(1):21-28, 1997 - -#define EPSILON 0.000001 - -vec_t ray_intersect_triangle( const ray_t *ray, qboolean bCullBack, const vec3_t vert0, const vec3_t vert1, const vec3_t vert2 ){ - float edge1[3], edge2[3], tvec[3], pvec[3], qvec[3]; - float det,inv_det; - float u, v; - vec_t depth = (vec_t)FLT_MAX; - - /* find vectors for two edges sharing vert0 */ - VectorSubtract( vert1, vert0, edge1 ); - VectorSubtract( vert2, vert0, edge2 ); - - /* begin calculating determinant - also used to calculate U parameter */ - CrossProduct( ray->direction, edge2, pvec ); - - /* if determinant is near zero, ray lies in plane of triangle */ - det = DotProduct( edge1, pvec ); - - if ( bCullBack == qtrue ) { - if ( det < EPSILON ) { - return depth; - } - - // calculate distance from vert0 to ray origin - VectorSubtract( ray->origin, vert0, tvec ); - - // calculate U parameter and test bounds - u = DotProduct( tvec, pvec ); - if ( u < 0.0 || u > det ) { - return depth; - } - - // prepare to test V parameter - CrossProduct( tvec, edge1, qvec ); - - // calculate V parameter and test bounds - v = DotProduct( ray->direction, qvec ); - if ( v < 0.0 || u + v > det ) { - return depth; - } - - // calculate t, scale parameters, ray intersects triangle - depth = DotProduct( edge2, qvec ); - inv_det = 1.0f / det; - depth *= inv_det; - //u *= inv_det; - //v *= inv_det; - } - else - { - /* the non-culling branch */ - if ( det > -EPSILON && det < EPSILON ) { - return depth; - } - inv_det = 1.0f / det; - - /* calculate distance from vert0 to ray origin */ - VectorSubtract( ray->origin, vert0, tvec ); - - /* calculate U parameter and test bounds */ - u = DotProduct( tvec, pvec ) * inv_det; - if ( u < 0.0 || u > 1.0 ) { - return depth; - } - - /* prepare to test V parameter */ - CrossProduct( tvec, edge1, qvec ); - - /* calculate V parameter and test bounds */ - v = DotProduct( ray->direction, qvec ) * inv_det; - if ( v < 0.0 || u + v > 1.0 ) { - return depth; - } - - /* calculate t, ray intersects triangle */ - depth = DotProduct( edge2, qvec ) * inv_det; - } - return depth; -} - -vec_t ray_intersect_plane( const ray_t* ray, const vec3_t normal, vec_t dist ){ - return -( DotProduct( normal, ray->origin ) - dist ) / DotProduct( ray->direction, normal ); -} diff --git a/tools/urt/libs/md5lib.h b/tools/urt/libs/md5lib.h deleted file mode 100644 index db9fd33..0000000 --- a/tools/urt/libs/md5lib.h +++ /dev/null @@ -1,91 +0,0 @@ -/* - Copyright (C) 1999, 2002 Aladdin Enterprises. All rights reserved. - - This software is provided 'as-is', without any express or implied - warranty. In no event will the authors be held liable for any damages - arising from the use of this software. - - Permission is granted to anyone to use this software for any purpose, - including commercial applications, and to alter it and redistribute it - freely, subject to the following restrictions: - - 1. The origin of this software must not be misrepresented; you must not - claim that you wrote the original software. If you use this software - in a product, an acknowledgment in the product documentation would be - appreciated but is not required. - 2. Altered source versions must be plainly marked as such, and must not be - misrepresented as being the original software. - 3. This notice may not be removed or altered from any source distribution. - - L. Peter Deutsch - ghost@aladdin.com - - */ -/* $Id: md5lib.h,v 1.1.2.1 2003/07/19 23:25:50 spog Exp $ */ -/* - Independent implementation of MD5 (RFC 1321). - - This code implements the MD5 Algorithm defined in RFC 1321, whose - text is available at - http://www.ietf.org/rfc/rfc1321.txt - The code is derived from the text of the RFC, including the test suite - (section A.5) but excluding the rest of Appendix A. It does not include - any code or documentation that is identified in the RFC as being - copyrighted. - - The original and principal author of md5.h is L. Peter Deutsch - . Other authors are noted in the change history - that follows (in reverse chronological order): - - 2002-04-13 lpd Removed support for non-ANSI compilers; removed - references to Ghostscript; clarified derivation from RFC 1321; - now handles byte order either statically or dynamically. - 1999-11-04 lpd Edited comments slightly for automatic TOC extraction. - 1999-10-18 lpd Fixed typo in header comment (ansi2knr rather than md5); - added conditionalization for C++ compilation from Martin - Purschke . - 1999-05-03 lpd Original version. - */ - -#ifndef md5_INCLUDED -# define md5_INCLUDED - -/* - * This package supports both compile-time and run-time determination of CPU - * byte order. If ARCH_IS_BIG_ENDIAN is defined as 0, the code will be - * compiled to run only on little-endian CPUs; if ARCH_IS_BIG_ENDIAN is - * defined as non-zero, the code will be compiled to run only on big-endian - * CPUs; if ARCH_IS_BIG_ENDIAN is not defined, the code will be compiled to - * run on either big- or little-endian CPUs, but will run slightly less - * efficiently on either one than if ARCH_IS_BIG_ENDIAN is defined. - */ - -typedef unsigned char md5_byte_t; /* 8-bit byte */ -typedef unsigned int md5_word_t; /* 32-bit word */ - -/* Define the state of the MD5 Algorithm. */ -typedef struct md5_state_s { - md5_word_t count[2]; /* message length in bits, lsw first */ - md5_word_t abcd[4]; /* digest buffer */ - md5_byte_t buf[64]; /* accumulate block */ -} md5_state_t; - -#ifdef __cplusplus -extern "C" -{ -#endif - -/* Initialize the algorithm. */ -void md5_init( md5_state_t *pms ); - -/* Append a string to the message. */ -void md5_append( md5_state_t *pms, const md5_byte_t *data, int nbytes ); - -/* Finish the message and return the digest. */ -void md5_finish( md5_state_t * pms, md5_byte_t digest[16] ); - -#ifdef __cplusplus -} /* end extern "C" */ -#endif - -#endif /* md5_INCLUDED */ diff --git a/tools/urt/libs/md5lib/md5lib.c b/tools/urt/libs/md5lib/md5lib.c deleted file mode 100644 index f30d095..0000000 --- a/tools/urt/libs/md5lib/md5lib.c +++ /dev/null @@ -1,396 +0,0 @@ -/* - Copyright (C) 1999, 2000, 2002 Aladdin Enterprises. All rights reserved. - - This software is provided 'as-is', without any express or implied - warranty. In no event will the authors be held liable for any damages - arising from the use of this software. - - Permission is granted to anyone to use this software for any purpose, - including commercial applications, and to alter it and redistribute it - freely, subject to the following restrictions: - - 1. The origin of this software must not be misrepresented; you must not - claim that you wrote the original software. If you use this software - in a product, an acknowledgment in the product documentation would be - appreciated but is not required. - 2. Altered source versions must be plainly marked as such, and must not be - misrepresented as being the original software. - 3. This notice may not be removed or altered from any source distribution. - - L. Peter Deutsch - ghost@aladdin.com - - */ -/* $Id: md5lib.c,v 1.1 2003/07/18 04:24:39 ydnar Exp $ */ -/* - Independent implementation of MD5 (RFC 1321). - - This code implements the MD5 Algorithm defined in RFC 1321, whose - text is available at - http://www.ietf.org/rfc/rfc1321.txt - The code is derived from the text of the RFC, including the test suite - (section A.5) but excluding the rest of Appendix A. It does not include - any code or documentation that is identified in the RFC as being - copyrighted. - - The original and principal author of md5.c is L. Peter Deutsch - . Other authors are noted in the change history - that follows (in reverse chronological order): - - 2003-07-17 ydnar added to gtkradiant project from - http://sourceforge.net/projects/libmd5-rfc/ - 2002-04-13 lpd Clarified derivation from RFC 1321; now handles byte order - either statically or dynamically; added missing #include - in library. - 2002-03-11 lpd Corrected argument list for main(), and added int return - type, in test program and T value program. - 2002-02-21 lpd Added missing #include in test program. - 2000-07-03 lpd Patched to eliminate warnings about "constant is - unsigned in ANSI C, signed in traditional"; made test program - self-checking. - 1999-11-04 lpd Edited comments slightly for automatic TOC extraction. - 1999-10-18 lpd Fixed typo in header comment (ansi2knr rather than md5). - 1999-05-03 lpd Original version. - */ - -#include "md5lib.h" /* ydnar */ -#include - -/* ydnar: gtkradiant endian picking */ -#ifdef _SGI_SOURCE -#define __BIG_ENDIAN__ -#endif - -#ifdef __BIG_ENDIAN__ -#define ARCH_IS_BIG_ENDIAN 1 -#else -#define ARCH_IS_BIG_ENDIAN 0 -#endif -/* ydnar: end */ - -#undef BYTE_ORDER /* 1 = big-endian, -1 = little-endian, 0 = unknown */ -#ifdef ARCH_IS_BIG_ENDIAN -# define BYTE_ORDER ( ARCH_IS_BIG_ENDIAN ? 1 : -1 ) -#else -# define BYTE_ORDER 0 -#endif - -#define T_MASK ( ( md5_word_t ) ~0 ) -#define T1 /* 0xd76aa478 */ ( T_MASK ^ 0x28955b87 ) -#define T2 /* 0xe8c7b756 */ ( T_MASK ^ 0x173848a9 ) -#define T3 0x242070db -#define T4 /* 0xc1bdceee */ ( T_MASK ^ 0x3e423111 ) -#define T5 /* 0xf57c0faf */ ( T_MASK ^ 0x0a83f050 ) -#define T6 0x4787c62a -#define T7 /* 0xa8304613 */ ( T_MASK ^ 0x57cfb9ec ) -#define T8 /* 0xfd469501 */ ( T_MASK ^ 0x02b96afe ) -#define T9 0x698098d8 -#define T10 /* 0x8b44f7af */ ( T_MASK ^ 0x74bb0850 ) -#define T11 /* 0xffff5bb1 */ ( T_MASK ^ 0x0000a44e ) -#define T12 /* 0x895cd7be */ ( T_MASK ^ 0x76a32841 ) -#define T13 0x6b901122 -#define T14 /* 0xfd987193 */ ( T_MASK ^ 0x02678e6c ) -#define T15 /* 0xa679438e */ ( T_MASK ^ 0x5986bc71 ) -#define T16 0x49b40821 -#define T17 /* 0xf61e2562 */ ( T_MASK ^ 0x09e1da9d ) -#define T18 /* 0xc040b340 */ ( T_MASK ^ 0x3fbf4cbf ) -#define T19 0x265e5a51 -#define T20 /* 0xe9b6c7aa */ ( T_MASK ^ 0x16493855 ) -#define T21 /* 0xd62f105d */ ( T_MASK ^ 0x29d0efa2 ) -#define T22 0x02441453 -#define T23 /* 0xd8a1e681 */ ( T_MASK ^ 0x275e197e ) -#define T24 /* 0xe7d3fbc8 */ ( T_MASK ^ 0x182c0437 ) -#define T25 0x21e1cde6 -#define T26 /* 0xc33707d6 */ ( T_MASK ^ 0x3cc8f829 ) -#define T27 /* 0xf4d50d87 */ ( T_MASK ^ 0x0b2af278 ) -#define T28 0x455a14ed -#define T29 /* 0xa9e3e905 */ ( T_MASK ^ 0x561c16fa ) -#define T30 /* 0xfcefa3f8 */ ( T_MASK ^ 0x03105c07 ) -#define T31 0x676f02d9 -#define T32 /* 0x8d2a4c8a */ ( T_MASK ^ 0x72d5b375 ) -#define T33 /* 0xfffa3942 */ ( T_MASK ^ 0x0005c6bd ) -#define T34 /* 0x8771f681 */ ( T_MASK ^ 0x788e097e ) -#define T35 0x6d9d6122 -#define T36 /* 0xfde5380c */ ( T_MASK ^ 0x021ac7f3 ) -#define T37 /* 0xa4beea44 */ ( T_MASK ^ 0x5b4115bb ) -#define T38 0x4bdecfa9 -#define T39 /* 0xf6bb4b60 */ ( T_MASK ^ 0x0944b49f ) -#define T40 /* 0xbebfbc70 */ ( T_MASK ^ 0x4140438f ) -#define T41 0x289b7ec6 -#define T42 /* 0xeaa127fa */ ( T_MASK ^ 0x155ed805 ) -#define T43 /* 0xd4ef3085 */ ( T_MASK ^ 0x2b10cf7a ) -#define T44 0x04881d05 -#define T45 /* 0xd9d4d039 */ ( T_MASK ^ 0x262b2fc6 ) -#define T46 /* 0xe6db99e5 */ ( T_MASK ^ 0x1924661a ) -#define T47 0x1fa27cf8 -#define T48 /* 0xc4ac5665 */ ( T_MASK ^ 0x3b53a99a ) -#define T49 /* 0xf4292244 */ ( T_MASK ^ 0x0bd6ddbb ) -#define T50 0x432aff97 -#define T51 /* 0xab9423a7 */ ( T_MASK ^ 0x546bdc58 ) -#define T52 /* 0xfc93a039 */ ( T_MASK ^ 0x036c5fc6 ) -#define T53 0x655b59c3 -#define T54 /* 0x8f0ccc92 */ ( T_MASK ^ 0x70f3336d ) -#define T55 /* 0xffeff47d */ ( T_MASK ^ 0x00100b82 ) -#define T56 /* 0x85845dd1 */ ( T_MASK ^ 0x7a7ba22e ) -#define T57 0x6fa87e4f -#define T58 /* 0xfe2ce6e0 */ ( T_MASK ^ 0x01d3191f ) -#define T59 /* 0xa3014314 */ ( T_MASK ^ 0x5cfebceb ) -#define T60 0x4e0811a1 -#define T61 /* 0xf7537e82 */ ( T_MASK ^ 0x08ac817d ) -#define T62 /* 0xbd3af235 */ ( T_MASK ^ 0x42c50dca ) -#define T63 0x2ad7d2bb -#define T64 /* 0xeb86d391 */ ( T_MASK ^ 0x14792c6e ) - - -static void -md5_process( md5_state_t *pms, const md5_byte_t *data /*[64]*/ ){ - md5_word_t - a = pms->abcd[0], b = pms->abcd[1], - c = pms->abcd[2], d = pms->abcd[3]; - md5_word_t t; -#if BYTE_ORDER > 0 - /* Define storage only for big-endian CPUs. */ - md5_word_t X[16]; -#else - /* Define storage for little-endian or both types of CPUs. */ - md5_word_t xbuf[16]; - const md5_word_t *X; -#endif - - { -#if BYTE_ORDER == 0 - /* - * Determine dynamically whether this is a big-endian or - * little-endian machine, since we can use a more efficient - * algorithm on the latter. - */ - static const int w = 1; - - if ( *( (const md5_byte_t *)&w ) ) /* dynamic little-endian */ -#endif -#if BYTE_ORDER <= 0 /* little-endian */ - { - /* - * On little-endian machines, we can process properly aligned - * data without copying it. - */ - if ( !( ( data - (const md5_byte_t *)0 ) & 3 ) ) { - /* data are properly aligned */ - X = (const md5_word_t *)data; - } - else { - /* not aligned */ - memcpy( xbuf, data, 64 ); - X = xbuf; - } - } -#endif -#if BYTE_ORDER == 0 - else /* dynamic big-endian */ -#endif -#if BYTE_ORDER >= 0 /* big-endian */ - { - /* - * On big-endian machines, we must arrange the bytes in the - * right order. - */ - const md5_byte_t *xp = data; - int i; - -# if BYTE_ORDER == 0 - X = xbuf; /* (dynamic only) */ -# else -# define xbuf X /* (static only) */ -# endif - for ( i = 0; i < 16; ++i, xp += 4 ) - xbuf[i] = xp[0] + ( xp[1] << 8 ) + ( xp[2] << 16 ) + ( xp[3] << 24 ); - } -#endif - } - -#define ROTATE_LEFT( x, n ) ( ( ( x ) << ( n ) ) | ( ( x ) >> ( 32 - ( n ) ) ) ) - - /* Round 1. */ - /* Let [abcd k s i] denote the operation - a = b + ((a + F(b,c,d) + X[k] + T[i]) <<< s). */ -#define F( x, y, z ) ( ( ( x ) & ( y ) ) | ( ~( x ) & ( z ) ) ) -#define SET( a, b, c, d, k, s, Ti ) \ - t = a + F( b,c,d ) + X[k] + Ti; \ - a = ROTATE_LEFT( t, s ) + b - /* Do the following 16 operations. */ - SET( a, b, c, d, 0, 7, T1 ); - SET( d, a, b, c, 1, 12, T2 ); - SET( c, d, a, b, 2, 17, T3 ); - SET( b, c, d, a, 3, 22, T4 ); - SET( a, b, c, d, 4, 7, T5 ); - SET( d, a, b, c, 5, 12, T6 ); - SET( c, d, a, b, 6, 17, T7 ); - SET( b, c, d, a, 7, 22, T8 ); - SET( a, b, c, d, 8, 7, T9 ); - SET( d, a, b, c, 9, 12, T10 ); - SET( c, d, a, b, 10, 17, T11 ); - SET( b, c, d, a, 11, 22, T12 ); - SET( a, b, c, d, 12, 7, T13 ); - SET( d, a, b, c, 13, 12, T14 ); - SET( c, d, a, b, 14, 17, T15 ); - SET( b, c, d, a, 15, 22, T16 ); -#undef SET - - /* Round 2. */ - /* Let [abcd k s i] denote the operation - a = b + ((a + G(b,c,d) + X[k] + T[i]) <<< s). */ -#define G( x, y, z ) ( ( ( x ) & ( z ) ) | ( ( y ) & ~( z ) ) ) -#define SET( a, b, c, d, k, s, Ti ) \ - t = a + G( b,c,d ) + X[k] + Ti; \ - a = ROTATE_LEFT( t, s ) + b - /* Do the following 16 operations. */ - SET( a, b, c, d, 1, 5, T17 ); - SET( d, a, b, c, 6, 9, T18 ); - SET( c, d, a, b, 11, 14, T19 ); - SET( b, c, d, a, 0, 20, T20 ); - SET( a, b, c, d, 5, 5, T21 ); - SET( d, a, b, c, 10, 9, T22 ); - SET( c, d, a, b, 15, 14, T23 ); - SET( b, c, d, a, 4, 20, T24 ); - SET( a, b, c, d, 9, 5, T25 ); - SET( d, a, b, c, 14, 9, T26 ); - SET( c, d, a, b, 3, 14, T27 ); - SET( b, c, d, a, 8, 20, T28 ); - SET( a, b, c, d, 13, 5, T29 ); - SET( d, a, b, c, 2, 9, T30 ); - SET( c, d, a, b, 7, 14, T31 ); - SET( b, c, d, a, 12, 20, T32 ); -#undef SET - - /* Round 3. */ - /* Let [abcd k s t] denote the operation - a = b + ((a + H(b,c,d) + X[k] + T[i]) <<< s). */ -#define H( x, y, z ) ( ( x ) ^ ( y ) ^ ( z ) ) -#define SET( a, b, c, d, k, s, Ti ) \ - t = a + H( b,c,d ) + X[k] + Ti; \ - a = ROTATE_LEFT( t, s ) + b - /* Do the following 16 operations. */ - SET( a, b, c, d, 5, 4, T33 ); - SET( d, a, b, c, 8, 11, T34 ); - SET( c, d, a, b, 11, 16, T35 ); - SET( b, c, d, a, 14, 23, T36 ); - SET( a, b, c, d, 1, 4, T37 ); - SET( d, a, b, c, 4, 11, T38 ); - SET( c, d, a, b, 7, 16, T39 ); - SET( b, c, d, a, 10, 23, T40 ); - SET( a, b, c, d, 13, 4, T41 ); - SET( d, a, b, c, 0, 11, T42 ); - SET( c, d, a, b, 3, 16, T43 ); - SET( b, c, d, a, 6, 23, T44 ); - SET( a, b, c, d, 9, 4, T45 ); - SET( d, a, b, c, 12, 11, T46 ); - SET( c, d, a, b, 15, 16, T47 ); - SET( b, c, d, a, 2, 23, T48 ); -#undef SET - - /* Round 4. */ - /* Let [abcd k s t] denote the operation - a = b + ((a + I(b,c,d) + X[k] + T[i]) <<< s). */ -#define I( x, y, z ) ( ( y ) ^ ( ( x ) | ~( z ) ) ) -#define SET( a, b, c, d, k, s, Ti ) \ - t = a + I( b,c,d ) + X[k] + Ti; \ - a = ROTATE_LEFT( t, s ) + b - /* Do the following 16 operations. */ - SET( a, b, c, d, 0, 6, T49 ); - SET( d, a, b, c, 7, 10, T50 ); - SET( c, d, a, b, 14, 15, T51 ); - SET( b, c, d, a, 5, 21, T52 ); - SET( a, b, c, d, 12, 6, T53 ); - SET( d, a, b, c, 3, 10, T54 ); - SET( c, d, a, b, 10, 15, T55 ); - SET( b, c, d, a, 1, 21, T56 ); - SET( a, b, c, d, 8, 6, T57 ); - SET( d, a, b, c, 15, 10, T58 ); - SET( c, d, a, b, 6, 15, T59 ); - SET( b, c, d, a, 13, 21, T60 ); - SET( a, b, c, d, 4, 6, T61 ); - SET( d, a, b, c, 11, 10, T62 ); - SET( c, d, a, b, 2, 15, T63 ); - SET( b, c, d, a, 9, 21, T64 ); -#undef SET - - /* Then perform the following additions. (That is increment each - of the four registers by the value it had before this block - was started.) */ - pms->abcd[0] += a; - pms->abcd[1] += b; - pms->abcd[2] += c; - pms->abcd[3] += d; -} - -void -md5_init( md5_state_t *pms ){ - pms->count[0] = pms->count[1] = 0; - pms->abcd[0] = 0x67452301; - pms->abcd[1] = /*0xefcdab89*/ T_MASK ^ 0x10325476; - pms->abcd[2] = /*0x98badcfe*/ T_MASK ^ 0x67452301; - pms->abcd[3] = 0x10325476; -} - -void -md5_append( md5_state_t *pms, const md5_byte_t *data, int nbytes ){ - const md5_byte_t *p = data; - int left = nbytes; - int offset = ( pms->count[0] >> 3 ) & 63; - md5_word_t nbits = (md5_word_t)( nbytes << 3 ); - - if ( nbytes <= 0 ) { - return; - } - - /* Update the message length. */ - pms->count[1] += nbytes >> 29; - pms->count[0] += nbits; - if ( pms->count[0] < nbits ) { - pms->count[1]++; - } - - /* Process an initial partial block. */ - if ( offset ) { - int copy = ( offset + nbytes > 64 ? 64 - offset : nbytes ); - - memcpy( pms->buf + offset, p, copy ); - if ( offset + copy < 64 ) { - return; - } - p += copy; - left -= copy; - md5_process( pms, pms->buf ); - } - - /* Process full blocks. */ - for (; left >= 64; p += 64, left -= 64 ) - md5_process( pms, p ); - - /* Process a final partial block. */ - if ( left ) { - memcpy( pms->buf, p, left ); - } -} - -void -md5_finish( md5_state_t *pms, md5_byte_t digest[16] ){ - static const md5_byte_t pad[64] = { - 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 - }; - md5_byte_t data[8]; - int i; - - /* Save the length before padding. */ - for ( i = 0; i < 8; ++i ) - data[i] = (md5_byte_t)( pms->count[i >> 2] >> ( ( i & 3 ) << 3 ) ); - /* Pad to 56 bytes mod 64. */ - md5_append( pms, pad, ( ( 55 - ( pms->count[0] >> 3 ) ) & 63 ) + 1 ); - /* Append the length. */ - md5_append( pms, data, 8 ); - for ( i = 0; i < 16; ++i ) - digest[i] = (md5_byte_t)( pms->abcd[i >> 2] >> ( ( i & 3 ) << 3 ) ); -} diff --git a/tools/urt/libs/md5lib/md5lib.dsp b/tools/urt/libs/md5lib/md5lib.dsp deleted file mode 100644 index 81addbb..0000000 --- a/tools/urt/libs/md5lib/md5lib.dsp +++ /dev/null @@ -1,106 +0,0 @@ -# Microsoft Developer Studio Project File - Name="md5lib" - Package Owner=<4> -# Microsoft Developer Studio Generated Build File, Format Version 6.00 -# ** DO NOT EDIT ** - -# TARGTYPE "Win32 (x86) Static Library" 0x0104 - -CFG=md5lib - Win32 Debug -!MESSAGE This is not a valid makefile. To build this project using NMAKE, -!MESSAGE use the Export Makefile command and run -!MESSAGE -!MESSAGE NMAKE /f "md5lib.mak". -!MESSAGE -!MESSAGE You can specify a configuration when running NMAKE -!MESSAGE by defining the macro CFG on the command line. For example: -!MESSAGE -!MESSAGE NMAKE /f "md5lib.mak" CFG="md5lib - Win32 Debug" -!MESSAGE -!MESSAGE Possible choices for configuration are: -!MESSAGE -!MESSAGE "md5lib - Win32 Release" (based on "Win32 (x86) Static Library") -!MESSAGE "md5lib - Win32 Debug" (based on "Win32 (x86) Static Library") -!MESSAGE - -# Begin Project -# PROP AllowPerConfigDependencies 0 -# PROP Scc_ProjName "Perforce Project" -# PROP Scc_LocalPath ".." -CPP=cl.exe -RSC=rc.exe - -!IF "$(CFG)" == "md5lib - Win32 Release" - -# PROP BASE Use_MFC 0 -# PROP BASE Use_Debug_Libraries 0 -# PROP BASE Output_Dir "Release" -# PROP BASE Intermediate_Dir "Release" -# PROP BASE Target_Dir "" -# PROP Use_MFC 0 -# PROP Use_Debug_Libraries 0 -# PROP Output_Dir "Release" -# PROP Intermediate_Dir "Release" -# PROP Target_Dir "" -MTL=midl.exe -F90=df.exe -# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /YX /FD /c -# ADD CPP /nologo /MD /W3 /O2 /I ".." /D "WIN32" /D "NDEBUG" /D "_MBCS" /D "_LIB" /FR /FD /c -# SUBTRACT CPP /YX -# ADD BASE RSC /l 0x409 /d "NDEBUG" -# ADD RSC /l 0x409 /d "NDEBUG" -BSC32=bscmake.exe -# ADD BASE BSC32 /nologo -# ADD BSC32 /nologo -LIB32=link.exe -lib -# ADD BASE LIB32 /nologo -# ADD LIB32 /nologo - -!ELSEIF "$(CFG)" == "md5lib - Win32 Debug" - -# PROP BASE Use_MFC 0 -# PROP BASE Use_Debug_Libraries 1 -# PROP BASE Output_Dir "Debug" -# PROP BASE Intermediate_Dir "Debug" -# PROP BASE Target_Dir "" -# PROP Use_MFC 0 -# PROP Use_Debug_Libraries 1 -# PROP Output_Dir "Debug" -# PROP Intermediate_Dir "Debug" -# PROP Target_Dir "" -MTL=midl.exe -F90=df.exe -# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /YX /FD /GZ /c -# ADD CPP /nologo /MDd /W3 /Gm /ZI /Od /I ".." /D "WIN32" /D "_DEBUG" /D "_MBCS" /D "_LIB" /FR /FD /GZ /c -# SUBTRACT CPP /YX -# ADD BASE RSC /l 0x409 /d "_DEBUG" -# ADD RSC /l 0x409 /d "_DEBUG" -BSC32=bscmake.exe -# ADD BASE BSC32 /nologo -# ADD BSC32 /nologo -LIB32=link.exe -lib -# ADD BASE LIB32 /nologo -# ADD LIB32 /nologo - -!ENDIF - -# Begin Target - -# Name "md5lib - Win32 Release" -# Name "md5lib - Win32 Debug" -# Begin Group "src" - -# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat" -# Begin Source File - -SOURCE=.\md5lib.c -# End Source File -# End Group -# Begin Group "include" - -# PROP Default_Filter "h;hpp;hxx;hm;inl" -# Begin Source File - -SOURCE=..\md5lib.h -# End Source File -# End Group -# End Target -# End Project diff --git a/tools/urt/libs/md5lib/md5lib.vcproj b/tools/urt/libs/md5lib/md5lib.vcproj deleted file mode 100644 index 08eb232..0000000 --- a/tools/urt/libs/md5lib/md5lib.vcproj +++ /dev/null @@ -1,211 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/tools/urt/libs/memory/allocator.cpp b/tools/urt/libs/memory/allocator.cpp deleted file mode 100644 index b4dbdcd..0000000 --- a/tools/urt/libs/memory/allocator.cpp +++ /dev/null @@ -1,56 +0,0 @@ - -#include "memory/allocator.h" - -#include - -template -struct Vector -{ - typedef std::vector > Type; -}; - -namespace -{ -class Bleh -{ -int* m_blah; -public: -Bleh( int* blah ) : m_blah( blah ){ -} -~Bleh(){ - *m_blah = 15; -} -}; - -void TestAllocator(){ - Vector::Type test; - - int i = 0; - test.push_back( Bleh( &i ) ); -} - -void TestNewDelete(){ - { - NamedAllocator allocator( "test" ); - int* p = NamedNew::type( allocator ).scalar(); - //new int(); - NamedDelete::type( allocator ).scalar( p ); - } - - { - int* p = New().scalar( 3 ); - Delete().scalar( p ); - } - - { - int* p = New().scalar( int(15.9) ); - Delete().scalar( p ); - } - - { - int* p = New().vector( 15 ); - // new int[15] - Delete().vector( p, 15 ); - } -} -} \ No newline at end of file diff --git a/tools/urt/libs/memory/allocator.h b/tools/urt/libs/memory/allocator.h deleted file mode 100644 index 43c68f5..0000000 --- a/tools/urt/libs/memory/allocator.h +++ /dev/null @@ -1,270 +0,0 @@ - -#if !defined( INCLUDED_MEMORY_ALLOCATOR_H ) -#define INCLUDED_MEMORY_ALLOCATOR_H - -#include - -#if 0 - -#define DefaultAllocator std::allocator - -#else - -/// \brief An allocator that uses c++ new/delete. -/// Compliant with the std::allocator interface. -template -class DefaultAllocator -{ -public: - -typedef Type value_type; -typedef value_type* pointer; -typedef const Type* const_pointer; -typedef Type& reference; -typedef const Type& const_reference; -typedef size_t size_type; -typedef ptrdiff_t difference_type; - -template -struct rebind -{ - typedef DefaultAllocator other; -}; - -DefaultAllocator(){ -} -DefaultAllocator( const DefaultAllocator& ){ -} -template DefaultAllocator( const DefaultAllocator& ){ -} -~DefaultAllocator(){ -} - -pointer address( reference instance ) const { - return &instance; -} -const_pointer address( const_reference instance ) const { - return &instance; -} -Type* allocate( size_type size, const void* = 0 ){ - return static_cast( ::operator new( size * sizeof( Type ) ) ); -} -void deallocate( pointer p, size_type ){ - ::operator delete( p ); -} -size_type max_size() const { - return std::size_t( -1 ) / sizeof( Type ); -} -void construct( pointer p, const Type& value ){ - new(p) Type( value ); -} -void destroy( pointer p ){ - p->~Type(); -} -}; - -template -inline bool operator==( const DefaultAllocator&, const DefaultAllocator& ){ - return true; -} -template -inline bool operator==( const DefaultAllocator&, const OtherAllocator& ){ - return false; -} - -#endif - - -template -class NamedAllocator : public DefaultAllocator -{ -typedef DefaultAllocator allocator_type; - -const char* m_name; -public: - -typedef Type value_type; -typedef value_type* pointer; -typedef const Type* const_pointer; -typedef Type& reference; -typedef const Type& const_reference; -typedef size_t size_type; -typedef ptrdiff_t difference_type; - -template -struct rebind -{ - typedef NamedAllocator other; -}; - -explicit NamedAllocator( const char* name ) : m_name( name ){ -} -NamedAllocator( const NamedAllocator& other ) : m_name( other.m_name ){ -} -template NamedAllocator( const NamedAllocator& other ) : m_name( other.m_name ){ -} -~NamedAllocator(){ -} - -pointer address( reference instance ) const { - return allocator_type::address( instance ); -} -const_pointer address( const_reference instance ) const { - return allocator_type::address( instance ); -} -Type* allocate( size_type size, const void* = 0 ){ - return allocator_type::allocate( size ); -} -void deallocate( pointer p, size_type size ){ - allocator_type::deallocate( p, size ); -} -size_type max_size() const { - return allocator_type::max_size(); -} -void construct( pointer p, const Type& value ){ - allocator_type::construct( p, value ); -} -void destroy( pointer p ){ - allocator_type::destroy( p ); -} - -template -bool operator==( const NamedAllocator& other ){ - return true; -} - -// returns true if the allocators are not interchangeable -template -bool operator!=( const NamedAllocator& other ){ - return false; -} -}; - - - -#include -#include "generic/object.h" - - - -template -class DefaultConstruct -{ -public: -void operator()( Type& t ){ - constructor( t ); -} -}; - -template -class Construct -{ -const T1& other; -public: -Construct( const T1& other_ ) : other( other_ ){ -} -void operator()( Type& t ){ - constructor( t, other ); -} -}; - -template -class Destroy -{ -public: -void operator()( Type& t ){ - destructor( t ); -} -}; - -template > -class New : public Allocator -{ -public: -New(){ -} -explicit New( const Allocator& allocator ) : Allocator( allocator ){ -} - -Type* scalar(){ - return new( Allocator::allocate( 1 ) )Type(); -} -template -Type* scalar( const T1& t1 ){ - return new( Allocator::allocate( 1 ) )Type( t1 ); -} -template -Type* scalar( const T1& t1, const T2& t2 ){ - return new( Allocator::allocate( 1 ) )Type( t1, t2 ); -} -template -Type* scalar( const T1& t1, const T2& t2, const T3& t3 ){ - return new( Allocator::allocate( 1 ) )Type( t1, t2, t3 ); -} -template -Type* scalar( const T1& t1, const T2& t2, const T3& t3, const T4& t4 ){ - return new( Allocator::allocate( 1 ) )Type( t1, t2, t3, t4 ); -} -template -Type* scalar( const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5 ){ - return new( Allocator::allocate( 1 ) )Type( t1, t2, t3, t4, t5 ); -} -Type* vector( std::size_t size ){ -#if 1 - Type* p = Allocator::allocate( size ); - std::for_each( p, p + size, DefaultConstruct() ); - return p; -#else - // this does not work with msvc71 runtime - return new( Allocator::allocate( size ) )Type[size]; -#endif -} -template -Type* vector( std::size_t size, const T1& t1 ){ - Type* p = Allocator::allocate( size ); - std::for_each( p, p + size, Construct( t1 ) ); - return p; -} -}; - -template > -class Delete : public Allocator -{ -public: -Delete(){ -} -explicit Delete( const Allocator& allocator ) : Allocator( allocator ){ -} - -void scalar( Type* p ){ - if ( p != 0 ) { - p->~Type(); - Allocator::deallocate( p, 1 ); - } -} -void vector( Type* p, std::size_t size ){ - // '::operator delete' handles null - // 'std::allocator::deallocate' requires non-null - if ( p != 0 ) { - std::for_each( p, p + size, Destroy() ); - Allocator::deallocate( p, size ); - } -} -}; - - -template -class NamedNew -{ -public: -typedef New > type; -}; - -template -class NamedDelete -{ -public: -typedef Delete > type; -}; - -#endif diff --git a/tools/urt/libs/moduleobservers.cpp b/tools/urt/libs/moduleobservers.cpp deleted file mode 100644 index e4aa286..0000000 --- a/tools/urt/libs/moduleobservers.cpp +++ /dev/null @@ -1,2 +0,0 @@ - -#include "moduleobservers.h" diff --git a/tools/urt/libs/moduleobservers.h b/tools/urt/libs/moduleobservers.h deleted file mode 100644 index 006cfe9..0000000 --- a/tools/urt/libs/moduleobservers.h +++ /dev/null @@ -1,39 +0,0 @@ - -#if !defined( INCLUDED_MODULEOBSERVERS_H ) -#define INCLUDED_MODULEOBSERVERS_H - -#include "debugging/debugging.h" -#include -#include "moduleobserver.h" - -class ModuleObservers -{ -typedef std::set Observers; -Observers m_observers; -public: -~ModuleObservers(){ - ASSERT_MESSAGE( m_observers.empty(), "ModuleObservers::~ModuleObservers: observers still attached" ); -} -void attach( ModuleObserver& observer ){ - ASSERT_MESSAGE( m_observers.find( &observer ) == m_observers.end(), "ModuleObservers::attach: cannot attach observer" ); - m_observers.insert( &observer ); -} -void detach( ModuleObserver& observer ){ - ASSERT_MESSAGE( m_observers.find( &observer ) != m_observers.end(), "ModuleObservers::detach: cannot detach observer" ); - m_observers.erase( &observer ); -} -void realise(){ - for ( Observers::iterator i = m_observers.begin(); i != m_observers.end(); ++i ) - { - ( *i )->realise(); - } -} -void unrealise(){ - for ( Observers::reverse_iterator i = m_observers.rbegin(); i != m_observers.rend(); ++i ) - { - ( *i )->unrealise(); - } -} -}; - -#endif diff --git a/tools/urt/libs/modulesystem/moduleregistry.cpp b/tools/urt/libs/modulesystem/moduleregistry.cpp deleted file mode 100644 index ce5580d..0000000 --- a/tools/urt/libs/modulesystem/moduleregistry.cpp +++ /dev/null @@ -1,2 +0,0 @@ - -#include "moduleregistry.h" diff --git a/tools/urt/libs/modulesystem/moduleregistry.h b/tools/urt/libs/modulesystem/moduleregistry.h deleted file mode 100644 index a15558e..0000000 --- a/tools/urt/libs/modulesystem/moduleregistry.h +++ /dev/null @@ -1,42 +0,0 @@ - -#if !defined( INCLUDED_MODULESYSTEM_MODULEREGISTRY_H ) -#define INCLUDED_MODULESYSTEM_MODULEREGISTRY_H - -#include "generic/static.h" -#include - -class ModuleRegisterable -{ -public: -virtual void selfRegister() = 0; -}; - -class ModuleRegistryList -{ -typedef std::list RegisterableModules; -RegisterableModules m_modules; -public: -void addModule( ModuleRegisterable& module ){ - m_modules.push_back( &module ); -} -void registerModules() const { - for ( RegisterableModules::const_iterator i = m_modules.begin(); i != m_modules.end(); ++i ) - { - ( *i )->selfRegister(); - } -} -}; - -typedef SmartStatic StaticModuleRegistryList; - - -class StaticRegisterModule : public StaticModuleRegistryList -{ -public: -StaticRegisterModule( ModuleRegisterable& module ){ - StaticModuleRegistryList::instance().addModule( module ); -} -}; - - -#endif diff --git a/tools/urt/libs/modulesystem/modulesmap.cpp b/tools/urt/libs/modulesystem/modulesmap.cpp deleted file mode 100644 index e31d642..0000000 --- a/tools/urt/libs/modulesystem/modulesmap.cpp +++ /dev/null @@ -1,2 +0,0 @@ - -#include "modulesmap.h" diff --git a/tools/urt/libs/modulesystem/modulesmap.h b/tools/urt/libs/modulesystem/modulesmap.h deleted file mode 100644 index cb5fd40..0000000 --- a/tools/urt/libs/modulesystem/modulesmap.h +++ /dev/null @@ -1,115 +0,0 @@ - -#if !defined( INCLUDED_MODULESYSTEM_MODULESMAP_H ) -#define INCLUDED_MODULESYSTEM_MODULESMAP_H - -#include "modulesystem.h" -#include "string/string.h" -#include -#include - -template -class ModulesMap : public Modules -{ -typedef std::map modules_t; -modules_t m_modules; -public: -~ModulesMap(){ - for ( modules_t::iterator i = m_modules.begin(); i != m_modules.end(); ++i ) - { - ( *i ).second->release(); - } -} - -typedef modules_t::const_iterator iterator; - -iterator begin() const { - return m_modules.begin(); -} -iterator end() const { - return m_modules.end(); -} - -void insert( const char* name, Module& module ){ - module.capture(); - if ( globalModuleServer().getError() ) { - module.release(); - globalModuleServer().setError( false ); - } - else - { - m_modules.insert( modules_t::value_type( name, &module ) ); - } -} - -Type* find( const char* name ){ - modules_t::iterator i = m_modules.find( name ); - if ( i != m_modules.end() ) { - return static_cast( Module_getTable( *( *i ).second ) ); - } - return 0; -} - -Type* findModule( const char* name ){ - return find( name ); -} -void foreachModule( typename Modules::Visitor& visitor ){ - for ( modules_t::iterator i = m_modules.begin(); i != m_modules.end(); ++i ) - { - visitor.visit( ( *i ).first.c_str(), *static_cast( Module_getTable( *( *i ).second ) ) ); - } -} -}; - -template -class InsertModules : public ModuleServer::Visitor -{ -ModulesMap& m_modules; -public: -InsertModules( ModulesMap& modules ) - : m_modules( modules ){ -} -void visit( const char* name, Module& module ){ - m_modules.insert( name, module ); -} -}; - -template -class ModulesRef -{ -ModulesMap m_modules; -public: -ModulesRef( const char* names ){ - if ( !globalModuleServer().getError() ) { - if ( string_equal( names, "*" ) ) { - InsertModules visitor( m_modules ); - globalModuleServer().foreachModule( Type::name(), Type::VERSION, visitor ); - } - else - { - StringTokeniser tokeniser( names ); - for (;; ) - { - const char* name = tokeniser.getToken(); - if ( string_empty( name ) ) { - break; - } - Module* module = globalModuleServer().findModule( Type::name(), Type::VERSION, name ); - if ( module == 0 ) { - globalModuleServer().setError( true ); - globalErrorStream() << "ModulesRef::initialise: type=" << makeQuoted( Type::name() ) << " version= " << makeQuoted( int(Type::VERSION) ) << " name=" << makeQuoted( name ) << " - not found\n"; - break; - } - else - { - m_modules.insert( name, *module ); - } - } - } - } -} -ModulesMap& get(){ - return m_modules; -} -}; - -#endif diff --git a/tools/urt/libs/modulesystem/singletonmodule.cpp b/tools/urt/libs/modulesystem/singletonmodule.cpp deleted file mode 100644 index 67b25f8..0000000 --- a/tools/urt/libs/modulesystem/singletonmodule.cpp +++ /dev/null @@ -1,29 +0,0 @@ - -#include "singletonmodule.h" - -class NullType -{ -public: -enum { VERSION = 1 }; -static const char* name(){ - return ""; -} -}; - -class NullModule -{ -public: -typedef NullType Type; -static const char* getName(){ - return ""; -} -void* getTable(){ - return NULL; -} -}; - -void TEST_SINGLETONMODULE(){ - SingletonModule null; - null.capture(); - null.release(); -} diff --git a/tools/urt/libs/modulesystem/singletonmodule.h b/tools/urt/libs/modulesystem/singletonmodule.h deleted file mode 100644 index 8ba0884..0000000 --- a/tools/urt/libs/modulesystem/singletonmodule.h +++ /dev/null @@ -1,111 +0,0 @@ - -#if !defined( INCLUDED_MODULESYSTEM_SINGLETONMODULE_H ) -#define INCLUDED_MODULESYSTEM_SINGLETONMODULE_H - -#include "modulesystem.h" -#include -#include "debugging/debugging.h" -#include "modulesystem/moduleregistry.h" -#include "generic/reference.h" - -template -class DefaultAPIConstructor -{ -public: -const char* getName(){ - return API::getName(); -} - -API* constructAPI( Dependencies& dependencies ){ - return new API; -} -void destroyAPI( API* api ){ - delete api; -} -}; - -template -class DependenciesAPIConstructor -{ -public: -const char* getName(){ - return API::getName(); -} - -API* constructAPI( Dependencies& dependencies ){ - return new API( dependencies ); -} -void destroyAPI( API* api ){ - delete api; -} -}; - -class NullDependencies -{ -}; - - -template > -class SingletonModule : public APIConstructor, public Module, public ModuleRegisterable -{ -Dependencies* m_dependencies; -API* m_api; -std::size_t m_refcount; -bool m_dependencyCheck; -bool m_cycleCheck; -public: -typedef typename API::Type Type; - -SingletonModule() - : m_dependencies( 0 ), m_api( 0 ), m_refcount( 0 ), m_dependencyCheck( false ), m_cycleCheck( false ){ -} -explicit SingletonModule( const APIConstructor& constructor ) - : APIConstructor( constructor ), m_dependencies( 0 ), m_api( 0 ), m_refcount( 0 ), m_dependencyCheck( false ), m_cycleCheck( false ){ -} -~SingletonModule(){ - ASSERT_MESSAGE( m_refcount == 0, "module still referenced at shutdown" ); -} - -void selfRegister(){ - globalModuleServer().registerModule( Type::name(), Type::VERSION, APIConstructor::getName(), *this ); -} - -Dependencies& getDependencies(){ - return *m_dependencies; -} -void* getTable(){ - if ( m_api != 0 ) { - return m_api->getTable(); - } - return 0; -} -void capture(){ - if ( ++m_refcount == 1 ) { - globalOutputStream() << "Module Initialising: '" << Type::name() << "' '" << APIConstructor::getName() << "'\n"; - m_dependencies = new Dependencies(); - m_dependencyCheck = !globalModuleServer().getError(); - if ( m_dependencyCheck ) { - m_api = APIConstructor::constructAPI( *m_dependencies ); - globalOutputStream() << "Module Ready: '" << Type::name() << "' '" << APIConstructor::getName() << "'\n"; - } - else - { - globalOutputStream() << "Module Dependencies Failed: '" << Type::name() << "' '" << APIConstructor::getName() << "'\n"; - } - m_cycleCheck = true; - } - - ASSERT_MESSAGE( m_cycleCheck, "cyclic dependency detected" ); -} -void release(){ - if ( --m_refcount == 0 ) { - if ( m_dependencyCheck ) { - APIConstructor::destroyAPI( m_api ); - } - delete m_dependencies; - } -} -}; - - -#endif diff --git a/tools/urt/libs/os/dir.cpp b/tools/urt/libs/os/dir.cpp deleted file mode 100644 index f25dd69..0000000 --- a/tools/urt/libs/os/dir.cpp +++ /dev/null @@ -1,2 +0,0 @@ - -#include "dir.h" diff --git a/tools/urt/libs/os/dir.h b/tools/urt/libs/os/dir.h deleted file mode 100644 index 7f6d224..0000000 --- a/tools/urt/libs/os/dir.h +++ /dev/null @@ -1,48 +0,0 @@ - -#if !defined( INCLUDED_OS_DIR_H ) -#define INCLUDED_OS_DIR_H - -/// \file -/// \brief OS directory-listing object. - -#include - -typedef GDir Directory; - -inline bool directory_good( Directory* directory ){ - return directory != 0; -} - -inline Directory* directory_open( const char* name ){ - return g_dir_open( name, 0, 0 ); -} - -inline void directory_close( Directory* directory ){ - g_dir_close( directory ); -} - -inline const char* directory_read_and_increment( Directory* directory ){ - return g_dir_read_name( directory ); -} - -template -void Directory_forEach( const char* path, const Functor& functor ){ - Directory* dir = directory_open( path ); - - if ( directory_good( dir ) ) { - for (;; ) - { - const char* name = directory_read_and_increment( dir ); - if ( name == 0 ) { - break; - } - - functor( name ); - } - - directory_close( dir ); - } -} - - -#endif diff --git a/tools/urt/libs/os/file.cpp b/tools/urt/libs/os/file.cpp deleted file mode 100644 index cd1c8c0..0000000 --- a/tools/urt/libs/os/file.cpp +++ /dev/null @@ -1,2 +0,0 @@ - -#include "file.h" diff --git a/tools/urt/libs/os/file.h b/tools/urt/libs/os/file.h deleted file mode 100644 index 22edf01..0000000 --- a/tools/urt/libs/os/file.h +++ /dev/null @@ -1,111 +0,0 @@ - -#if !defined( INCLUDED_OS_FILE_H ) -#define INCLUDED_OS_FILE_H - -/// \file -/// \brief OS file-system querying and manipulation. - -#if defined( WIN32 ) -#define S_ISDIR( mode ) ( mode & _S_IFDIR ) -#include // access() -#define F_OK 0x00 -#define W_OK 0x02 -#define R_OK 0x04 -#else -#include // access() -#endif - -#include // rename(), remove() -#include // stat() -#include // this is included by stat.h on win32 -#include -#include - -/// \brief Attempts to move the file identified by \p from to \p to and returns true if the operation was successful. -/// -/// The operation will fail unless: -/// - The path \p from identifies an existing file which is accessible for writing. -/// - The directory component of \p from identifies an existing directory which is accessible for writing. -/// - The path \p to does not identify an existing file or directory. -/// - The directory component of \p to identifies an existing directory which is accessible for writing. -inline bool file_move( const char* from, const char* to ){ - return rename( from, to ) == 0; -} - -/// \brief Attempts to remove the file identified by \p path and returns true if the operation was successful. -/// -/// The operation will fail unless: -/// - The \p path identifies an existing file. -/// - The parent-directory component of \p path identifies an existing directory which is accessible for writing. -inline bool file_remove( const char* path ){ - return remove( path ) == 0; -} - -namespace FileAccess -{ -enum Mode -{ - Read = R_OK, - Write = W_OK, - ReadWrite = Read | Write, - Exists = F_OK -}; -} - -/// \brief Returns true if the file or directory identified by \p path exists and/or may be accessed for reading, writing or both, depending on the value of \p mode. -inline bool file_accessible( const char* path, FileAccess::Mode mode ){ - return access( path, static_cast( mode ) ) == 0; -} - -/// \brief Returns true if the file or directory identified by \p path exists and may be opened for reading. -inline bool file_readable( const char* path ){ - return file_accessible( path, FileAccess::Read ); -} - -/// \brief Returns true if the file or directory identified by \p path exists and may be opened for writing. -inline bool file_writeable( const char* path ){ - return file_accessible( path, FileAccess::Write ); -} - -/// \brief Returns true if the file or directory identified by \p path exists. -inline bool file_exists( const char* path ){ - return file_accessible( path, FileAccess::Exists ); -} - -/// \brief Returns true if the file or directory identified by \p path exists and is a directory. -inline bool file_is_directory( const char* path ){ - struct stat st; - if ( stat( path, &st ) == -1 ) { - return false; - } - return S_ISDIR( st.st_mode ) != 0; -} - -typedef std::size_t FileSize; - -/// \brief Returns the size in bytes of the file identified by \p path, or 0 if the file was not found. -inline FileSize file_size( const char* path ){ - struct stat st; - if ( stat( path, &st ) == -1 ) { - return 0; - } - return st.st_size; -} - -/// Seconds elapsed since Jan 1, 1970 -typedef std::time_t FileTime; -/// No file can have been modified earlier than this time. -const FileTime c_invalidFileTime = -1; - -/// \brief Returns the time that the file identified by \p path was last modified, or c_invalidFileTime if the file was not found. -inline FileTime file_modified( const char* path ){ - struct stat st; - if ( stat( path, &st ) == -1 ) { - return c_invalidFileTime; - } - return st.st_mtime; -} - - - -#endif diff --git a/tools/urt/libs/os/path.cpp b/tools/urt/libs/os/path.cpp deleted file mode 100644 index c39d8d9..0000000 --- a/tools/urt/libs/os/path.cpp +++ /dev/null @@ -1,2 +0,0 @@ - -#include "path.h" diff --git a/tools/urt/libs/os/path.h b/tools/urt/libs/os/path.h deleted file mode 100644 index d638fc0..0000000 --- a/tools/urt/libs/os/path.h +++ /dev/null @@ -1,233 +0,0 @@ - -#if !defined ( INCLUDED_OS_PATH_H ) -#define INCLUDED_OS_PATH_H - -/// \file -/// \brief OS file-system path comparison, decomposition and manipulation. -/// -/// - Paths are c-style null-terminated-character-arrays. -/// - Path separators must be forward slashes (unix style). -/// - Directory paths must end in a separator. -/// - Paths must not contain the ascii characters \\ : * ? " < > or |. -/// - Paths may be encoded in UTF-8 or any extended-ascii character set. - -#include "string/string.h" - -#if defined( WIN32 ) -#define OS_CASE_INSENSITIVE -#endif - -/// \brief Returns true if \p path is lexicographically sorted before \p other. -/// If both \p path and \p other refer to the same file, neither will be sorted before the other. -/// O(n) -inline bool path_less( const char* path, const char* other ){ -#if defined( OS_CASE_INSENSITIVE ) - return string_less_nocase( path, other ); -#else - return string_less( path, other ); -#endif -} - -/// \brief Returns <0 if \p path is lexicographically less than \p other. -/// Returns >0 if \p path is lexicographically greater than \p other. -/// Returns 0 if both \p path and \p other refer to the same file. -/// O(n) -inline int path_compare( const char* path, const char* other ){ -#if defined( OS_CASE_INSENSITIVE ) - return string_compare_nocase( path, other ); -#else - return string_compare( path, other ); -#endif -} - -/// \brief Returns true if \p path and \p other refer to the same file or directory. -/// O(n) -inline bool path_equal( const char* path, const char* other ){ -#if defined( OS_CASE_INSENSITIVE ) - return string_equal_nocase( path, other ); -#else - return string_equal( path, other ); -#endif -} - -/// \brief Returns true if the first \p n bytes of \p path and \p other form paths that refer to the same file or directory. -/// If the paths are UTF-8 encoded, [\p path, \p path + \p n) must be a complete path. -/// O(n) -inline bool path_equal_n( const char* path, const char* other, std::size_t n ){ -#if defined( OS_CASE_INSENSITIVE ) - return string_equal_nocase_n( path, other, n ); -#else - return string_equal_n( path, other, n ); -#endif -} - - -/// \brief Returns true if \p path is a fully qualified file-system path. -/// O(1) -inline bool path_is_absolute( const char* path ){ -#if defined( WIN32 ) - return path[0] == '/' - || ( path[0] != '\0' && path[1] == ':' ); // local drive -#elif defined( __linux__ ) || defined( __APPLE__ ) - return path[0] == '/'; -#endif -} - -/// \brief Returns true if \p path is a directory. -/// O(n) -inline bool path_is_directory( const char* path ){ - std::size_t length = strlen( path ); - if ( length > 0 ) { - return path[length - 1] == '/'; - } - return false; -} - -/// \brief Returns a pointer to the first character of the component of \p path following the first directory component. -/// O(n) -inline const char* path_remove_directory( const char* path ){ - const char* first_separator = strchr( path, '/' ); - if ( first_separator != 0 ) { - return ++first_separator; - } - return ""; -} - -/// \brief Returns a pointer to the first character of the filename component of \p path. -/// O(n) -inline const char* path_get_filename_start( const char* path ){ - { - const char* last_forward_slash = strrchr( path, '/' ); - if ( last_forward_slash != 0 ) { - return last_forward_slash + 1; - } - } - - // not strictly necessary,since paths should not contain '\' - { - const char* last_backward_slash = strrchr( path, '\\' ); - if ( last_backward_slash != 0 ) { - return last_backward_slash + 1; - } - } - - return path; -} - -/// \brief Returns a pointer to the character after the end of the filename component of \p path - either the extension separator or the terminating null character. -/// O(n) -inline const char* path_get_filename_base_end( const char* path ){ - const char* last_period = strrchr( path_get_filename_start( path ), '.' ); - return ( last_period != 0 ) ? last_period : path + string_length( path ); -} - -/// \brief Returns the length of the filename component (not including extension) of \p path. -/// O(n) -inline std::size_t path_get_filename_base_length( const char* path ){ - return path_get_filename_base_end( path ) - path; -} - -/// \brief If \p path is a child of \p base, returns the subpath relative to \p base, else returns \p path. -/// O(n) -inline const char* path_make_relative( const char* path, const char* base ){ - const std::size_t length = string_length( base ); - if ( path_equal_n( path, base, length ) ) { - return path + length; - } - return path; -} - -/// \brief Returns a pointer to the first character of the file extension of \p path, or "" if not found. -/// O(n) -inline const char* path_get_extension( const char* path ){ - const char* last_period = strrchr( path_get_filename_start( path ), '.' ); - if ( last_period != 0 ) { - return ++last_period; - } - return ""; -} - -/// \brief Returns true if \p extension is of the same type as \p other. -/// O(n) -inline bool extension_equal( const char* extension, const char* other ){ - return path_equal( extension, other ); -} - -template -class MatchFileExtension -{ -const char* m_extension; -const Functor& m_functor; -public: -MatchFileExtension( const char* extension, const Functor& functor ) : m_extension( extension ), m_functor( functor ){ -} -void operator()( const char* name ) const { - const char* extension = path_get_extension( name ); - if ( extension_equal( extension, m_extension ) ) { - m_functor( name ); - } -} -}; - -/// \brief A functor which invokes its contained \p functor if the \p name argument matches its \p extension. -template -inline MatchFileExtension matchFileExtension( const char* extension, const Functor& functor ){ - return MatchFileExtension( extension, functor ); -} - -class PathCleaned -{ -public: -const char* m_path; -PathCleaned( const char* path ) : m_path( path ){ -} -}; - -/// \brief Writes \p path to \p ostream with dos-style separators replaced by unix-style separators. -template -TextOutputStreamType& ostream_write( TextOutputStreamType& ostream, const PathCleaned& path ){ - const char* i = path.m_path; - for (; *i != '\0'; ++i ) - { - if ( *i == '\\' ) { - ostream << '/'; - } - else - { - ostream << *i; - } - } - return ostream; -} - -class DirectoryCleaned -{ -public: -const char* m_path; -DirectoryCleaned( const char* path ) : m_path( path ){ -} -}; - -/// \brief Writes \p path to \p ostream with dos-style separators replaced by unix-style separators, and appends a separator if necessary. -template -TextOutputStreamType& ostream_write( TextOutputStreamType& ostream, const DirectoryCleaned& path ){ - const char* i = path.m_path; - for (; *i != '\0'; ++i ) - { - if ( *i == '\\' ) { - ostream << '/'; - } - else - { - ostream << *i; - } - } - char c = *( i - 1 ); - if ( c != '/' && c != '\\' ) { - ostream << '/'; - } - return ostream; -} - - -#endif diff --git a/tools/urt/libs/picomodel.h b/tools/urt/libs/picomodel.h deleted file mode 100644 index d5c0053..0000000 --- a/tools/urt/libs/picomodel.h +++ /dev/null @@ -1,353 +0,0 @@ -/* ----------------------------------------------------------------------------- - - PicoModel Library - - Copyright (c) 2002, Randy Reddig & seaw0lf - All rights reserved. - - Redistribution and use in source and binary forms, with or without modification, - are permitted provided that the following conditions are met: - - Redistributions of source code must retain the above copyright notice, this list - of conditions and the following disclaimer. - - Redistributions in binary form must reproduce the above copyright notice, this - list of conditions and the following disclaimer in the documentation and/or - other materials provided with the distribution. - - Neither the names of the copyright holders nor the names of its contributors may - be used to endorse or promote products derived from this software without - specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR - ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - ----------------------------------------------------------------------------- */ - - - -/* marker */ -#ifndef PICOMODEL_H -#define PICOMODEL_H - -#ifdef __cplusplus -extern "C" -{ -#endif - -#include - - - -/* version */ -#define PICOMODEL_VERSION "0.8.20" - - -/* constants */ -#define PICO_GROW_SHADERS 16 -#define PICO_GROW_SURFACES 16 -#define PICO_GROW_VERTEXES 1024 -#define PICO_GROW_INDEXES 1024 -#define PICO_GROW_ARRAYS 8 -#define PICO_GROW_FACES 256 -#define PICO_MAX_SPECIAL 8 -#define PICO_MAX_DEFAULT_EXTS 4 /* max default extensions per module */ - - -/* types */ -typedef unsigned char picoByte_t; -typedef float picoVec_t; -typedef float picoVec2_t[ 2 ]; -typedef float picoVec3_t[ 3 ]; -typedef float picoVec4_t[ 4 ]; -typedef picoByte_t picoColor_t[ 4 ]; -typedef int picoIndex_t; - -typedef enum -{ - PICO_BAD, - PICO_TRIANGLES, - PICO_PATCH -} -picoSurfaceType_t; - -typedef enum -{ - PICO_NORMAL, - PICO_VERBOSE, - PICO_WARNING, - PICO_ERROR, - PICO_FATAL -} -picoPrintLevel_t; - -typedef struct picoSurface_s picoSurface_t; -typedef struct picoShader_s picoShader_t; -typedef struct picoModel_s picoModel_t; -typedef struct picoModule_s picoModule_t; - -struct picoSurface_s -{ - void *data; - - picoModel_t *model; /* owner model */ - - picoSurfaceType_t type; - char *name; /* sea: surface name */ - picoShader_t *shader; /* ydnar: changed to ptr */ - - int numVertexes, maxVertexes; - picoVec3_t *xyz; - picoVec3_t *normal; - picoIndex_t *smoothingGroup; - - int numSTArrays, maxSTArrays; - picoVec2_t **st; - - int numColorArrays, maxColorArrays; - picoColor_t **color; - - int numIndexes, maxIndexes; - picoIndex_t *index; - - int numFaceNormals, maxFaceNormals; - picoVec3_t *faceNormal; - - int special[ PICO_MAX_SPECIAL ]; - - int submodel; //sub models are tracked -}; - - -/* seaw0lf */ -struct picoShader_s -{ - picoModel_t *model; /* owner model */ - - char *name; /* shader name */ - char *mapName; /* shader file name (name of diffuse texturemap) */ - picoColor_t ambientColor; /* ambient color of mesh (rgba) */ - picoColor_t diffuseColor; /* diffuse color of mesh (rgba) */ - picoColor_t specularColor; /* specular color of mesh (rgba) */ - float transparency; /* transparency (0..1; 1 = 100% transparent) */ - float shininess; /* shininess (0..128; 128 = 100% shiny) */ -}; - -struct picoModel_s -{ - void *data; - char *name; /* model name */ - char *fileName; /* sea: model file name */ - int frameNum; /* sea: renamed to frameNum */ - int numFrames; /* sea: number of frames */ - picoVec3_t mins; - picoVec3_t maxs; - - int numShaders, maxShaders; - picoShader_t **shader; - - int numSurfaces, maxSurfaces; - picoSurface_t **surface; - - const picoModule_t *module; /* sea */ -}; - - -/* seaw0lf */ -/* return codes used by the validation callbacks; pmv is short */ -/* for 'pico module validation'. everything >PICO_PMV_OK means */ -/* that there was an error. */ -enum -{ - PICO_PMV_OK, /* file valid */ - PICO_PMV_ERROR, /* file not valid */ - PICO_PMV_ERROR_IDENT, /* unknown file magic (aka ident) */ - PICO_PMV_ERROR_VERSION, /* unsupported file version */ - PICO_PMV_ERROR_SIZE, /* file size error */ - PICO_PMV_ERROR_MEMORY, /* out of memory error */ -}; - -/* convenience (makes it easy to add new params to the callbacks) */ -#define PM_PARAMS_CANLOAD \ - char *fileName, const void *buffer, int bufSize - -#define PM_PARAMS_LOAD \ - char *fileName, int frameNum, const void *buffer, int bufSize - -#define PM_PARAMS_CANSAVE \ - void - -#define PM_PARAMS_SAVE \ - char *fileName, picoModel_t * model - -/* pico file format module structure */ -struct picoModule_s -{ - char *version; /* internal module version (e.g. '1.5-b2') */ - - char *displayName; /* string used to display in guis, etc. */ - char *authorName; /* author name (eg. 'My Real Name') */ - char *copyright; /* copyright year and holder (eg. '2002 My Company') */ - - char *defaultExts[ PICO_MAX_DEFAULT_EXTS ]; /* default file extensions used by this file type */ - int ( *canload )( PM_PARAMS_CANLOAD ); /* checks whether module can load given file (returns PMVR_*) */ - picoModel_t *( *load )( PM_PARAMS_LOAD ); /* parses model file data */ - int ( *cansave )( PM_PARAMS_CANSAVE ); /* checks whether module can save (returns 1 or 0 and might spit out a message) */ - int ( *save )( PM_PARAMS_SAVE ); /* saves a pico model in module's native model format */ -}; - - - -/* general functions */ -int PicoInit( void ); -void PicoShutdown( void ); -int PicoError( void ); - -void PicoSetMallocFunc( void *( *func )( size_t ) ); -void PicoSetFreeFunc( void ( *func )( void* ) ); -void PicoSetLoadFileFunc( void ( *func )( char*, unsigned char**, int* ) ); -void PicoSetFreeFileFunc( void ( *func )( void* ) ); -void PicoSetPrintFunc( void ( *func )( int, const char* ) ); - -const picoModule_t **PicoModuleList( int *numModules ); - -picoModel_t *PicoLoadModel( char *name, int frameNum ); - -typedef size_t ( *PicoInputStreamReadFunc )( void* inputStream, unsigned char* buffer, size_t length ); -picoModel_t* PicoModuleLoadModelStream( const picoModule_t* module, void* inputStream, PicoInputStreamReadFunc inputStreamRead, size_t streamLength, int frameNum ); - -/* model functions */ -picoModel_t *PicoNewModel( void ); -void PicoFreeModel( picoModel_t *model ); -int PicoAdjustModel( picoModel_t *model, int numShaders, int numSurfaces ); - - -/* shader functions */ -picoShader_t *PicoNewShader( picoModel_t *model ); -void PicoFreeShader( picoShader_t *shader ); -picoShader_t *PicoFindShader( picoModel_t *model, char *name, int caseSensitive ); - - -/* surface functions */ -picoSurface_t *PicoNewSurface( picoModel_t *model ); -void PicoFreeSurface( picoSurface_t *surface ); -picoSurface_t *PicoFindSurface( picoModel_t *model, char *name, int caseSensitive ); -int PicoAdjustSurface( picoSurface_t *surface, int numVertexes, int numSTArrays, int numColorArrays, int numIndexes, int numFaceNormals ); - - -/* setter functions */ -void PicoSetModelName( picoModel_t *model, char *name ); -void PicoSetModelFileName( picoModel_t *model, char *fileName ); -void PicoSetModelFrameNum( picoModel_t *model, int frameNum ); -void PicoSetModelNumFrames( picoModel_t *model, int numFrames ); -void PicoSetModelData( picoModel_t *model, void *data ); - -void PicoSetShaderName( picoShader_t *shader, char *name ); -void PicoSetShaderMapName( picoShader_t *shader, char *mapName ); -void PicoSetShaderAmbientColor( picoShader_t *shader, picoColor_t color ); -void PicoSetShaderDiffuseColor( picoShader_t *shader, picoColor_t color ); -void PicoSetShaderSpecularColor( picoShader_t *shader, picoColor_t color ); -void PicoSetShaderTransparency( picoShader_t *shader, float value ); -void PicoSetShaderShininess( picoShader_t *shader, float value ); - -void PicoSetSurfaceData( picoSurface_t *surface, void *data ); -void PicoSetSurfaceType( picoSurface_t *surface, picoSurfaceType_t type ); -void PicoSetSurfaceName( picoSurface_t *surface, char *name ); -void PicoSetSurfaceShader( picoSurface_t *surface, picoShader_t *shader ); -void PicoSetSurfaceXYZ( picoSurface_t *surface, int num, picoVec3_t xyz ); -void PicoSetSurfaceNormal( picoSurface_t *surface, int num, picoVec3_t normal ); -void PicoSetSurfaceST( picoSurface_t *surface, int array, int num, picoVec2_t st ); -void PicoSetSurfaceColor( picoSurface_t *surface, int array, int num, picoColor_t color ); -void PicoSetSurfaceIndex( picoSurface_t *surface, int num, picoIndex_t index ); -void PicoSetSurfaceIndexes( picoSurface_t *surface, int num, picoIndex_t *index, int count ); -void PicoSetFaceNormal( picoSurface_t *surface, int num, picoVec3_t normal ); -void PicoSetSurfaceSpecial( picoSurface_t *surface, int num, int special ); -void PicoSetSurfaceSmoothingGroup( picoSurface_t *surface, int num, picoIndex_t smoothingGroup ); - - -/* getter functions */ -char *PicoGetModelName( picoModel_t *model ); -char *PicoGetModelFileName( picoModel_t *model ); -int PicoGetModelFrameNum( picoModel_t *model ); -int PicoGetModelNumFrames( picoModel_t *model ); -void *PicoGetModelData( picoModel_t *model ); -int PicoGetModelNumShaders( picoModel_t *model ); -picoShader_t *PicoGetModelShader( picoModel_t *model, int num ); /* sea */ -int PicoGetModelNumSurfaces( picoModel_t *model ); -picoSurface_t *PicoGetModelSurface( picoModel_t *model, int num ); -int PicoGetModelTotalVertexes( picoModel_t *model ); -int PicoGetModelTotalIndexes( picoModel_t *model ); - -char *PicoGetShaderName( picoShader_t *shader ); -char *PicoGetShaderMapName( picoShader_t *shader ); -picoByte_t *PicoGetShaderAmbientColor( picoShader_t *shader ); -picoByte_t *PicoGetShaderDiffuseColor( picoShader_t *shader ); -picoByte_t *PicoGetShaderSpecularColor( picoShader_t *shader ); -float PicoGetShaderTransparency( picoShader_t *shader ); -float PicoGetShaderShininess( picoShader_t *shader ); - -void *PicoGetSurfaceData( picoSurface_t *surface ); -char *PicoGetSurfaceName( picoSurface_t *surface ); /* sea */ -picoSurfaceType_t PicoGetSurfaceType( picoSurface_t *surface ); -char *PicoGetSurfaceName( picoSurface_t *surface ); -picoShader_t *PicoGetSurfaceShader( picoSurface_t *surface ); /* sea */ - -int PicoGetSurfaceNumVertexes( picoSurface_t *surface ); -picoVec_t *PicoGetSurfaceXYZ( picoSurface_t *surface, int num ); -picoVec_t *PicoGetSurfaceNormal( picoSurface_t *surface, int num ); -picoVec_t *PicoGetSurfaceST( picoSurface_t *surface, int array, int num ); -picoByte_t *PicoGetSurfaceColor( picoSurface_t *surface, int array, int num ); -int PicoGetSurfaceNumIndexes( picoSurface_t *surface ); -picoIndex_t PicoGetSurfaceIndex( picoSurface_t *surface, int num ); -picoIndex_t *PicoGetSurfaceIndexes( picoSurface_t *surface, int num ); -picoVec_t *PicoGetFaceNormal( picoSurface_t *surface, int num ); -int PicoGetSurfaceSpecial( picoSurface_t *surface, int num ); - - -/* hashtable related functions */ -typedef struct picoVertexCombinationData_s -{ - picoVec3_t xyz, normal; - picoVec2_t st; - picoColor_t color; -} picoVertexCombinationData_t; - -typedef struct picoVertexCombinationHash_s -{ - picoVertexCombinationData_t vcd; - picoIndex_t index; - - void *data; - - struct picoVertexCombinationHash_s *next; -} picoVertexCombinationHash_t; - -int PicoGetHashTableSize( void ); -unsigned int PicoVertexCoordGenerateHash( picoVec3_t xyz ); -picoVertexCombinationHash_t **PicoNewVertexCombinationHashTable( void ); -void PicoFreeVertexCombinationHashTable( picoVertexCombinationHash_t **hashTable ); -picoVertexCombinationHash_t *PicoFindVertexCombinationInHashTable( picoVertexCombinationHash_t **hashTable, picoVec3_t xyz, picoVec3_t normal, picoVec3_t st, picoColor_t color ); -picoVertexCombinationHash_t *PicoAddVertexCombinationToHashTable( picoVertexCombinationHash_t **hashTable, picoVec3_t xyz, picoVec3_t normal, picoVec3_t st, picoColor_t color, picoIndex_t index ); - -/* specialized functions */ -int PicoFindSurfaceVertexNum( picoSurface_t *surface, picoVec3_t xyz, picoVec3_t normal, int numSTs, picoVec2_t *st, int numColors, picoColor_t *color, picoIndex_t smoothingGroup ); -void PicoFixSurfaceNormals( picoSurface_t *surface ); -int PicoRemapModel( picoModel_t *model, char *remapFile ); - - -void PicoAddTriangleToModel( picoModel_t *model, picoVec3_t** xyz, picoVec3_t** normals, int numSTs, picoVec2_t **st, int numColors, picoColor_t **colors, picoShader_t* shader, picoIndex_t* smoothingGroupm, int submodel ); - -/* end marker */ -#ifdef __cplusplus -} -#endif - -#endif diff --git a/tools/urt/libs/picomodel/lwo/clip.c b/tools/urt/libs/picomodel/lwo/clip.c deleted file mode 100644 index 1e68cc1..0000000 --- a/tools/urt/libs/picomodel/lwo/clip.c +++ /dev/null @@ -1,300 +0,0 @@ -/* - ====================================================================== - clip.c - - Functions for LWO2 image references. - - Ernie Wright 17 Sep 00 - ====================================================================== */ - -#include "../picointernal.h" -#include "lwo2.h" - - -/* - ====================================================================== - lwFreeClip() - - Free memory used by an lwClip. - ====================================================================== */ - -void lwFreeClip( lwClip *clip ){ - if ( clip ) { - lwListFree( clip->ifilter, (void *) lwFreePlugin ); - lwListFree( clip->pfilter, (void *) lwFreePlugin ); - - switch ( clip->type ) { - case ID_STIL: - _pico_free( clip->source.still.name ); - break; - - case ID_ISEQ: - _pico_free( clip->source.seq.prefix ); - _pico_free( clip->source.seq.suffix ); - break; - - case ID_ANIM: - _pico_free( clip->source.anim.name ); - _pico_free( clip->source.anim.server ); - _pico_free( clip->source.anim.data ); - break; - - case ID_XREF: - _pico_free( clip->source.xref.string ); - break; - - case ID_STCC: - _pico_free( clip->source.cycle.name ); - break; - - default: - break; - } - - _pico_free( clip ); - } -} - - -/* - ====================================================================== - lwGetClip() - - Read image references from a CLIP chunk in an LWO2 file. - ====================================================================== */ - -lwClip *lwGetClip( picoMemStream_t *fp, int cksize ){ - lwClip *clip; - lwPlugin *filt; - unsigned int id; - unsigned short sz; - int pos, rlen; - - - /* allocate the Clip structure */ - - clip = _pico_calloc( 1, sizeof( lwClip ) ); - if ( !clip ) { - goto Fail; - } - - clip->contrast.val = 1.0f; - clip->brightness.val = 1.0f; - clip->saturation.val = 1.0f; - clip->gamma.val = 1.0f; - - /* remember where we started */ - - set_flen( 0 ); - pos = _pico_memstream_tell( fp ); - - /* index */ - - clip->index = getI4( fp ); - - /* first subchunk header */ - - clip->type = getU4( fp ); - sz = getU2( fp ); - if ( 0 > get_flen() ) { - goto Fail; - } - - sz += sz & 1; - set_flen( 0 ); - - switch ( clip->type ) { - case ID_STIL: - clip->source.still.name = getS0( fp ); - break; - - case ID_ISEQ: - clip->source.seq.digits = getU1( fp ); - clip->source.seq.flags = getU1( fp ); - clip->source.seq.offset = getI2( fp ); - getU2( fp ); /* not sure what this is yet */ - clip->source.seq.start = getI2( fp ); - clip->source.seq.end = getI2( fp ); - clip->source.seq.prefix = getS0( fp ); - clip->source.seq.suffix = getS0( fp ); - break; - - case ID_ANIM: - clip->source.anim.name = getS0( fp ); - clip->source.anim.server = getS0( fp ); - rlen = get_flen(); - clip->source.anim.data = getbytes( fp, sz - rlen ); - break; - - case ID_XREF: - clip->source.xref.index = getI4( fp ); - clip->source.xref.string = getS0( fp ); - break; - - case ID_STCC: - clip->source.cycle.lo = getI2( fp ); - clip->source.cycle.hi = getI2( fp ); - clip->source.cycle.name = getS0( fp ); - break; - - default: - break; - } - - /* error while reading current subchunk? */ - - rlen = get_flen(); - if ( rlen < 0 || rlen > sz ) { - goto Fail; - } - - /* skip unread parts of the current subchunk */ - - if ( rlen < sz ) { - _pico_memstream_seek( fp, sz - rlen, PICO_SEEK_CUR ); - } - - /* end of the CLIP chunk? */ - - rlen = _pico_memstream_tell( fp ) - pos; - if ( cksize < rlen ) { - goto Fail; - } - if ( cksize == rlen ) { - return clip; - } - - /* process subchunks as they're encountered */ - - id = getU4( fp ); - sz = getU2( fp ); - if ( 0 > get_flen() ) { - goto Fail; - } - - while ( 1 ) { - sz += sz & 1; - set_flen( 0 ); - - switch ( id ) { - case ID_TIME: - clip->start_time = getF4( fp ); - clip->duration = getF4( fp ); - clip->frame_rate = getF4( fp ); - break; - - case ID_CONT: - clip->contrast.val = getF4( fp ); - clip->contrast.eindex = getVX( fp ); - break; - - case ID_BRIT: - clip->brightness.val = getF4( fp ); - clip->brightness.eindex = getVX( fp ); - break; - - case ID_SATR: - clip->saturation.val = getF4( fp ); - clip->saturation.eindex = getVX( fp ); - break; - - case ID_HUE: - clip->hue.val = getF4( fp ); - clip->hue.eindex = getVX( fp ); - break; - - case ID_GAMM: - clip->gamma.val = getF4( fp ); - clip->gamma.eindex = getVX( fp ); - break; - - case ID_NEGA: - clip->negative = getU2( fp ); - break; - - case ID_IFLT: - case ID_PFLT: - filt = _pico_calloc( 1, sizeof( lwPlugin ) ); - if ( !filt ) { - goto Fail; - } - - filt->name = getS0( fp ); - filt->flags = getU2( fp ); - rlen = get_flen(); - filt->data = getbytes( fp, sz - rlen ); - - if ( id == ID_IFLT ) { - lwListAdd( (void *) &clip->ifilter, filt ); - clip->nifilters++; - } - else { - lwListAdd( (void *) &clip->pfilter, filt ); - clip->npfilters++; - } - break; - - default: - break; - } - - /* error while reading current subchunk? */ - - rlen = get_flen(); - if ( rlen < 0 || rlen > sz ) { - goto Fail; - } - - /* skip unread parts of the current subchunk */ - - if ( rlen < sz ) { - _pico_memstream_seek( fp, sz - rlen, PICO_SEEK_CUR ); - } - - /* end of the CLIP chunk? */ - - rlen = _pico_memstream_tell( fp ) - pos; - if ( cksize < rlen ) { - goto Fail; - } - if ( cksize == rlen ) { - break; - } - - /* get the next chunk header */ - - set_flen( 0 ); - id = getU4( fp ); - sz = getU2( fp ); - if ( 6 != get_flen() ) { - goto Fail; - } - } - - return clip; - -Fail: - lwFreeClip( clip ); - return NULL; -} - - -/* - ====================================================================== - lwFindClip() - - Returns an lwClip pointer, given a clip index. - ====================================================================== */ - -lwClip *lwFindClip( lwClip *list, int index ){ - lwClip *clip; - - clip = list; - while ( clip ) { - if ( clip->index == index ) { - break; - } - clip = clip->next; - } - return clip; -} diff --git a/tools/urt/libs/picomodel/lwo/envelope.c b/tools/urt/libs/picomodel/lwo/envelope.c deleted file mode 100644 index fbdb4c3..0000000 --- a/tools/urt/libs/picomodel/lwo/envelope.c +++ /dev/null @@ -1,641 +0,0 @@ -/* - ====================================================================== - envelope.c - - Envelope functions for an LWO2 reader. - - Ernie Wright 16 Nov 00 - ====================================================================== */ - -#include "../picointernal.h" -#include "lwo2.h" - -/* - ====================================================================== - lwFreeEnvelope() - - Free the memory used by an lwEnvelope. - ====================================================================== */ - -void lwFreeEnvelope( lwEnvelope *env ){ - if ( env ) { - if ( env->name ) { - _pico_free( env->name ); - } - lwListFree( env->key, _pico_free ); - lwListFree( env->cfilter, (void *) lwFreePlugin ); - _pico_free( env ); - } -} - - -static int compare_keys( lwKey *k1, lwKey *k2 ){ - return k1->time > k2->time ? 1 : k1->time < k2->time ? -1 : 0; -} - - -/* - ====================================================================== - lwGetEnvelope() - - Read an ENVL chunk from an LWO2 file. - ====================================================================== */ - -lwEnvelope *lwGetEnvelope( picoMemStream_t *fp, int cksize ){ - lwEnvelope *env; - lwKey *key; - lwPlugin *plug; - unsigned int id; - unsigned short sz; - float f[ 4 ]; - int i, nparams, pos, rlen; - - - /* allocate the Envelope structure */ - - env = _pico_calloc( 1, sizeof( lwEnvelope ) ); - if ( !env ) { - goto Fail; - } - - /* remember where we started */ - - set_flen( 0 ); - pos = _pico_memstream_tell( fp ); - - /* index */ - - env->index = getVX( fp ); - - /* first subchunk header */ - - id = getU4( fp ); - sz = getU2( fp ); - if ( 0 > get_flen() ) { - goto Fail; - } - - /* process subchunks as they're encountered */ - - while ( 1 ) { - sz += sz & 1; - set_flen( 0 ); - - switch ( id ) { - case ID_TYPE: - env->type = getU2( fp ); - break; - - case ID_NAME: - env->name = getS0( fp ); - break; - - case ID_PRE: - env->behavior[ 0 ] = getU2( fp ); - break; - - case ID_POST: - env->behavior[ 1 ] = getU2( fp ); - break; - - case ID_KEY: - key = _pico_calloc( 1, sizeof( lwKey ) ); - if ( !key ) { - goto Fail; - } - key->time = getF4( fp ); - key->value = getF4( fp ); - lwListInsert( (void **) &env->key, key, (void *) compare_keys ); - env->nkeys++; - break; - - case ID_SPAN: - if ( !key ) { - goto Fail; - } - key->shape = getU4( fp ); - - nparams = ( sz - 4 ) / 4; - if ( nparams > 4 ) { - nparams = 4; - } - for ( i = 0; i < nparams; i++ ) - f[ i ] = getF4( fp ); - - switch ( key->shape ) { - case ID_TCB: - key->tension = f[ 0 ]; - key->continuity = f[ 1 ]; - key->bias = f[ 2 ]; - break; - - case ID_BEZI: - case ID_HERM: - case ID_BEZ2: - for ( i = 0; i < nparams; i++ ) - key->param[ i ] = f[ i ]; - break; - } - break; - - case ID_CHAN: - plug = _pico_calloc( 1, sizeof( lwPlugin ) ); - if ( !plug ) { - goto Fail; - } - - plug->name = getS0( fp ); - plug->flags = getU2( fp ); - plug->data = getbytes( fp, sz - get_flen() ); - - lwListAdd( (void *) &env->cfilter, plug ); - env->ncfilters++; - break; - - default: - break; - } - - /* error while reading current subchunk? */ - - rlen = get_flen(); - if ( rlen < 0 || rlen > sz ) { - goto Fail; - } - - /* skip unread parts of the current subchunk */ - - if ( rlen < sz ) { - _pico_memstream_seek( fp, sz - rlen, PICO_SEEK_CUR ); - } - - /* end of the ENVL chunk? */ - - rlen = _pico_memstream_tell( fp ) - pos; - if ( cksize < rlen ) { - goto Fail; - } - if ( cksize == rlen ) { - break; - } - - /* get the next subchunk header */ - - set_flen( 0 ); - id = getU4( fp ); - sz = getU2( fp ); - if ( 6 != get_flen() ) { - goto Fail; - } - } - - return env; - -Fail: - lwFreeEnvelope( env ); - return NULL; -} - - -/* - ====================================================================== - lwFindEnvelope() - - Returns an lwEnvelope pointer, given an envelope index. - ====================================================================== */ - -lwEnvelope *lwFindEnvelope( lwEnvelope *list, int index ){ - lwEnvelope *env; - - env = list; - while ( env ) { - if ( env->index == index ) { - break; - } - env = env->next; - } - return env; -} - - -/* - ====================================================================== - range() - - Given the value v of a periodic function, returns the equivalent value - v2 in the principal interval [lo, hi]. If i isn't NULL, it receives - the number of wavelengths between v and v2. - - v2 = v - i * (hi - lo) - - For example, range( 3 pi, 0, 2 pi, i ) returns pi, with i = 1. - ====================================================================== */ - -static float range( float v, float lo, float hi, int *i ){ - float v2, r = hi - lo; - - if ( r == 0.0 ) { - if ( i ) { - *i = 0; - } - return lo; - } - - v2 = lo + v - r * ( float ) floor( ( double ) v / r ); - if ( i ) { - *i = -( int )( ( v2 - v ) / r + ( v2 > v ? 0.5 : -0.5 ) ); - } - - return v2; -} - - -/* - ====================================================================== - hermite() - - Calculate the Hermite coefficients. - ====================================================================== */ - -static void hermite( float t, float *h1, float *h2, float *h3, float *h4 ){ - float t2, t3; - - t2 = t * t; - t3 = t * t2; - - *h2 = 3.0f * t2 - t3 - t3; - *h1 = 1.0f - *h2; - *h4 = t3 - t2; - *h3 = *h4 - t2 + t; -} - - -/* - ====================================================================== - bezier() - - Interpolate the value of a 1D Bezier curve. - ====================================================================== */ - -static float bezier( float x0, float x1, float x2, float x3, float t ){ - float a, b, c, t2, t3; - - t2 = t * t; - t3 = t2 * t; - - c = 3.0f * ( x1 - x0 ); - b = 3.0f * ( x2 - x1 ) - c; - a = x3 - x0 - c - b; - - return a * t3 + b * t2 + c * t + x0; -} - - -/* - ====================================================================== - bez2_time() - - Find the t for which bezier() returns the input time. The handle - endpoints of a BEZ2 curve represent the control points, and these have - (time, value) coordinates, so time is used as both a coordinate and a - parameter for this curve type. - ====================================================================== */ - -static float bez2_time( float x0, float x1, float x2, float x3, float time, - float *t0, float *t1 ){ - float v, t; - - t = *t0 + ( *t1 - *t0 ) * 0.5f; - v = bezier( x0, x1, x2, x3, t ); - if ( fabs( time - v ) > .0001f ) { - if ( v > time ) { - *t1 = t; - } - else{ - *t0 = t; - } - return bez2_time( x0, x1, x2, x3, time, t0, t1 ); - } - else{ - return t; - } -} - - -/* - ====================================================================== - bez2() - - Interpolate the value of a BEZ2 curve. - ====================================================================== */ - -static float bez2( lwKey *key0, lwKey *key1, float time ){ - float x, y, t, t0 = 0.0f, t1 = 1.0f; - - if ( key0->shape == ID_BEZ2 ) { - x = key0->time + key0->param[ 2 ]; - } - else{ - x = key0->time + ( key1->time - key0->time ) / 3.0f; - } - - t = bez2_time( key0->time, x, key1->time + key1->param[ 0 ], key1->time, - time, &t0, &t1 ); - - if ( key0->shape == ID_BEZ2 ) { - y = key0->value + key0->param[ 3 ]; - } - else{ - y = key0->value + key0->param[ 1 ] / 3.0f; - } - - return bezier( key0->value, y, key1->param[ 1 ] + key1->value, key1->value, t ); -} - - -/* - ====================================================================== - outgoing() - - Return the outgoing tangent to the curve at key0. The value returned - for the BEZ2 case is used when extrapolating a linear pre behavior and - when interpolating a non-BEZ2 span. - ====================================================================== */ - -static float outgoing( lwKey *key0, lwKey *key1 ){ - float a, b, d, t, out; - - switch ( key0->shape ) - { - case ID_TCB: - a = ( 1.0f - key0->tension ) - * ( 1.0f + key0->continuity ) - * ( 1.0f + key0->bias ); - b = ( 1.0f - key0->tension ) - * ( 1.0f - key0->continuity ) - * ( 1.0f - key0->bias ); - d = key1->value - key0->value; - - if ( key0->prev ) { - t = ( key1->time - key0->time ) / ( key1->time - key0->prev->time ); - out = t * ( a * ( key0->value - key0->prev->value ) + b * d ); - } - else{ - out = b * d; - } - break; - - case ID_LINE: - d = key1->value - key0->value; - if ( key0->prev ) { - t = ( key1->time - key0->time ) / ( key1->time - key0->prev->time ); - out = t * ( key0->value - key0->prev->value + d ); - } - else{ - out = d; - } - break; - - case ID_BEZI: - case ID_HERM: - out = key0->param[ 1 ]; - if ( key0->prev ) { - out *= ( key1->time - key0->time ) / ( key1->time - key0->prev->time ); - } - break; - - case ID_BEZ2: - out = key0->param[ 3 ] * ( key1->time - key0->time ); - if ( fabs( key0->param[ 2 ] ) > 1e-5f ) { - out /= key0->param[ 2 ]; - } - else{ - out *= 1e5f; - } - break; - - case ID_STEP: - default: - out = 0.0f; - break; - } - - return out; -} - - -/* - ====================================================================== - incoming() - - Return the incoming tangent to the curve at key1. The value returned - for the BEZ2 case is used when extrapolating a linear post behavior. - ====================================================================== */ - -static float incoming( lwKey *key0, lwKey *key1 ){ - float a, b, d, t, in; - - switch ( key1->shape ) - { - case ID_LINE: - d = key1->value - key0->value; - if ( key1->next ) { - t = ( key1->time - key0->time ) / ( key1->next->time - key0->time ); - in = t * ( key1->next->value - key1->value + d ); - } - else{ - in = d; - } - break; - - case ID_TCB: - a = ( 1.0f - key1->tension ) - * ( 1.0f - key1->continuity ) - * ( 1.0f + key1->bias ); - b = ( 1.0f - key1->tension ) - * ( 1.0f + key1->continuity ) - * ( 1.0f - key1->bias ); - d = key1->value - key0->value; - - if ( key1->next ) { - t = ( key1->time - key0->time ) / ( key1->next->time - key0->time ); - in = t * ( b * ( key1->next->value - key1->value ) + a * d ); - } - else{ - in = a * d; - } - break; - - case ID_BEZI: - case ID_HERM: - in = key1->param[ 0 ]; - if ( key1->next ) { - in *= ( key1->time - key0->time ) / ( key1->next->time - key0->time ); - } - break; - return in; - - case ID_BEZ2: - in = key1->param[ 1 ] * ( key1->time - key0->time ); - if ( fabs( key1->param[ 0 ] ) > 1e-5f ) { - in /= key1->param[ 0 ]; - } - else{ - in *= 1e5f; - } - break; - - case ID_STEP: - default: - in = 0.0f; - break; - } - - return in; -} - - -/* - ====================================================================== - evalEnvelope() - - Given a list of keys and a time, returns the interpolated value of the - envelope at that time. - ====================================================================== */ - -float evalEnvelope( lwEnvelope *env, float time ){ - lwKey *key0, *key1, *skey, *ekey; - float t, h1, h2, h3, h4, in, out, offset = 0.0f; - int noff; - - - /* if there's no key, the value is 0 */ - - if ( env->nkeys == 0 ) { - return 0.0f; - } - - /* if there's only one key, the value is constant */ - - if ( env->nkeys == 1 ) { - return env->key->value; - } - - /* find the first and last keys */ - - skey = ekey = env->key; - while ( ekey->next ) ekey = ekey->next; - - /* use pre-behavior if time is before first key time */ - - if ( time < skey->time ) { - switch ( env->behavior[ 0 ] ) - { - case BEH_RESET: - return 0.0f; - - case BEH_CONSTANT: - return skey->value; - - case BEH_REPEAT: - time = range( time, skey->time, ekey->time, NULL ); - break; - - case BEH_OSCILLATE: - time = range( time, skey->time, ekey->time, &noff ); - if ( noff % 2 ) { - time = ekey->time - skey->time - time; - } - break; - - case BEH_OFFSET: - time = range( time, skey->time, ekey->time, &noff ); - offset = noff * ( ekey->value - skey->value ); - break; - - case BEH_LINEAR: - out = outgoing( skey, skey->next ) - / ( skey->next->time - skey->time ); - return out * ( time - skey->time ) + skey->value; - } - } - - /* use post-behavior if time is after last key time */ - - else if ( time > ekey->time ) { - switch ( env->behavior[ 1 ] ) - { - case BEH_RESET: - return 0.0f; - - case BEH_CONSTANT: - return ekey->value; - - case BEH_REPEAT: - time = range( time, skey->time, ekey->time, NULL ); - break; - - case BEH_OSCILLATE: - time = range( time, skey->time, ekey->time, &noff ); - if ( noff % 2 ) { - time = ekey->time - skey->time - time; - } - break; - - case BEH_OFFSET: - time = range( time, skey->time, ekey->time, &noff ); - offset = noff * ( ekey->value - skey->value ); - break; - - case BEH_LINEAR: - in = incoming( ekey->prev, ekey ) - / ( ekey->time - ekey->prev->time ); - return in * ( time - ekey->time ) + ekey->value; - } - } - - /* get the endpoints of the interval being evaluated */ - - key0 = env->key; - while ( time > key0->next->time ) - key0 = key0->next; - key1 = key0->next; - - /* check for singularities first */ - - if ( time == key0->time ) { - return key0->value + offset; - } - else if ( time == key1->time ) { - return key1->value + offset; - } - - /* get interval length, time in [0, 1] */ - - t = ( time - key0->time ) / ( key1->time - key0->time ); - - /* interpolate */ - - switch ( key1->shape ) - { - case ID_TCB: - case ID_BEZI: - case ID_HERM: - out = outgoing( key0, key1 ); - in = incoming( key0, key1 ); - hermite( t, &h1, &h2, &h3, &h4 ); - return h1 * key0->value + h2 * key1->value + h3 * out + h4 * in + offset; - - case ID_BEZ2: - return bez2( key0, key1, time ) + offset; - - case ID_LINE: - return key0->value + t * ( key1->value - key0->value ) + offset; - - case ID_STEP: - return key0->value + offset; - - default: - return offset; - } -} diff --git a/tools/urt/libs/picomodel/lwo/libs_rar.rar b/tools/urt/libs/picomodel/lwo/libs_rar.rar deleted file mode 100644 index 6421f5c..0000000 Binary files a/tools/urt/libs/picomodel/lwo/libs_rar.rar and /dev/null differ diff --git a/tools/urt/libs/picomodel/lwo/list.c b/tools/urt/libs/picomodel/lwo/list.c deleted file mode 100644 index d57547d..0000000 --- a/tools/urt/libs/picomodel/lwo/list.c +++ /dev/null @@ -1,100 +0,0 @@ -/* - ====================================================================== - list.c - - Generic linked list operations. - - Ernie Wright 17 Sep 00 - ====================================================================== */ - -#include "../picointernal.h" -#include "lwo2.h" - - -/* - ====================================================================== - lwListFree() - - Free the items in a list. - ====================================================================== */ - -void lwListFree( void *list, void ( *freeNode )( void * ) ){ - lwNode *node, *next; - - node = ( lwNode * ) list; - while ( node ) { - next = node->next; - freeNode( node ); - node = next; - } -} - - -/* - ====================================================================== - lwListAdd() - - Append a node to a list. - ====================================================================== */ - -void lwListAdd( void **list, void *node ){ - lwNode *head, *tail; - - head = *( ( lwNode ** ) list ); - if ( !head ) { - *list = node; - return; - } - while ( head ) { - tail = head; - head = head->next; - } - tail->next = ( lwNode * ) node; - ( ( lwNode * ) node )->prev = tail; -} - - -/* - ====================================================================== - lwListInsert() - - Insert a node into a list in sorted order. - ====================================================================== */ - -void lwListInsert( void **vlist, void *vitem, int ( *compare )( void *, void * ) ){ - lwNode **list, *item, *node, *prev; - - if ( !*vlist ) { - *vlist = vitem; - return; - } - - list = ( lwNode ** ) vlist; - item = ( lwNode * ) vitem; - node = *list; - prev = NULL; - - while ( node ) { - if ( 0 < compare( node, item ) ) { - break; - } - prev = node; - node = node->next; - } - - if ( !prev ) { - *list = item; - node->prev = item; - item->next = node; - } - else if ( !node ) { - prev->next = item; - item->prev = prev; - } - else { - item->next = node; - item->prev = prev; - prev->next = item; - node->prev = item; - } -} diff --git a/tools/urt/libs/picomodel/lwo/lwio.c b/tools/urt/libs/picomodel/lwo/lwio.c deleted file mode 100644 index b1981b3..0000000 --- a/tools/urt/libs/picomodel/lwo/lwio.c +++ /dev/null @@ -1,471 +0,0 @@ -/* - ====================================================================== - lwio.c - - Functions for reading basic LWO2 data types. - - Ernie Wright 17 Sep 00 - ====================================================================== */ - -#include "../picointernal.h" -#include "lwo2.h" - - -/* - ====================================================================== - flen - - This accumulates a count of the number of bytes read. Callers can set - it at the beginning of a sequence of reads and then retrieve it to get - the number of bytes actually read. If one of the I/O functions fails, - flen is set to an error code, after which the I/O functions ignore - read requests until flen is reset. - ====================================================================== */ - -#define INT_MIN ( -2147483647 - 1 ) /* minimum (signed) int value */ -#define FLEN_ERROR INT_MIN - -static int flen; - -void set_flen( int i ) { flen = i; } - -int get_flen( void ) { return flen; } - - -#ifndef __BIG_ENDIAN__ -/* - ===================================================================== - revbytes() - - Reverses byte order in place. - - INPUTS - bp bytes to reverse - elsize size of the underlying data type - elcount number of elements to swap - - RESULTS - Reverses the byte order in each of elcount elements. - - This only needs to be defined on little-endian platforms, most - notably Windows. lwo2.h replaces this with a #define on big-endian - platforms. - ===================================================================== */ - -void revbytes( void *bp, int elsize, int elcount ){ - register unsigned char *p, *q; - - p = ( unsigned char * ) bp; - - if ( elsize == 2 ) { - q = p + 1; - while ( elcount-- ) { - *p ^= *q; - *q ^= *p; - *p ^= *q; - p += 2; - q += 2; - } - return; - } - - while ( elcount-- ) { - q = p + elsize - 1; - while ( p < q ) { - *p ^= *q; - *q ^= *p; - *p ^= *q; - ++p; - --q; - } - p += elsize >> 1; - } -} -#endif - - -void *getbytes( picoMemStream_t *fp, int size ){ - void *data; - - if ( flen == FLEN_ERROR ) { - return NULL; - } - if ( size < 0 ) { - flen = FLEN_ERROR; - return NULL; - } - data = _pico_alloc( size ); - if ( !data ) { - flen = FLEN_ERROR; - return NULL; - } - if ( 1 != _pico_memstream_read( fp, data, size ) ) { - flen = FLEN_ERROR; - _pico_free( data ); - return NULL; - } - - flen += size; - return data; -} - - -void skipbytes( picoMemStream_t *fp, int n ){ - if ( flen == FLEN_ERROR ) { - return; - } - if ( _pico_memstream_seek( fp, n, PICO_SEEK_CUR ) ) { - flen = FLEN_ERROR; - } - else{ - flen += n; - } -} - - -int getI1( picoMemStream_t *fp ){ - int i; - - if ( flen == FLEN_ERROR ) { - return 0; - } - i = _pico_memstream_getc( fp ); - if ( i < 0 ) { - flen = FLEN_ERROR; - return 0; - } - if ( i > 127 ) { - i -= 256; - } - flen += 1; - return i; -} - - -short getI2( picoMemStream_t *fp ){ - short i; - - if ( flen == FLEN_ERROR ) { - return 0; - } - if ( 1 != _pico_memstream_read( fp, &i, 2 ) ) { - flen = FLEN_ERROR; - return 0; - } - revbytes( &i, 2, 1 ); - flen += 2; - return i; -} - - -int getI4( picoMemStream_t *fp ){ - int i; - - if ( flen == FLEN_ERROR ) { - return 0; - } - if ( 1 != _pico_memstream_read( fp, &i, 4 ) ) { - flen = FLEN_ERROR; - return 0; - } - revbytes( &i, 4, 1 ); - flen += 4; - return i; -} - - -unsigned char getU1( picoMemStream_t *fp ){ - int i; - - if ( flen == FLEN_ERROR ) { - return 0; - } - i = _pico_memstream_getc( fp ); - if ( i < 0 ) { - flen = FLEN_ERROR; - return 0; - } - flen += 1; - return i; -} - - -unsigned short getU2( picoMemStream_t *fp ){ - unsigned short i; - - if ( flen == FLEN_ERROR ) { - return 0; - } - if ( 1 != _pico_memstream_read( fp, &i, 2 ) ) { - flen = FLEN_ERROR; - return 0; - } - revbytes( &i, 2, 1 ); - flen += 2; - return i; -} - - -unsigned int getU4( picoMemStream_t *fp ){ - unsigned int i; - - if ( flen == FLEN_ERROR ) { - return 0; - } - if ( 1 != _pico_memstream_read( fp, &i, 4 ) ) { - flen = FLEN_ERROR; - return 0; - } - revbytes( &i, 4, 1 ); - flen += 4; - return i; -} - - -int getVX( picoMemStream_t *fp ){ - int i, c; - - if ( flen == FLEN_ERROR ) { - return 0; - } - - c = _pico_memstream_getc( fp ); - if ( c != 0xFF ) { - i = c << 8; - c = _pico_memstream_getc( fp ); - i |= c; - flen += 2; - } - else { - c = _pico_memstream_getc( fp ); - i = c << 16; - c = _pico_memstream_getc( fp ); - i |= c << 8; - c = _pico_memstream_getc( fp ); - i |= c; - flen += 4; - } - - if ( _pico_memstream_error( fp ) ) { - flen = FLEN_ERROR; - return 0; - } - return i; -} - - -float getF4( picoMemStream_t *fp ){ - float f; - - if ( flen == FLEN_ERROR ) { - return 0.0f; - } - if ( 1 != _pico_memstream_read( fp, &f, 4 ) ) { - flen = FLEN_ERROR; - return 0.0f; - } - revbytes( &f, 4, 1 ); - flen += 4; - return f; -} - - -char *getS0( picoMemStream_t *fp ){ - char *s; - int i, c, len, pos; - - if ( flen == FLEN_ERROR ) { - return NULL; - } - - pos = _pico_memstream_tell( fp ); - for ( i = 1; ; i++ ) { - c = _pico_memstream_getc( fp ); - if ( c <= 0 ) { - break; - } - } - if ( c < 0 ) { - flen = FLEN_ERROR; - return NULL; - } - - if ( i == 1 ) { - if ( _pico_memstream_seek( fp, pos + 2, PICO_SEEK_SET ) ) { - flen = FLEN_ERROR; - } - else{ - flen += 2; - } - return NULL; - } - - len = i + ( i & 1 ); - s = _pico_alloc( len ); - if ( !s ) { - flen = FLEN_ERROR; - return NULL; - } - - if ( _pico_memstream_seek( fp, pos, PICO_SEEK_SET ) ) { - flen = FLEN_ERROR; - return NULL; - } - if ( 1 != _pico_memstream_read( fp, s, len ) ) { - flen = FLEN_ERROR; - return NULL; - } - - flen += len; - return s; -} - - -int sgetI1( unsigned char **bp ){ - int i; - - if ( flen == FLEN_ERROR ) { - return 0; - } - i = **bp; - if ( i > 127 ) { - i -= 256; - } - flen += 1; - *bp++; - return i; -} - - -short sgetI2( unsigned char **bp ){ - short i; - - if ( flen == FLEN_ERROR ) { - return 0; - } - memcpy( &i, *bp, 2 ); - revbytes( &i, 2, 1 ); - flen += 2; - *bp += 2; - return i; -} - - -int sgetI4( unsigned char **bp ){ - int i; - - if ( flen == FLEN_ERROR ) { - return 0; - } - memcpy( &i, *bp, 4 ); - revbytes( &i, 4, 1 ); - flen += 4; - *bp += 4; - return i; -} - - -unsigned char sgetU1( unsigned char **bp ){ - unsigned char c; - - if ( flen == FLEN_ERROR ) { - return 0; - } - c = **bp; - flen += 1; - *bp++; - return c; -} - - -unsigned short sgetU2( unsigned char **bp ){ - unsigned char *buf = *bp; - unsigned short i; - - if ( flen == FLEN_ERROR ) { - return 0; - } - i = ( buf[ 0 ] << 8 ) | buf[ 1 ]; - flen += 2; - *bp += 2; - return i; -} - - -unsigned int sgetU4( unsigned char **bp ){ - unsigned int i; - - if ( flen == FLEN_ERROR ) { - return 0; - } - memcpy( &i, *bp, 4 ); - revbytes( &i, 4, 1 ); - flen += 4; - *bp += 4; - return i; -} - - -int sgetVX( unsigned char **bp ){ - unsigned char *buf = *bp; - int i; - - if ( flen == FLEN_ERROR ) { - return 0; - } - - if ( buf[ 0 ] != 0xFF ) { - i = buf[ 0 ] << 8 | buf[ 1 ]; - flen += 2; - *bp += 2; - } - else { - i = ( buf[ 1 ] << 16 ) | ( buf[ 2 ] << 8 ) | buf[ 3 ]; - flen += 4; - *bp += 4; - } - return i; -} - - -float sgetF4( unsigned char **bp ){ - float f; - - if ( flen == FLEN_ERROR ) { - return 0.0f; - } - memcpy( &f, *bp, 4 ); - revbytes( &f, 4, 1 ); - flen += 4; - *bp += 4; - return f; -} - - -char *sgetS0( unsigned char **bp ){ - char *s; - unsigned char *buf = *bp; - int len; - - if ( flen == FLEN_ERROR ) { - return NULL; - } - - len = strlen( buf ) + 1; - if ( len == 1 ) { - flen += 2; - *bp += 2; - return NULL; - } - len += len & 1; - s = _pico_alloc( len ); - if ( !s ) { - flen = FLEN_ERROR; - return NULL; - } - - memcpy( s, buf, len ); - flen += len; - *bp += len; - return s; -} diff --git a/tools/urt/libs/picomodel/lwo/lwo2.c b/tools/urt/libs/picomodel/lwo/lwo2.c deleted file mode 100644 index 4c6e771..0000000 --- a/tools/urt/libs/picomodel/lwo/lwo2.c +++ /dev/null @@ -1,364 +0,0 @@ -/* - ====================================================================== - lwo2.c - - The entry point for loading LightWave object files. - - Ernie Wright 17 Sep 00 - ====================================================================== */ - -#include "../picointernal.h" -#include "lwo2.h" - -/* disable warnings */ -#ifdef WIN32 -#pragma warning( disable:4018 ) /* signed/unsigned mismatch */ -#endif - - -/* - ====================================================================== - lwFreeLayer() - - Free memory used by an lwLayer. - ====================================================================== */ - -void lwFreeLayer( lwLayer *layer ){ - if ( layer ) { - if ( layer->name ) { - _pico_free( layer->name ); - } - lwFreePoints( &layer->point ); - lwFreePolygons( &layer->polygon ); - lwListFree( layer->vmap, (void *) lwFreeVMap ); - _pico_free( layer ); - } -} - - -/* - ====================================================================== - lwFreeObject() - - Free memory used by an lwObject. - ====================================================================== */ - -void lwFreeObject( lwObject *object ){ - if ( object ) { - lwListFree( object->layer, (void *) lwFreeLayer ); - lwListFree( object->env, (void *) lwFreeEnvelope ); - lwListFree( object->clip, (void *) lwFreeClip ); - lwListFree( object->surf, (void *) lwFreeSurface ); - lwFreeTags( &object->taglist ); - _pico_free( object ); - } -} - - -/* - ====================================================================== - lwGetObject() - - Returns the contents of a LightWave object, given its filename, or - NULL if the file couldn't be loaded. On failure, failID and failpos - can be used to diagnose the cause. - - 1. If the file isn't an LWO2 or an LWOB, failpos will contain 12 and - failID will be unchanged. - - 2. If an error occurs while reading, failID will contain the most - recently read IFF chunk ID, and failpos will contain the value - returned by _pico_memstream_tell() at the time of the failure. - - 3. If the file couldn't be opened, or an error occurs while reading - the first 12 bytes, both failID and failpos will be unchanged. - - If you don't need this information, failID and failpos can be NULL. - ====================================================================== */ - -lwObject *lwGetObject( char *filename, picoMemStream_t *fp, unsigned int *failID, int *failpos ){ - lwObject *object; - lwLayer *layer; - lwNode *node; - unsigned int id, formsize, type, cksize; - int i, rlen; - - /* open the file */ - - if ( !fp ) { - return NULL; - } - - /* read the first 12 bytes */ - - set_flen( 0 ); - id = getU4( fp ); - formsize = getU4( fp ); - type = getU4( fp ); - if ( 12 != get_flen() ) { - return NULL; - } - - /* is this a LW object? */ - - if ( id != ID_FORM ) { - if ( failpos ) { - *failpos = 12; - } - return NULL; - } - - if ( type != ID_LWO2 ) { - if ( type == ID_LWOB ) { - return lwGetObject5( filename, fp, failID, failpos ); - } - else { - if ( failpos ) { - *failpos = 12; - } - return NULL; - } - } - - /* allocate an object and a default layer */ - - object = _pico_calloc( 1, sizeof( lwObject ) ); - if ( !object ) { - goto Fail; - } - - layer = _pico_calloc( 1, sizeof( lwLayer ) ); - if ( !layer ) { - goto Fail; - } - object->layer = layer; - - /* get the first chunk header */ - - id = getU4( fp ); - cksize = getU4( fp ); - if ( 0 > get_flen() ) { - goto Fail; - } - - /* process chunks as they're encountered */ - - while ( 1 ) { - cksize += cksize & 1; - - switch ( id ) - { - case ID_LAYR: - if ( object->nlayers > 0 ) { - layer = _pico_calloc( 1, sizeof( lwLayer ) ); - if ( !layer ) { - goto Fail; - } - lwListAdd( (void **) &object->layer, layer ); - } - object->nlayers++; - - set_flen( 0 ); - layer->index = getU2( fp ); - layer->flags = getU2( fp ); - layer->pivot[ 0 ] = getF4( fp ); - layer->pivot[ 1 ] = getF4( fp ); - layer->pivot[ 2 ] = getF4( fp ); - layer->name = getS0( fp ); - - rlen = get_flen(); - if ( rlen < 0 || rlen > cksize ) { - goto Fail; - } - if ( rlen <= cksize - 2 ) { - layer->parent = getU2( fp ); - } - rlen = get_flen(); - if ( rlen < cksize ) { - _pico_memstream_seek( fp, cksize - rlen, PICO_SEEK_CUR ); - } - break; - - case ID_PNTS: - if ( !lwGetPoints( fp, cksize, &layer->point ) ) { - goto Fail; - } - break; - - case ID_POLS: - if ( !lwGetPolygons( fp, cksize, &layer->polygon, - layer->point.offset ) ) { - goto Fail; - } - break; - - case ID_VMAP: - case ID_VMAD: - node = ( lwNode * ) lwGetVMap( fp, cksize, layer->point.offset, - layer->polygon.offset, id == ID_VMAD ); - if ( !node ) { - goto Fail; - } - lwListAdd( (void **) &layer->vmap, node ); - layer->nvmaps++; - break; - - case ID_PTAG: - if ( !lwGetPolygonTags( fp, cksize, &object->taglist, - &layer->polygon ) ) { - goto Fail; - } - break; - - case ID_BBOX: - set_flen( 0 ); - for ( i = 0; i < 6; i++ ) - layer->bbox[ i ] = getF4( fp ); - rlen = get_flen(); - if ( rlen < 0 || rlen > cksize ) { - goto Fail; - } - if ( rlen < cksize ) { - _pico_memstream_seek( fp, cksize - rlen, PICO_SEEK_CUR ); - } - break; - - case ID_TAGS: - if ( !lwGetTags( fp, cksize, &object->taglist ) ) { - goto Fail; - } - break; - - case ID_ENVL: - node = ( lwNode * ) lwGetEnvelope( fp, cksize ); - if ( !node ) { - goto Fail; - } - lwListAdd( (void **) &object->env, node ); - object->nenvs++; - break; - - case ID_CLIP: - node = ( lwNode * ) lwGetClip( fp, cksize ); - if ( !node ) { - goto Fail; - } - lwListAdd( (void **) &object->clip, node ); - object->nclips++; - break; - - case ID_SURF: - node = ( lwNode * ) lwGetSurface( fp, cksize ); - if ( !node ) { - goto Fail; - } - lwListAdd( (void **) &object->surf, node ); - object->nsurfs++; - break; - - case ID_DESC: - case ID_TEXT: - case ID_ICON: - default: - _pico_memstream_seek( fp, cksize, PICO_SEEK_CUR ); - break; - } - - /* end of the file? */ - - if ( formsize <= _pico_memstream_tell( fp ) - 8 ) { - break; - } - - /* get the next chunk header */ - - set_flen( 0 ); - id = getU4( fp ); - cksize = getU4( fp ); - if ( 8 != get_flen() ) { - goto Fail; - } - } - - if ( object->nlayers == 0 ) { - object->nlayers = 1; - } - - layer = object->layer; - while ( layer ) { - lwGetBoundingBox( &layer->point, layer->bbox ); - lwGetPolyNormals( &layer->point, &layer->polygon ); - if ( !lwGetPointPolygons( &layer->point, &layer->polygon ) ) { - goto Fail; - } - if ( !lwResolvePolySurfaces( &layer->polygon, &object->taglist, - &object->surf, &object->nsurfs ) ) { - goto Fail; - } - lwGetVertNormals( &layer->point, &layer->polygon ); - if ( !lwGetPointVMaps( &layer->point, layer->vmap ) ) { - goto Fail; - } - if ( !lwGetPolyVMaps( &layer->polygon, layer->vmap ) ) { - goto Fail; - } - layer = layer->next; - } - - return object; - -Fail: - if ( failID ) { - *failID = id; - } - if ( fp ) { - if ( failpos ) { - *failpos = _pico_memstream_tell( fp ); - } - } - lwFreeObject( object ); - return NULL; -} - -int lwValidateObject( char *filename, picoMemStream_t *fp, unsigned int *failID, int *failpos ){ - unsigned int id, formsize, type; - - /* open the file */ - - if ( !fp ) { - return PICO_PMV_ERROR_MEMORY; - } - - /* read the first 12 bytes */ - - set_flen( 0 ); - id = getU4( fp ); - formsize = getU4( fp ); - type = getU4( fp ); - if ( 12 != get_flen() ) { - return PICO_PMV_ERROR_SIZE; - } - - /* is this a LW object? */ - - if ( id != ID_FORM ) { - if ( failpos ) { - *failpos = 12; - } - return PICO_PMV_ERROR_SIZE; - } - - if ( type != ID_LWO2 ) { - if ( type == ID_LWOB ) { - return lwValidateObject5( filename, fp, failID, failpos ); - } - else { - if ( failpos ) { - *failpos = 12; - } - return PICO_PMV_ERROR_IDENT; - } - } - - return PICO_PMV_OK; -} diff --git a/tools/urt/libs/picomodel/lwo/lwo2.h b/tools/urt/libs/picomodel/lwo/lwo2.h deleted file mode 100644 index 6971366..0000000 --- a/tools/urt/libs/picomodel/lwo/lwo2.h +++ /dev/null @@ -1,651 +0,0 @@ -/* - ====================================================================== - lwo2.h - - Definitions and typedefs for LWO2 files. - - Ernie Wright 17 Sep 00 - ====================================================================== */ - -#ifndef LWO2_H -#define LWO2_H - -/* chunk and subchunk IDs */ - -#define LWID_( a,b,c,d ) ( ( ( a ) << 24 ) | ( ( b ) << 16 ) | ( ( c ) << 8 ) | ( d ) ) - -#define ID_FORM LWID_( 'F','O','R','M' ) -#define ID_LWO2 LWID_( 'L','W','O','2' ) -#define ID_LWOB LWID_( 'L','W','O','B' ) - -/* top-level chunks */ -#define ID_LAYR LWID_( 'L','A','Y','R' ) -#define ID_TAGS LWID_( 'T','A','G','S' ) -#define ID_PNTS LWID_( 'P','N','T','S' ) -#define ID_BBOX LWID_( 'B','B','O','X' ) -#define ID_VMAP LWID_( 'V','M','A','P' ) -#define ID_VMAD LWID_( 'V','M','A','D' ) -#define ID_POLS LWID_( 'P','O','L','S' ) -#define ID_PTAG LWID_( 'P','T','A','G' ) -#define ID_ENVL LWID_( 'E','N','V','L' ) -#define ID_CLIP LWID_( 'C','L','I','P' ) -#define ID_SURF LWID_( 'S','U','R','F' ) -#define ID_DESC LWID_( 'D','E','S','C' ) -#define ID_TEXT LWID_( 'T','E','X','T' ) -#define ID_ICON LWID_( 'I','C','O','N' ) - -/* polygon types */ -#define ID_FACE LWID_( 'F','A','C','E' ) -#define ID_CURV LWID_( 'C','U','R','V' ) -#define ID_PTCH LWID_( 'P','T','C','H' ) -#define ID_MBAL LWID_( 'M','B','A','L' ) -#define ID_BONE LWID_( 'B','O','N','E' ) - -/* polygon tags */ -#define ID_SURF LWID_( 'S','U','R','F' ) -#define ID_PART LWID_( 'P','A','R','T' ) -#define ID_SMGP LWID_( 'S','M','G','P' ) - -/* envelopes */ -#define ID_PRE LWID_( 'P','R','E',' ' ) -#define ID_POST LWID_( 'P','O','S','T' ) -#define ID_KEY LWID_( 'K','E','Y',' ' ) -#define ID_SPAN LWID_( 'S','P','A','N' ) -#define ID_TCB LWID_( 'T','C','B',' ' ) -#define ID_HERM LWID_( 'H','E','R','M' ) -#define ID_BEZI LWID_( 'B','E','Z','I' ) -#define ID_BEZ2 LWID_( 'B','E','Z','2' ) -#define ID_LINE LWID_( 'L','I','N','E' ) -#define ID_STEP LWID_( 'S','T','E','P' ) - -/* clips */ -#define ID_STIL LWID_( 'S','T','I','L' ) -#define ID_ISEQ LWID_( 'I','S','E','Q' ) -#define ID_ANIM LWID_( 'A','N','I','M' ) -#define ID_XREF LWID_( 'X','R','E','F' ) -#define ID_STCC LWID_( 'S','T','C','C' ) -#define ID_TIME LWID_( 'T','I','M','E' ) -#define ID_CONT LWID_( 'C','O','N','T' ) -#define ID_BRIT LWID_( 'B','R','I','T' ) -#define ID_SATR LWID_( 'S','A','T','R' ) -#define ID_HUE LWID_( 'H','U','E',' ' ) -#define ID_GAMM LWID_( 'G','A','M','M' ) -#define ID_NEGA LWID_( 'N','E','G','A' ) -#define ID_IFLT LWID_( 'I','F','L','T' ) -#define ID_PFLT LWID_( 'P','F','L','T' ) - -/* surfaces */ -#define ID_COLR LWID_( 'C','O','L','R' ) -#define ID_LUMI LWID_( 'L','U','M','I' ) -#define ID_DIFF LWID_( 'D','I','F','F' ) -#define ID_SPEC LWID_( 'S','P','E','C' ) -#define ID_GLOS LWID_( 'G','L','O','S' ) -#define ID_REFL LWID_( 'R','E','F','L' ) -#define ID_RFOP LWID_( 'R','F','O','P' ) -#define ID_RIMG LWID_( 'R','I','M','G' ) -#define ID_RSAN LWID_( 'R','S','A','N' ) -#define ID_TRAN LWID_( 'T','R','A','N' ) -#define ID_TROP LWID_( 'T','R','O','P' ) -#define ID_TIMG LWID_( 'T','I','M','G' ) -#define ID_RIND LWID_( 'R','I','N','D' ) -#define ID_TRNL LWID_( 'T','R','N','L' ) -#define ID_BUMP LWID_( 'B','U','M','P' ) -#define ID_SMAN LWID_( 'S','M','A','N' ) -#define ID_SIDE LWID_( 'S','I','D','E' ) -#define ID_CLRH LWID_( 'C','L','R','H' ) -#define ID_CLRF LWID_( 'C','L','R','F' ) -#define ID_ADTR LWID_( 'A','D','T','R' ) -#define ID_SHRP LWID_( 'S','H','R','P' ) -#define ID_LINE LWID_( 'L','I','N','E' ) -#define ID_LSIZ LWID_( 'L','S','I','Z' ) -#define ID_ALPH LWID_( 'A','L','P','H' ) -#define ID_AVAL LWID_( 'A','V','A','L' ) -#define ID_GVAL LWID_( 'G','V','A','L' ) -#define ID_BLOK LWID_( 'B','L','O','K' ) - -/* texture layer */ -#define ID_TYPE LWID_( 'T','Y','P','E' ) -#define ID_CHAN LWID_( 'C','H','A','N' ) -#define ID_NAME LWID_( 'N','A','M','E' ) -#define ID_ENAB LWID_( 'E','N','A','B' ) -#define ID_OPAC LWID_( 'O','P','A','C' ) -#define ID_FLAG LWID_( 'F','L','A','G' ) -#define ID_PROJ LWID_( 'P','R','O','J' ) -#define ID_STCK LWID_( 'S','T','C','K' ) -#define ID_TAMP LWID_( 'T','A','M','P' ) - -/* texture coordinates */ -#define ID_TMAP LWID_( 'T','M','A','P' ) -#define ID_AXIS LWID_( 'A','X','I','S' ) -#define ID_CNTR LWID_( 'C','N','T','R' ) -#define ID_SIZE LWID_( 'S','I','Z','E' ) -#define ID_ROTA LWID_( 'R','O','T','A' ) -#define ID_OREF LWID_( 'O','R','E','F' ) -#define ID_FALL LWID_( 'F','A','L','L' ) -#define ID_CSYS LWID_( 'C','S','Y','S' ) - -/* image map */ -#define ID_IMAP LWID_( 'I','M','A','P' ) -#define ID_IMAG LWID_( 'I','M','A','G' ) -#define ID_WRAP LWID_( 'W','R','A','P' ) -#define ID_WRPW LWID_( 'W','R','P','W' ) -#define ID_WRPH LWID_( 'W','R','P','H' ) -#define ID_VMAP LWID_( 'V','M','A','P' ) -#define ID_AAST LWID_( 'A','A','S','T' ) -#define ID_PIXB LWID_( 'P','I','X','B' ) - -/* procedural */ -#define ID_PROC LWID_( 'P','R','O','C' ) -#define ID_COLR LWID_( 'C','O','L','R' ) -#define ID_VALU LWID_( 'V','A','L','U' ) -#define ID_FUNC LWID_( 'F','U','N','C' ) -#define ID_FTPS LWID_( 'F','T','P','S' ) -#define ID_ITPS LWID_( 'I','T','P','S' ) -#define ID_ETPS LWID_( 'E','T','P','S' ) - -/* gradient */ -#define ID_GRAD LWID_( 'G','R','A','D' ) -#define ID_GRST LWID_( 'G','R','S','T' ) -#define ID_GREN LWID_( 'G','R','E','N' ) -#define ID_PNAM LWID_( 'P','N','A','M' ) -#define ID_INAM LWID_( 'I','N','A','M' ) -#define ID_GRPT LWID_( 'G','R','P','T' ) -#define ID_FKEY LWID_( 'F','K','E','Y' ) -#define ID_IKEY LWID_( 'I','K','E','Y' ) - -/* shader */ -#define ID_SHDR LWID_( 'S','H','D','R' ) -#define ID_DATA LWID_( 'D','A','T','A' ) - - -/* generic linked list */ - -typedef struct st_lwNode { - struct st_lwNode *next, *prev; - void *data; -} lwNode; - - -/* plug-in reference */ - -typedef struct st_lwPlugin { - struct st_lwPlugin *next, *prev; - char *ord; - char *name; - int flags; - void *data; -} lwPlugin; - - -/* envelopes */ - -typedef struct st_lwKey { - struct st_lwKey *next, *prev; - float value; - float time; - unsigned int shape; /* ID_TCB, ID_BEZ2, etc. */ - float tension; - float continuity; - float bias; - float param[ 4 ]; -} lwKey; - -typedef struct st_lwEnvelope { - struct st_lwEnvelope *next, *prev; - int index; - int type; - char *name; - lwKey *key; /* linked list of keys */ - int nkeys; - int behavior[ 2 ]; /* pre and post (extrapolation) */ - lwPlugin *cfilter; /* linked list of channel filters */ - int ncfilters; -} lwEnvelope; - -#define BEH_RESET 0 -#define BEH_CONSTANT 1 -#define BEH_REPEAT 2 -#define BEH_OSCILLATE 3 -#define BEH_OFFSET 4 -#define BEH_LINEAR 5 - - -/* values that can be enveloped */ - -typedef struct st_lwEParam { - float val; - int eindex; -} lwEParam; - -typedef struct st_lwVParam { - float val[ 3 ]; - int eindex; -} lwVParam; - - -/* clips */ - -typedef struct st_lwClipStill { - char *name; -} lwClipStill; - -typedef struct st_lwClipSeq { - char *prefix; /* filename before sequence digits */ - char *suffix; /* after digits, e.g. extensions */ - int digits; - int flags; - int offset; - int start; - int end; -} lwClipSeq; - -typedef struct st_lwClipAnim { - char *name; - char *server; /* anim loader plug-in */ - void *data; -} lwClipAnim; - -typedef struct st_lwClipXRef { - char *string; - int index; - struct st_lwClip *clip; -} lwClipXRef; - -typedef struct st_lwClipCycle { - char *name; - int lo; - int hi; -} lwClipCycle; - -typedef struct st_lwClip { - struct st_lwClip *next, *prev; - int index; - unsigned int type; /* ID_STIL, ID_ISEQ, etc. */ - union { - lwClipStill still; - lwClipSeq seq; - lwClipAnim anim; - lwClipXRef xref; - lwClipCycle cycle; - } source; - float start_time; - float duration; - float frame_rate; - lwEParam contrast; - lwEParam brightness; - lwEParam saturation; - lwEParam hue; - lwEParam gamma; - int negative; - lwPlugin *ifilter; /* linked list of image filters */ - int nifilters; - lwPlugin *pfilter; /* linked list of pixel filters */ - int npfilters; -} lwClip; - - -/* textures */ - -typedef struct st_lwTMap { - lwVParam size; - lwVParam center; - lwVParam rotate; - lwVParam falloff; - int fall_type; - char *ref_object; - int coord_sys; -} lwTMap; - -typedef struct st_lwImageMap { - int cindex; - int projection; - char *vmap_name; - int axis; - int wrapw_type; - int wraph_type; - lwEParam wrapw; - lwEParam wraph; - float aa_strength; - int aas_flags; - int pblend; - lwEParam stck; - lwEParam amplitude; -} lwImageMap; - -#define PROJ_PLANAR 0 -#define PROJ_CYLINDRICAL 1 -#define PROJ_SPHERICAL 2 -#define PROJ_CUBIC 3 -#define PROJ_FRONT 4 - -#define WRAP_NONE 0 -#define WRAP_EDGE 1 -#define WRAP_REPEAT 2 -#define WRAP_MIRROR 3 - -typedef struct st_lwProcedural { - int axis; - float value[ 3 ]; - char *name; - void *data; -} lwProcedural; - -typedef struct st_lwGradKey { - struct st_lwGradKey *next, *prev; - float value; - float rgba[ 4 ]; -} lwGradKey; - -typedef struct st_lwGradient { - char *paramname; - char *itemname; - float start; - float end; - int repeat; - lwGradKey *key; /* array of gradient keys */ - short *ikey; /* array of interpolation codes */ -} lwGradient; - -typedef struct st_lwTexture { - struct st_lwTexture *next, *prev; - char *ord; - unsigned int type; - unsigned int chan; - lwEParam opacity; - short opac_type; - short enabled; - short negative; - short axis; - union { - lwImageMap imap; - lwProcedural proc; - lwGradient grad; - } param; - lwTMap tmap; -} lwTexture; - - -/* values that can be textured */ - -typedef struct st_lwTParam { - float val; - int eindex; - lwTexture *tex; /* linked list of texture layers */ -} lwTParam; - -typedef struct st_lwCParam { - float rgb[ 3 ]; - int eindex; - lwTexture *tex; /* linked list of texture layers */ -} lwCParam; - - -/* surfaces */ - -typedef struct st_lwGlow { - short enabled; - short type; - lwEParam intensity; - lwEParam size; -} Glow; - -typedef struct st_lwRMap { - lwTParam val; - int options; - int cindex; - float seam_angle; -} lwRMap; - -typedef struct st_lwLine { - short enabled; - unsigned short flags; - lwEParam size; -} lwLine; - -typedef struct st_lwSurface { - struct st_lwSurface *next, *prev; - char *name; - char *srcname; - lwCParam color; - lwTParam luminosity; - lwTParam diffuse; - lwTParam specularity; - lwTParam glossiness; - lwRMap reflection; - lwRMap transparency; - lwTParam eta; - lwTParam translucency; - lwTParam bump; - float smooth; - int sideflags; - float alpha; - int alpha_mode; - lwEParam color_hilite; - lwEParam color_filter; - lwEParam add_trans; - lwEParam dif_sharp; - lwEParam glow; - lwLine line; - lwPlugin *shader; /* linked list of shaders */ - int nshaders; -} lwSurface; - - -/* vertex maps */ - -typedef struct st_lwVMap { - struct st_lwVMap *next, *prev; - char *name; - unsigned int type; - int dim; - int nverts; - int perpoly; - int *vindex; /* array of point indexes */ - int *pindex; /* array of polygon indexes */ - float **val; -} lwVMap; - -typedef struct st_lwVMapPt { - lwVMap *vmap; - int index; /* vindex or pindex element */ -} lwVMapPt; - - -/* points and polygons */ - -typedef struct st_lwPoint { - float pos[ 3 ]; - int npols; /* number of polygons sharing the point */ - int *pol; /* array of polygon indexes */ - int nvmaps; - lwVMapPt *vm; /* array of vmap references */ -} lwPoint; - -typedef struct st_lwPolVert { - int index; /* index into the point array */ - float norm[ 3 ]; - int nvmaps; - lwVMapPt *vm; /* array of vmap references */ -} lwPolVert; - -typedef struct st_lwPolygon { - lwSurface *surf; - int part; /* part index */ - int smoothgrp; /* smoothing group */ - int flags; - unsigned int type; - float norm[ 3 ]; - int nverts; - lwPolVert *v; /* array of vertex records */ -} lwPolygon; - -typedef struct st_lwPointList { - int count; - int offset; /* only used during reading */ - lwPoint *pt; /* array of points */ -} lwPointList; - -typedef struct st_lwPolygonList { - int count; - int offset; /* only used during reading */ - int vcount; /* total number of vertices */ - int voffset; /* only used during reading */ - lwPolygon *pol; /* array of polygons */ -} lwPolygonList; - - -/* geometry layers */ - -typedef struct st_lwLayer { - struct st_lwLayer *next, *prev; - char *name; - int index; - int parent; - int flags; - float pivot[ 3 ]; - float bbox[ 6 ]; - lwPointList point; - lwPolygonList polygon; - int nvmaps; - lwVMap *vmap; /* linked list of vmaps */ -} lwLayer; - - -/* tag strings */ - -typedef struct st_lwTagList { - int count; - int offset; /* only used during reading */ - char **tag; /* array of strings */ -} lwTagList; - - -/* an object */ - -typedef struct st_lwObject { - lwLayer *layer; /* linked list of layers */ - lwEnvelope *env; /* linked list of envelopes */ - lwClip *clip; /* linked list of clips */ - lwSurface *surf; /* linked list of surfaces */ - lwTagList taglist; - int nlayers; - int nenvs; - int nclips; - int nsurfs; -} lwObject; - - -/* lwo2.c */ - -void lwFreeLayer( lwLayer *layer ); -void lwFreeObject( lwObject *object ); -lwObject *lwGetObject( char *filename, picoMemStream_t *fp, unsigned int *failID, int *failpos ); -int lwValidateObject( char *filename, picoMemStream_t *fp, unsigned int *failID, int *failpos ); - -/* pntspols.c */ - -void lwFreePoints( lwPointList *point ); -void lwFreePolygons( lwPolygonList *plist ); -int lwGetPoints( picoMemStream_t *fp, int cksize, lwPointList *point ); -void lwGetBoundingBox( lwPointList * point, float bbox[] ); -int lwAllocPolygons( lwPolygonList *plist, int npols, int nverts ); -int lwGetPolygons( picoMemStream_t *fp, int cksize, lwPolygonList *plist, int ptoffset ); -void lwGetPolyNormals( lwPointList *point, lwPolygonList *polygon ); -int lwGetPointPolygons( lwPointList *point, lwPolygonList *polygon ); -int lwResolvePolySurfaces( lwPolygonList *polygon, lwTagList *tlist, - lwSurface **surf, int *nsurfs ); -void lwGetVertNormals( lwPointList *point, lwPolygonList *polygon ); -void lwFreeTags( lwTagList *tlist ); -int lwGetTags( picoMemStream_t *fp, int cksize, lwTagList *tlist ); -int lwGetPolygonTags( picoMemStream_t *fp, int cksize, lwTagList *tlist, - lwPolygonList *plist ); - -/* vmap.c */ - -void lwFreeVMap( lwVMap *vmap ); -lwVMap *lwGetVMap( picoMemStream_t *fp, int cksize, int ptoffset, int poloffset, - int perpoly ); -int lwGetPointVMaps( lwPointList *point, lwVMap *vmap ); -int lwGetPolyVMaps( lwPolygonList *polygon, lwVMap *vmap ); - -/* clip.c */ - -void lwFreeClip( lwClip *clip ); -lwClip *lwGetClip( picoMemStream_t *fp, int cksize ); -lwClip *lwFindClip( lwClip *list, int index ); - -/* envelope.c */ - -void lwFreeEnvelope( lwEnvelope *env ); -lwEnvelope *lwGetEnvelope( picoMemStream_t *fp, int cksize ); -lwEnvelope *lwFindEnvelope( lwEnvelope *list, int index ); -float lwEvalEnvelope( lwEnvelope *env, float time ); - -/* surface.c */ - -void lwFreePlugin( lwPlugin *p ); -void lwFreeTexture( lwTexture *t ); -void lwFreeSurface( lwSurface *surf ); -int lwGetTHeader( picoMemStream_t *fp, int hsz, lwTexture *tex ); -int lwGetTMap( picoMemStream_t *fp, int tmapsz, lwTMap *tmap ); -int lwGetImageMap( picoMemStream_t *fp, int rsz, lwTexture *tex ); -int lwGetProcedural( picoMemStream_t *fp, int rsz, lwTexture *tex ); -int lwGetGradient( picoMemStream_t *fp, int rsz, lwTexture *tex ); -lwTexture *lwGetTexture( picoMemStream_t *fp, int bloksz, unsigned int type ); -lwPlugin *lwGetShader( picoMemStream_t *fp, int bloksz ); -lwSurface *lwGetSurface( picoMemStream_t *fp, int cksize ); -lwSurface *lwDefaultSurface( void ); - -/* lwob.c */ - -lwSurface *lwGetSurface5( picoMemStream_t *fp, int cksize, lwObject *obj ); -int lwGetPolygons5( picoMemStream_t *fp, int cksize, lwPolygonList *plist, int ptoffset ); -lwObject *lwGetObject5( char *filename, picoMemStream_t *fp, unsigned int *failID, int *failpos ); -int lwValidateObject5( char *filename, picoMemStream_t *fp, unsigned int *failID, int *failpos ); - -/* list.c */ - -void lwListFree( void *list, void ( *freeNode )( void * ) ); -void lwListAdd( void **list, void *node ); -void lwListInsert( void **vlist, void *vitem, - int ( *compare )( void *, void * ) ); - -/* vecmath.c */ - -float dot( float a[], float b[] ); -void cross( float a[], float b[], float c[] ); -void normalize( float v[] ); -#define vecangle( a, b ) ( float ) acos( dot( a, b ) ) - -/* lwio.c */ - -void set_flen( int i ); -int get_flen( void ); -void *getbytes( picoMemStream_t *fp, int size ); -void skipbytes( picoMemStream_t *fp, int n ); -int getI1( picoMemStream_t *fp ); -short getI2( picoMemStream_t *fp ); -int getI4( picoMemStream_t *fp ); -unsigned char getU1( picoMemStream_t *fp ); -unsigned short getU2( picoMemStream_t *fp ); -unsigned int getU4( picoMemStream_t *fp ); -int getVX( picoMemStream_t *fp ); -float getF4( picoMemStream_t *fp ); -char *getS0( picoMemStream_t *fp ); -int sgetI1( unsigned char **bp ); -short sgetI2( unsigned char **bp ); -int sgetI4( unsigned char **bp ); -unsigned char sgetU1( unsigned char **bp ); -unsigned short sgetU2( unsigned char **bp ); -unsigned int sgetU4( unsigned char **bp ); -int sgetVX( unsigned char **bp ); -float sgetF4( unsigned char **bp ); -char *sgetS0( unsigned char **bp ); - -#ifndef __BIG_ENDIAN__ -void revbytes( void *bp, int elsize, int elcount ); -#else - #define revbytes( b, s, c ) -#endif - -#endif diff --git a/tools/urt/libs/picomodel/lwo/lwob.c b/tools/urt/libs/picomodel/lwo/lwob.c deleted file mode 100644 index b9ab462..0000000 --- a/tools/urt/libs/picomodel/lwo/lwob.c +++ /dev/null @@ -1,818 +0,0 @@ -/* - ====================================================================== - lwob.c - - Functions for an LWOB reader. LWOB is the LightWave object format - for versions of LW prior to 6.0. - - Ernie Wright 17 Sep 00 - ====================================================================== */ - -#include "../picointernal.h" -#include "lwo2.h" - -/* disable warnings */ -#ifdef WIN32 -#pragma warning( disable:4018 ) /* signed/unsigned mismatch */ -#endif - - -/* IDs specific to LWOB */ - -#define ID_SRFS LWID_( 'S','R','F','S' ) -#define ID_FLAG LWID_( 'F','L','A','G' ) -#define ID_VLUM LWID_( 'V','L','U','M' ) -#define ID_VDIF LWID_( 'V','D','I','F' ) -#define ID_VSPC LWID_( 'V','S','P','C' ) -#define ID_RFLT LWID_( 'R','F','L','T' ) -#define ID_BTEX LWID_( 'B','T','E','X' ) -#define ID_CTEX LWID_( 'C','T','E','X' ) -#define ID_DTEX LWID_( 'D','T','E','X' ) -#define ID_LTEX LWID_( 'L','T','E','X' ) -#define ID_RTEX LWID_( 'R','T','E','X' ) -#define ID_STEX LWID_( 'S','T','E','X' ) -#define ID_TTEX LWID_( 'T','T','E','X' ) -#define ID_TFLG LWID_( 'T','F','L','G' ) -#define ID_TSIZ LWID_( 'T','S','I','Z' ) -#define ID_TCTR LWID_( 'T','C','T','R' ) -#define ID_TFAL LWID_( 'T','F','A','L' ) -#define ID_TVEL LWID_( 'T','V','E','L' ) -#define ID_TCLR LWID_( 'T','C','L','R' ) -#define ID_TVAL LWID_( 'T','V','A','L' ) -#define ID_TAMP LWID_( 'T','A','M','P' ) -#define ID_TIMG LWID_( 'T','I','M','G' ) -#define ID_TAAS LWID_( 'T','A','A','S' ) -#define ID_TREF LWID_( 'T','R','E','F' ) -#define ID_TOPC LWID_( 'T','O','P','C' ) -#define ID_SDAT LWID_( 'S','D','A','T' ) -#define ID_TFP0 LWID_( 'T','F','P','0' ) -#define ID_TFP1 LWID_( 'T','F','P','1' ) - - -/* - ====================================================================== - add_clip() - - Add a clip to the clip list. Used to store the contents of an RIMG or - TIMG surface subchunk. - ====================================================================== */ - -static int add_clip( char *s, lwClip **clist, int *nclips ){ - lwClip *clip; - char *p; - - clip = _pico_calloc( 1, sizeof( lwClip ) ); - if ( !clip ) { - return 0; - } - - clip->contrast.val = 1.0f; - clip->brightness.val = 1.0f; - clip->saturation.val = 1.0f; - clip->gamma.val = 1.0f; - - if ( p = strstr( s, "(sequence)" ) ) { - p[ -1 ] = 0; - clip->type = ID_ISEQ; - clip->source.seq.prefix = s; - clip->source.seq.digits = 3; - } - else { - clip->type = ID_STIL; - clip->source.still.name = s; - } - - *nclips++; - clip->index = *nclips; - - lwListAdd( (void *) clist, clip ); - - return clip->index; -} - - -/* - ====================================================================== - add_tvel() - - Add a triple of envelopes to simulate the old texture velocity - parameters. - ====================================================================== */ - -static int add_tvel( float pos[], float vel[], lwEnvelope **elist, int *nenvs ){ - lwEnvelope *env; - lwKey *key0, *key1; - int i; - - for ( i = 0; i < 3; i++ ) { - env = _pico_calloc( 1, sizeof( lwEnvelope ) ); - key0 = _pico_calloc( 1, sizeof( lwKey ) ); - key1 = _pico_calloc( 1, sizeof( lwKey ) ); - if ( !env || !key0 || !key1 ) { - return 0; - } - - key0->next = key1; - key0->value = pos[ i ]; - key0->time = 0.0f; - key1->prev = key0; - key1->value = pos[ i ] + vel[ i ] * 30.0f; - key1->time = 1.0f; - key0->shape = key1->shape = ID_LINE; - - env->index = *nenvs + i + 1; - env->type = 0x0301 + i; - env->name = _pico_alloc( 11 ); - if ( env->name ) { - strcpy( env->name, "Position.X" ); - env->name[ 9 ] += i; - } - env->key = key0; - env->nkeys = 2; - env->behavior[ 0 ] = BEH_LINEAR; - env->behavior[ 1 ] = BEH_LINEAR; - - lwListAdd( (void *) elist, env ); - } - - *nenvs += 3; - return env->index - 2; -} - - -/* - ====================================================================== - get_texture() - - Create a new texture for BTEX, CTEX, etc. subchunks. - ====================================================================== */ - -static lwTexture *get_texture( char *s ){ - lwTexture *tex; - - tex = _pico_calloc( 1, sizeof( lwTexture ) ); - if ( !tex ) { - return NULL; - } - - tex->tmap.size.val[ 0 ] = - tex->tmap.size.val[ 1 ] = - tex->tmap.size.val[ 2 ] = 1.0f; - tex->opacity.val = 1.0f; - tex->enabled = 1; - - if ( strstr( s, "Image Map" ) ) { - tex->type = ID_IMAP; - if ( strstr( s, "Planar" ) ) { - tex->param.imap.projection = 0; - } - else if ( strstr( s, "Cylindrical" ) ) { - tex->param.imap.projection = 1; - } - else if ( strstr( s, "Spherical" ) ) { - tex->param.imap.projection = 2; - } - else if ( strstr( s, "Cubic" ) ) { - tex->param.imap.projection = 3; - } - else if ( strstr( s, "Front" ) ) { - tex->param.imap.projection = 4; - } - tex->param.imap.aa_strength = 1.0f; - tex->param.imap.amplitude.val = 1.0f; - _pico_free( s ); - } - else { - tex->type = ID_PROC; - tex->param.proc.name = s; - } - - return tex; -} - - -/* - ====================================================================== - lwGetSurface5() - - Read an lwSurface from an LWOB file. - ====================================================================== */ - -lwSurface *lwGetSurface5( picoMemStream_t *fp, int cksize, lwObject *obj ){ - lwSurface *surf; - lwTexture *tex; - lwPlugin *shdr; - char *s; - float v[ 3 ]; - unsigned int id, flags; - unsigned short sz; - int pos, rlen, i; - - - /* allocate the Surface structure */ - - surf = _pico_calloc( 1, sizeof( lwSurface ) ); - if ( !surf ) { - goto Fail; - } - - /* non-zero defaults */ - - surf->color.rgb[ 0 ] = 0.78431f; - surf->color.rgb[ 1 ] = 0.78431f; - surf->color.rgb[ 2 ] = 0.78431f; - surf->diffuse.val = 1.0f; - surf->glossiness.val = 0.4f; - surf->bump.val = 1.0f; - surf->eta.val = 1.0f; - surf->sideflags = 1; - - /* remember where we started */ - - set_flen( 0 ); - pos = _pico_memstream_tell( fp ); - - /* name */ - - surf->name = getS0( fp ); - - /* first subchunk header */ - - id = getU4( fp ); - sz = getU2( fp ); - if ( 0 > get_flen() ) { - goto Fail; - } - - /* process subchunks as they're encountered */ - - while ( 1 ) { - sz += sz & 1; - set_flen( 0 ); - - switch ( id ) { - case ID_COLR: - surf->color.rgb[ 0 ] = getU1( fp ) / 255.0f; - surf->color.rgb[ 1 ] = getU1( fp ) / 255.0f; - surf->color.rgb[ 2 ] = getU1( fp ) / 255.0f; - break; - - case ID_FLAG: - flags = getU2( fp ); - if ( flags & 4 ) { - surf->smooth = 1.56207f; - } - if ( flags & 8 ) { - surf->color_hilite.val = 1.0f; - } - if ( flags & 16 ) { - surf->color_filter.val = 1.0f; - } - if ( flags & 128 ) { - surf->dif_sharp.val = 0.5f; - } - if ( flags & 256 ) { - surf->sideflags = 3; - } - if ( flags & 512 ) { - surf->add_trans.val = 1.0f; - } - break; - - case ID_LUMI: - surf->luminosity.val = getI2( fp ) / 256.0f; - break; - - case ID_VLUM: - surf->luminosity.val = getF4( fp ); - break; - - case ID_DIFF: - surf->diffuse.val = getI2( fp ) / 256.0f; - break; - - case ID_VDIF: - surf->diffuse.val = getF4( fp ); - break; - - case ID_SPEC: - surf->specularity.val = getI2( fp ) / 256.0f; - break; - - case ID_VSPC: - surf->specularity.val = getF4( fp ); - break; - - case ID_GLOS: - surf->glossiness.val = ( float ) log( getU2( fp ) ) / 20.7944f; - break; - - case ID_SMAN: - surf->smooth = getF4( fp ); - break; - - case ID_REFL: - surf->reflection.val.val = getI2( fp ) / 256.0f; - break; - - case ID_RFLT: - surf->reflection.options = getU2( fp ); - break; - - case ID_RIMG: - s = getS0( fp ); - surf->reflection.cindex = add_clip( s, &obj->clip, &obj->nclips ); - surf->reflection.options = 3; - break; - - case ID_RSAN: - surf->reflection.seam_angle = getF4( fp ); - break; - - case ID_TRAN: - surf->transparency.val.val = getI2( fp ) / 256.0f; - break; - - case ID_RIND: - surf->eta.val = getF4( fp ); - break; - - case ID_BTEX: - s = getbytes( fp, sz ); - tex = get_texture( s ); - lwListAdd( (void *) &surf->bump.tex, tex ); - break; - - case ID_CTEX: - s = getbytes( fp, sz ); - tex = get_texture( s ); - lwListAdd( (void *) &surf->color.tex, tex ); - break; - - case ID_DTEX: - s = getbytes( fp, sz ); - tex = get_texture( s ); - lwListAdd( (void *) &surf->diffuse.tex, tex ); - break; - - case ID_LTEX: - s = getbytes( fp, sz ); - tex = get_texture( s ); - lwListAdd( (void *) &surf->luminosity.tex, tex ); - break; - - case ID_RTEX: - s = getbytes( fp, sz ); - tex = get_texture( s ); - lwListAdd( (void *) &surf->reflection.val.tex, tex ); - break; - - case ID_STEX: - s = getbytes( fp, sz ); - tex = get_texture( s ); - lwListAdd( (void *) &surf->specularity.tex, tex ); - break; - - case ID_TTEX: - s = getbytes( fp, sz ); - tex = get_texture( s ); - lwListAdd( (void *) &surf->transparency.val.tex, tex ); - break; - - case ID_TFLG: - flags = getU2( fp ); - - if ( flags & 1 ) { - i = 0; - } - if ( flags & 2 ) { - i = 1; - } - if ( flags & 4 ) { - i = 2; - } - tex->axis = i; - if ( tex->type == ID_IMAP ) { - tex->param.imap.axis = i; - } - else{ - tex->param.proc.axis = i; - } - - if ( flags & 8 ) { - tex->tmap.coord_sys = 1; - } - if ( flags & 16 ) { - tex->negative = 1; - } - if ( flags & 32 ) { - tex->param.imap.pblend = 1; - } - if ( flags & 64 ) { - tex->param.imap.aa_strength = 1.0f; - tex->param.imap.aas_flags = 1; - } - break; - - case ID_TSIZ: - for ( i = 0; i < 3; i++ ) - tex->tmap.size.val[ i ] = getF4( fp ); - break; - - case ID_TCTR: - for ( i = 0; i < 3; i++ ) - tex->tmap.center.val[ i ] = getF4( fp ); - break; - - case ID_TFAL: - for ( i = 0; i < 3; i++ ) - tex->tmap.falloff.val[ i ] = getF4( fp ); - break; - - case ID_TVEL: - for ( i = 0; i < 3; i++ ) - v[ i ] = getF4( fp ); - tex->tmap.center.eindex = add_tvel( tex->tmap.center.val, v, - &obj->env, &obj->nenvs ); - break; - - case ID_TCLR: - if ( tex->type == ID_PROC ) { - for ( i = 0; i < 3; i++ ) - tex->param.proc.value[ i ] = getU1( fp ) / 255.0f; - } - break; - - case ID_TVAL: - tex->param.proc.value[ 0 ] = getI2( fp ) / 256.0f; - break; - - case ID_TAMP: - if ( tex->type == ID_IMAP ) { - tex->param.imap.amplitude.val = getF4( fp ); - } - break; - - case ID_TIMG: - s = getS0( fp ); - tex->param.imap.cindex = add_clip( s, &obj->clip, &obj->nclips ); - break; - - case ID_TAAS: - tex->param.imap.aa_strength = getF4( fp ); - tex->param.imap.aas_flags = 1; - break; - - case ID_TREF: - tex->tmap.ref_object = getbytes( fp, sz ); - break; - - case ID_TOPC: - tex->opacity.val = getF4( fp ); - break; - - case ID_TFP0: - if ( tex->type == ID_IMAP ) { - tex->param.imap.wrapw.val = getF4( fp ); - } - break; - - case ID_TFP1: - if ( tex->type == ID_IMAP ) { - tex->param.imap.wraph.val = getF4( fp ); - } - break; - - case ID_SHDR: - shdr = _pico_calloc( 1, sizeof( lwPlugin ) ); - if ( !shdr ) { - goto Fail; - } - shdr->name = getbytes( fp, sz ); - lwListAdd( (void *) &surf->shader, shdr ); - surf->nshaders++; - break; - - case ID_SDAT: - shdr->data = getbytes( fp, sz ); - break; - - default: - break; - } - - /* error while reading current subchunk? */ - - rlen = get_flen(); - if ( rlen < 0 || rlen > sz ) { - goto Fail; - } - - /* skip unread parts of the current subchunk */ - - if ( rlen < sz ) { - _pico_memstream_seek( fp, sz - rlen, PICO_SEEK_CUR ); - } - - /* end of the SURF chunk? */ - - if ( cksize <= _pico_memstream_tell( fp ) - pos ) { - break; - } - - /* get the next subchunk header */ - - set_flen( 0 ); - id = getU4( fp ); - sz = getU2( fp ); - if ( 6 != get_flen() ) { - goto Fail; - } - } - - return surf; - -Fail: - if ( surf ) { - lwFreeSurface( surf ); - } - return NULL; -} - - -/* - ====================================================================== - lwGetPolygons5() - - Read polygon records from a POLS chunk in an LWOB file. The polygons - are added to the array in the lwPolygonList. - ====================================================================== */ - -int lwGetPolygons5( picoMemStream_t *fp, int cksize, lwPolygonList *plist, int ptoffset ){ - lwPolygon *pp; - lwPolVert *pv; - unsigned char *buf, *bp; - int i, j, nv, nverts, npols; - - - if ( cksize == 0 ) { - return 1; - } - - /* read the whole chunk */ - - set_flen( 0 ); - buf = getbytes( fp, cksize ); - if ( !buf ) { - goto Fail; - } - - /* count the polygons and vertices */ - - nverts = 0; - npols = 0; - bp = buf; - - while ( bp < buf + cksize ) { - nv = sgetU2( &bp ); - nverts += nv; - npols++; - bp += 2 * nv; - i = sgetI2( &bp ); - if ( i < 0 ) { - bp += 2; /* detail polygons */ - } - } - - if ( !lwAllocPolygons( plist, npols, nverts ) ) { - goto Fail; - } - - /* fill in the new polygons */ - - bp = buf; - pp = plist->pol + plist->offset; - pv = plist->pol[ 0 ].v + plist->voffset; - - for ( i = 0; i < npols; i++ ) { - nv = sgetU2( &bp ); - - pp->nverts = nv; - pp->type = ID_FACE; - if ( !pp->v ) { - pp->v = pv; - } - for ( j = 0; j < nv; j++ ) - pv[ j ].index = sgetU2( &bp ) + ptoffset; - j = sgetI2( &bp ); - if ( j < 0 ) { - j = -j; - bp += 2; - } - j -= 1; - pp->surf = ( lwSurface * ) j; - - pp++; - pv += nv; - } - - _pico_free( buf ); - return 1; - -Fail: - if ( buf ) { - _pico_free( buf ); - } - lwFreePolygons( plist ); - return 0; -} - - -/* - ====================================================================== - getLWObject5() - - Returns the contents of an LWOB, given its filename, or NULL if the - file couldn't be loaded. On failure, failID and failpos can be used - to diagnose the cause. - - 1. If the file isn't an LWOB, failpos will contain 12 and failID will - be unchanged. - - 2. If an error occurs while reading an LWOB, failID will contain the - most recently read IFF chunk ID, and failpos will contain the - value returned by _pico_memstream_tell() at the time of the failure. - - 3. If the file couldn't be opened, or an error occurs while reading - the first 12 bytes, both failID and failpos will be unchanged. - - If you don't need this information, failID and failpos can be NULL. - ====================================================================== */ - -lwObject *lwGetObject5( char *filename, picoMemStream_t *fp, unsigned int *failID, int *failpos ){ - lwObject *object; - lwLayer *layer; - lwNode *node; - unsigned int id, formsize, type, cksize; - - - /* open the file */ - - if ( !fp ) { - return NULL; - } - - /* read the first 12 bytes */ - - set_flen( 0 ); - id = getU4( fp ); - formsize = getU4( fp ); - type = getU4( fp ); - if ( 12 != get_flen() ) { - return NULL; - } - - /* LWOB? */ - - if ( id != ID_FORM || type != ID_LWOB ) { - if ( failpos ) { - *failpos = 12; - } - return NULL; - } - - /* allocate an object and a default layer */ - - object = _pico_calloc( 1, sizeof( lwObject ) ); - if ( !object ) { - goto Fail; - } - - layer = _pico_calloc( 1, sizeof( lwLayer ) ); - if ( !layer ) { - goto Fail; - } - object->layer = layer; - object->nlayers = 1; - - /* get the first chunk header */ - - id = getU4( fp ); - cksize = getU4( fp ); - if ( 0 > get_flen() ) { - goto Fail; - } - - /* process chunks as they're encountered */ - - while ( 1 ) { - cksize += cksize & 1; - - switch ( id ) - { - case ID_PNTS: - if ( !lwGetPoints( fp, cksize, &layer->point ) ) { - goto Fail; - } - break; - - case ID_POLS: - if ( !lwGetPolygons5( fp, cksize, &layer->polygon, - layer->point.offset ) ) { - goto Fail; - } - break; - - case ID_SRFS: - if ( !lwGetTags( fp, cksize, &object->taglist ) ) { - goto Fail; - } - break; - - case ID_SURF: - node = ( lwNode * ) lwGetSurface5( fp, cksize, object ); - if ( !node ) { - goto Fail; - } - lwListAdd( (void *) &object->surf, node ); - object->nsurfs++; - break; - - default: - _pico_memstream_seek( fp, cksize, PICO_SEEK_CUR ); - break; - } - - /* end of the file? */ - - if ( formsize <= _pico_memstream_tell( fp ) - 8 ) { - break; - } - - /* get the next chunk header */ - - set_flen( 0 ); - id = getU4( fp ); - cksize = getU4( fp ); - if ( 8 != get_flen() ) { - goto Fail; - } - } - - lwGetBoundingBox( &layer->point, layer->bbox ); - lwGetPolyNormals( &layer->point, &layer->polygon ); - if ( !lwGetPointPolygons( &layer->point, &layer->polygon ) ) { - goto Fail; - } - if ( !lwResolvePolySurfaces( &layer->polygon, &object->taglist, - &object->surf, &object->nsurfs ) ) { - goto Fail; - } - lwGetVertNormals( &layer->point, &layer->polygon ); - - return object; - -Fail: - if ( failID ) { - *failID = id; - } - if ( fp ) { - if ( failpos ) { - *failpos = _pico_memstream_tell( fp ); - } - } - lwFreeObject( object ); - return NULL; -} - -int lwValidateObject5( char *filename, picoMemStream_t *fp, unsigned int *failID, int *failpos ){ - unsigned int id, formsize, type; - - - /* open the file */ - - if ( !fp ) { - return PICO_PMV_ERROR_MEMORY; - } - - /* read the first 12 bytes */ - - set_flen( 0 ); - id = getU4( fp ); - formsize = getU4( fp ); - type = getU4( fp ); - if ( 12 != get_flen() ) { - return PICO_PMV_ERROR_SIZE; - } - - /* LWOB? */ - - if ( id != ID_FORM || type != ID_LWOB ) { - if ( failpos ) { - *failpos = 12; - } - return PICO_PMV_ERROR_IDENT; - } - - return PICO_PMV_OK; -} diff --git a/tools/urt/libs/picomodel/lwo/pntspols.c b/tools/urt/libs/picomodel/lwo/pntspols.c deleted file mode 100644 index 15171e8..0000000 --- a/tools/urt/libs/picomodel/lwo/pntspols.c +++ /dev/null @@ -1,588 +0,0 @@ -/* - ====================================================================== - pntspols.c - - Point and polygon functions for an LWO2 reader. - - Ernie Wright 17 Sep 00 - ====================================================================== */ - -#include "../picointernal.h" -#include "lwo2.h" - - -/* - ====================================================================== - lwFreePoints() - - Free the memory used by an lwPointList. - ====================================================================== */ - -void lwFreePoints( lwPointList *point ){ - int i; - - if ( point ) { - if ( point->pt ) { - for ( i = 0; i < point->count; i++ ) { - if ( point->pt[ i ].pol ) { - _pico_free( point->pt[ i ].pol ); - } - if ( point->pt[ i ].vm ) { - _pico_free( point->pt[ i ].vm ); - } - } - _pico_free( point->pt ); - } - memset( point, 0, sizeof( lwPointList ) ); - } -} - - -/* - ====================================================================== - lwFreePolygons() - - Free the memory used by an lwPolygonList. - ====================================================================== */ - -void lwFreePolygons( lwPolygonList *plist ){ - int i, j; - - if ( plist ) { - if ( plist->pol ) { - for ( i = 0; i < plist->count; i++ ) { - if ( plist->pol[ i ].v ) { - for ( j = 0; j < plist->pol[ i ].nverts; j++ ) - if ( plist->pol[ i ].v[ j ].vm ) { - _pico_free( plist->pol[ i ].v[ j ].vm ); - } - } - } - if ( plist->pol[ 0 ].v ) { - _pico_free( plist->pol[ 0 ].v ); - } - _pico_free( plist->pol ); - } - memset( plist, 0, sizeof( lwPolygonList ) ); - } -} - - -/* - ====================================================================== - lwGetPoints() - - Read point records from a PNTS chunk in an LWO2 file. The points are - added to the array in the lwPointList. - ====================================================================== */ - -int lwGetPoints( picoMemStream_t *fp, int cksize, lwPointList *point ){ - float *f; - int np, i, j; - - if ( cksize == 1 ) { - return 1; - } - - /* extend the point array to hold the new points */ - - np = cksize / 12; - point->offset = point->count; - point->count += np; - if ( !_pico_realloc( (void *) &point->pt, ( point->count - np ) * sizeof( lwPoint ), point->count * sizeof( lwPoint ) ) ) { - return 0; - } - memset( &point->pt[ point->offset ], 0, np * sizeof( lwPoint ) ); - - /* read the whole chunk */ - - f = ( float * ) getbytes( fp, cksize ); - if ( !f ) { - return 0; - } - revbytes( f, 4, np * 3 ); - - /* assign position values */ - - for ( i = 0, j = 0; i < np; i++, j += 3 ) { - point->pt[ i ].pos[ 0 ] = f[ j ]; - point->pt[ i ].pos[ 1 ] = f[ j + 1 ]; - point->pt[ i ].pos[ 2 ] = f[ j + 2 ]; - } - - _pico_free( f ); - return 1; -} - - -/* - ====================================================================== - lwGetBoundingBox() - - Calculate the bounding box for a point list, but only if the bounding - box hasn't already been initialized. - ====================================================================== */ - -void lwGetBoundingBox( lwPointList *point, float bbox[] ){ - int i, j; - - if ( point->count == 0 ) { - return; - } - - for ( i = 0; i < 6; i++ ) - if ( bbox[ i ] != 0.0f ) { - return; - } - - bbox[ 0 ] = bbox[ 1 ] = bbox[ 2 ] = 1e20f; - bbox[ 3 ] = bbox[ 4 ] = bbox[ 5 ] = -1e20f; - for ( i = 0; i < point->count; i++ ) { - for ( j = 0; j < 3; j++ ) { - if ( bbox[ j ] > point->pt[ i ].pos[ j ] ) { - bbox[ j ] = point->pt[ i ].pos[ j ]; - } - if ( bbox[ j + 3 ] < point->pt[ i ].pos[ j ] ) { - bbox[ j + 3 ] = point->pt[ i ].pos[ j ]; - } - } - } -} - - -/* - ====================================================================== - lwAllocPolygons() - - Allocate or extend the polygon arrays to hold new records. - ====================================================================== */ - -int lwAllocPolygons( lwPolygonList *plist, int npols, int nverts ){ - int i; - - plist->offset = plist->count; - plist->count += npols; - if ( !_pico_realloc( (void *) &plist->pol, ( plist->count - npols ) * sizeof( lwPolygon ), plist->count * sizeof( lwPolygon ) ) ) { - return 0; - } - memset( plist->pol + plist->offset, 0, npols * sizeof( lwPolygon ) ); - - plist->voffset = plist->vcount; - plist->vcount += nverts; - if ( !_pico_realloc( (void *) &plist->pol[ 0 ].v, ( plist->vcount - nverts ) * sizeof( lwPolVert ), plist->vcount * sizeof( lwPolVert ) ) ) { - return 0; - } - memset( plist->pol[ 0 ].v + plist->voffset, 0, nverts * sizeof( lwPolVert ) ); - - /* fix up the old vertex pointers */ - - for ( i = 1; i < plist->offset; i++ ) - plist->pol[ i ].v = plist->pol[ i - 1 ].v + plist->pol[ i - 1 ].nverts; - - return 1; -} - - -/* - ====================================================================== - lwGetPolygons() - - Read polygon records from a POLS chunk in an LWO2 file. The polygons - are added to the array in the lwPolygonList. - ====================================================================== */ - -int lwGetPolygons( picoMemStream_t *fp, int cksize, lwPolygonList *plist, int ptoffset ){ - lwPolygon *pp; - lwPolVert *pv; - unsigned char *buf, *bp; - int i, j, flags, nv, nverts, npols; - unsigned int type; - - - if ( cksize == 0 ) { - return 1; - } - - /* read the whole chunk */ - - set_flen( 0 ); - type = getU4( fp ); - buf = getbytes( fp, cksize - 4 ); - if ( cksize != get_flen() ) { - goto Fail; - } - - /* count the polygons and vertices */ - - nverts = 0; - npols = 0; - bp = buf; - - while ( bp < buf + cksize - 4 ) { - nv = sgetU2( &bp ); - nv &= 0x03FF; - nverts += nv; - npols++; - for ( i = 0; i < nv; i++ ) - j = sgetVX( &bp ); - } - - if ( !lwAllocPolygons( plist, npols, nverts ) ) { - goto Fail; - } - - /* fill in the new polygons */ - - bp = buf; - pp = plist->pol + plist->offset; - pv = plist->pol[ 0 ].v + plist->voffset; - - for ( i = 0; i < npols; i++ ) { - nv = sgetU2( &bp ); - flags = nv & 0xFC00; - nv &= 0x03FF; - - pp->nverts = nv; - pp->flags = flags; - pp->type = type; - if ( !pp->v ) { - pp->v = pv; - } - for ( j = 0; j < nv; j++ ) - pp->v[ j ].index = sgetVX( &bp ) + ptoffset; - - pp++; - pv += nv; - } - - _pico_free( buf ); - return 1; - -Fail: - if ( buf ) { - _pico_free( buf ); - } - lwFreePolygons( plist ); - return 0; -} - - -/* - ====================================================================== - lwGetPolyNormals() - - Calculate the polygon normals. By convention, LW's polygon normals - are found as the cross product of the first and last edges. It's - undefined for one- and two-point polygons. - ====================================================================== */ - -void lwGetPolyNormals( lwPointList *point, lwPolygonList *polygon ){ - int i, j; - float p1[ 3 ], p2[ 3 ], pn[ 3 ], v1[ 3 ], v2[ 3 ]; - - for ( i = 0; i < polygon->count; i++ ) { - if ( polygon->pol[ i ].nverts < 3 ) { - continue; - } - for ( j = 0; j < 3; j++ ) { - p1[ j ] = point->pt[ polygon->pol[ i ].v[ 0 ].index ].pos[ j ]; - p2[ j ] = point->pt[ polygon->pol[ i ].v[ 1 ].index ].pos[ j ]; - pn[ j ] = point->pt[ polygon->pol[ i ].v[ - polygon->pol[ i ].nverts - 1 ].index ].pos[ j ]; - } - - for ( j = 0; j < 3; j++ ) { - v1[ j ] = p2[ j ] - p1[ j ]; - v2[ j ] = pn[ j ] - p1[ j ]; - } - - cross( v1, v2, polygon->pol[ i ].norm ); - normalize( polygon->pol[ i ].norm ); - } -} - - -/* - ====================================================================== - lwGetPointPolygons() - - For each point, fill in the indexes of the polygons that share the - point. Returns 0 if any of the memory allocations fail, otherwise - returns 1. - ====================================================================== */ - -int lwGetPointPolygons( lwPointList *point, lwPolygonList *polygon ){ - int i, j, k; - - /* count the number of polygons per point */ - - for ( i = 0; i < polygon->count; i++ ) - for ( j = 0; j < polygon->pol[ i ].nverts; j++ ) - ++point->pt[ polygon->pol[ i ].v[ j ].index ].npols; - - /* alloc per-point polygon arrays */ - - for ( i = 0; i < point->count; i++ ) { - if ( point->pt[ i ].npols == 0 ) { - continue; - } - point->pt[ i ].pol = _pico_calloc( point->pt[ i ].npols, sizeof( int ) ); - if ( !point->pt[ i ].pol ) { - return 0; - } - point->pt[ i ].npols = 0; - } - - /* fill in polygon array for each point */ - - for ( i = 0; i < polygon->count; i++ ) { - for ( j = 0; j < polygon->pol[ i ].nverts; j++ ) { - k = polygon->pol[ i ].v[ j ].index; - point->pt[ k ].pol[ point->pt[ k ].npols ] = i; - ++point->pt[ k ].npols; - } - } - - return 1; -} - - -/* - ====================================================================== - lwResolvePolySurfaces() - - Convert tag indexes into actual lwSurface pointers. If any polygons - point to tags for which no corresponding surface can be found, a - default surface is created. - ====================================================================== */ - -int lwResolvePolySurfaces( lwPolygonList *polygon, lwTagList *tlist, - lwSurface **surf, int *nsurfs ){ - lwSurface **s, *st; - int i, index; - - if ( tlist->count == 0 ) { - return 1; - } - - s = _pico_calloc( tlist->count, sizeof( lwSurface * ) ); - if ( !s ) { - return 0; - } - - for ( i = 0; i < tlist->count; i++ ) { - st = *surf; - while ( st ) { - if ( !strcmp( st->name, tlist->tag[ i ] ) ) { - s[ i ] = st; - break; - } - st = st->next; - } - } - - for ( i = 0; i < polygon->count; i++ ) { - index = ( int ) polygon->pol[ i ].surf; - if ( index < 0 || index > tlist->count ) { - return 0; - } - if ( !s[ index ] ) { - s[ index ] = lwDefaultSurface(); - if ( !s[ index ] ) { - return 0; - } - s[ index ]->name = _pico_alloc( strlen( tlist->tag[ index ] ) + 1 ); - if ( !s[ index ]->name ) { - return 0; - } - strcpy( s[ index ]->name, tlist->tag[ index ] ); - lwListAdd( (void *) surf, s[ index ] ); - *nsurfs = *nsurfs + 1; - } - polygon->pol[ i ].surf = s[ index ]; - } - - _pico_free( s ); - return 1; -} - - -/* - ====================================================================== - lwGetVertNormals() - - Calculate the vertex normals. For each polygon vertex, sum the - normals of the polygons that share the point. If the normals of the - current and adjacent polygons form an angle greater than the max - smoothing angle for the current polygon's surface, the normal of the - adjacent polygon is excluded from the sum. It's also excluded if the - polygons aren't in the same smoothing group. - - Assumes that lwGetPointPolygons(), lwGetPolyNormals() and - lwResolvePolySurfaces() have already been called. - ====================================================================== */ - -void lwGetVertNormals( lwPointList *point, lwPolygonList *polygon ){ - int j, k, n, g, h, p; - float a; - - for ( j = 0; j < polygon->count; j++ ) { - for ( n = 0; n < polygon->pol[ j ].nverts; n++ ) { - for ( k = 0; k < 3; k++ ) - polygon->pol[ j ].v[ n ].norm[ k ] = polygon->pol[ j ].norm[ k ]; - - if ( polygon->pol[ j ].surf->smooth <= 0 ) { - continue; - } - - p = polygon->pol[ j ].v[ n ].index; - - for ( g = 0; g < point->pt[ p ].npols; g++ ) { - h = point->pt[ p ].pol[ g ]; - if ( h == j ) { - continue; - } - - if ( polygon->pol[ j ].smoothgrp != polygon->pol[ h ].smoothgrp ) { - continue; - } - a = vecangle( polygon->pol[ j ].norm, polygon->pol[ h ].norm ); - if ( a > polygon->pol[ j ].surf->smooth ) { - continue; - } - - for ( k = 0; k < 3; k++ ) - polygon->pol[ j ].v[ n ].norm[ k ] += polygon->pol[ h ].norm[ k ]; - } - - normalize( polygon->pol[ j ].v[ n ].norm ); - } - } -} - - -/* - ====================================================================== - lwFreeTags() - - Free memory used by an lwTagList. - ====================================================================== */ - -void lwFreeTags( lwTagList *tlist ){ - int i; - - if ( tlist ) { - if ( tlist->tag ) { - for ( i = 0; i < tlist->count; i++ ) - if ( tlist->tag[ i ] ) { - _pico_free( tlist->tag[ i ] ); - } - _pico_free( tlist->tag ); - } - memset( tlist, 0, sizeof( lwTagList ) ); - } -} - - -/* - ====================================================================== - lwGetTags() - - Read tag strings from a TAGS chunk in an LWO2 file. The tags are - added to the lwTagList array. - ====================================================================== */ - -int lwGetTags( picoMemStream_t *fp, int cksize, lwTagList *tlist ){ - char *buf, *bp; - int i, len, ntags; - - if ( cksize == 0 ) { - return 1; - } - - /* read the whole chunk */ - - set_flen( 0 ); - buf = getbytes( fp, cksize ); - if ( !buf ) { - return 0; - } - - /* count the strings */ - - ntags = 0; - bp = buf; - while ( bp < buf + cksize ) { - len = strlen( bp ) + 1; - len += len & 1; - bp += len; - ++ntags; - } - - /* expand the string array to hold the new tags */ - - tlist->offset = tlist->count; - tlist->count += ntags; - if ( !_pico_realloc( (void *) &tlist->tag, ( tlist->count - ntags ) * sizeof( char * ), tlist->count * sizeof( char * ) ) ) { - goto Fail; - } - memset( &tlist->tag[ tlist->offset ], 0, ntags * sizeof( char * ) ); - - /* copy the new tags to the tag array */ - - bp = buf; - for ( i = 0; i < ntags; i++ ) - tlist->tag[ i + tlist->offset ] = sgetS0( (unsigned char **) &bp ); - - _pico_free( buf ); - return 1; - -Fail: - if ( buf ) { - _pico_free( buf ); - } - return 0; -} - - -/* - ====================================================================== - lwGetPolygonTags() - - Read polygon tags from a PTAG chunk in an LWO2 file. - ====================================================================== */ - -int lwGetPolygonTags( picoMemStream_t *fp, int cksize, lwTagList *tlist, - lwPolygonList *plist ){ - unsigned int type; - int rlen = 0, i, j; - - set_flen( 0 ); - type = getU4( fp ); - rlen = get_flen(); - if ( rlen < 0 ) { - return 0; - } - - if ( type != ID_SURF && type != ID_PART && type != ID_SMGP ) { - _pico_memstream_seek( fp, cksize - 4, PICO_SEEK_CUR ); - return 1; - } - - while ( rlen < cksize ) { - i = getVX( fp ) + plist->offset; - j = getVX( fp ) + tlist->offset; - rlen = get_flen(); - if ( rlen < 0 || rlen > cksize ) { - return 0; - } - - switch ( type ) { - case ID_SURF: plist->pol[ i ].surf = ( lwSurface * ) j; break; - case ID_PART: plist->pol[ i ].part = j; break; - case ID_SMGP: plist->pol[ i ].smoothgrp = j; break; - } - } - - return 1; -} diff --git a/tools/urt/libs/picomodel/lwo/surface.c b/tools/urt/libs/picomodel/lwo/surface.c deleted file mode 100644 index 4b35002..0000000 --- a/tools/urt/libs/picomodel/lwo/surface.c +++ /dev/null @@ -1,1107 +0,0 @@ -/* - ====================================================================== - surface.c - - Surface functions for an LWO2 reader. - - Ernie Wright 17 Sep 00 - ====================================================================== */ - -#include "../picointernal.h" -#include "lwo2.h" - - -/* - ====================================================================== - lwFreePlugin() - - Free the memory used by an lwPlugin. - ====================================================================== */ - -void lwFreePlugin( lwPlugin *p ){ - if ( p ) { - if ( p->ord ) { - _pico_free( p->ord ); - } - if ( p->name ) { - _pico_free( p->name ); - } - if ( p->data ) { - _pico_free( p->data ); - } - _pico_free( p ); - } -} - - -/* - ====================================================================== - lwFreeTexture() - - Free the memory used by an lwTexture. - ====================================================================== */ - -void lwFreeTexture( lwTexture *t ){ - if ( t ) { - if ( t->ord ) { - _pico_free( t->ord ); - } - switch ( t->type ) { - case ID_IMAP: - if ( t->param.imap.vmap_name ) { - _pico_free( t->param.imap.vmap_name ); - } - if ( t->tmap.ref_object ) { - _pico_free( t->tmap.ref_object ); - } - break; - case ID_PROC: - if ( t->param.proc.name ) { - _pico_free( t->param.proc.name ); - } - if ( t->param.proc.data ) { - _pico_free( t->param.proc.data ); - } - break; - case ID_GRAD: - if ( t->param.grad.key ) { - _pico_free( t->param.grad.key ); - } - if ( t->param.grad.ikey ) { - _pico_free( t->param.grad.ikey ); - } - break; - } - _pico_free( t ); - } -} - - -/* - ====================================================================== - lwFreeSurface() - - Free the memory used by an lwSurface. - ====================================================================== */ - -void lwFreeSurface( lwSurface *surf ){ - if ( surf ) { - if ( surf->name ) { - _pico_free( surf->name ); - } - if ( surf->srcname ) { - _pico_free( surf->srcname ); - } - - lwListFree( surf->shader, (void *) lwFreePlugin ); - - lwListFree( surf->color.tex, (void *) lwFreeTexture ); - lwListFree( surf->luminosity.tex, (void *) lwFreeTexture ); - lwListFree( surf->diffuse.tex, (void *) lwFreeTexture ); - lwListFree( surf->specularity.tex, (void *) lwFreeTexture ); - lwListFree( surf->glossiness.tex, (void *) lwFreeTexture ); - lwListFree( surf->reflection.val.tex, (void *) lwFreeTexture ); - lwListFree( surf->transparency.val.tex, (void *) lwFreeTexture ); - lwListFree( surf->eta.tex, (void *) lwFreeTexture ); - lwListFree( surf->translucency.tex, (void *) lwFreeTexture ); - lwListFree( surf->bump.tex, (void *) lwFreeTexture ); - - _pico_free( surf ); - } -} - - -/* - ====================================================================== - lwGetTHeader() - - Read a texture map header from a SURF.BLOK in an LWO2 file. This is - the first subchunk in a BLOK, and its contents are common to all three - texture types. - ====================================================================== */ - -int lwGetTHeader( picoMemStream_t *fp, int hsz, lwTexture *tex ){ - unsigned int id; - unsigned short sz; - int pos, rlen; - - - /* remember where we started */ - - set_flen( 0 ); - pos = _pico_memstream_tell( fp ); - - /* ordinal string */ - - tex->ord = getS0( fp ); - - /* first subchunk header */ - - id = getU4( fp ); - sz = getU2( fp ); - if ( 0 > get_flen() ) { - return 0; - } - - /* process subchunks as they're encountered */ - - while ( 1 ) { - sz += sz & 1; - set_flen( 0 ); - - switch ( id ) { - case ID_CHAN: - tex->chan = getU4( fp ); - break; - - case ID_OPAC: - tex->opac_type = getU2( fp ); - tex->opacity.val = getF4( fp ); - tex->opacity.eindex = getVX( fp ); - break; - - case ID_ENAB: - tex->enabled = getU2( fp ); - break; - - case ID_NEGA: - tex->negative = getU2( fp ); - break; - - case ID_AXIS: - tex->axis = getU2( fp ); - break; - - default: - break; - } - - /* error while reading current subchunk? */ - - rlen = get_flen(); - if ( rlen < 0 || rlen > sz ) { - return 0; - } - - /* skip unread parts of the current subchunk */ - - if ( rlen < sz ) { - _pico_memstream_seek( fp, sz - rlen, PICO_SEEK_CUR ); - } - - /* end of the texture header subchunk? */ - - if ( hsz <= _pico_memstream_tell( fp ) - pos ) { - break; - } - - /* get the next subchunk header */ - - set_flen( 0 ); - id = getU4( fp ); - sz = getU2( fp ); - if ( 6 != get_flen() ) { - return 0; - } - } - - set_flen( _pico_memstream_tell( fp ) - pos ); - return 1; -} - - -/* - ====================================================================== - lwGetTMap() - - Read a texture map from a SURF.BLOK in an LWO2 file. The TMAP - defines the mapping from texture to world or object coordinates. - ====================================================================== */ - -int lwGetTMap( picoMemStream_t *fp, int tmapsz, lwTMap *tmap ){ - unsigned int id; - unsigned short sz; - int rlen, pos, i; - - pos = _pico_memstream_tell( fp ); - id = getU4( fp ); - sz = getU2( fp ); - if ( 0 > get_flen() ) { - return 0; - } - - while ( 1 ) { - sz += sz & 1; - set_flen( 0 ); - - switch ( id ) { - case ID_SIZE: - for ( i = 0; i < 3; i++ ) - tmap->size.val[ i ] = getF4( fp ); - tmap->size.eindex = getVX( fp ); - break; - - case ID_CNTR: - for ( i = 0; i < 3; i++ ) - tmap->center.val[ i ] = getF4( fp ); - tmap->center.eindex = getVX( fp ); - break; - - case ID_ROTA: - for ( i = 0; i < 3; i++ ) - tmap->rotate.val[ i ] = getF4( fp ); - tmap->rotate.eindex = getVX( fp ); - break; - - case ID_FALL: - tmap->fall_type = getU2( fp ); - for ( i = 0; i < 3; i++ ) - tmap->falloff.val[ i ] = getF4( fp ); - tmap->falloff.eindex = getVX( fp ); - break; - - case ID_OREF: - tmap->ref_object = getS0( fp ); - break; - - case ID_CSYS: - tmap->coord_sys = getU2( fp ); - break; - - default: - break; - } - - /* error while reading the current subchunk? */ - - rlen = get_flen(); - if ( rlen < 0 || rlen > sz ) { - return 0; - } - - /* skip unread parts of the current subchunk */ - - if ( rlen < sz ) { - _pico_memstream_seek( fp, sz - rlen, PICO_SEEK_CUR ); - } - - /* end of the TMAP subchunk? */ - - if ( tmapsz <= _pico_memstream_tell( fp ) - pos ) { - break; - } - - /* get the next subchunk header */ - - set_flen( 0 ); - id = getU4( fp ); - sz = getU2( fp ); - if ( 6 != get_flen() ) { - return 0; - } - } - - set_flen( _pico_memstream_tell( fp ) - pos ); - return 1; -} - - -/* - ====================================================================== - lwGetImageMap() - - Read an lwImageMap from a SURF.BLOK in an LWO2 file. - ====================================================================== */ - -int lwGetImageMap( picoMemStream_t *fp, int rsz, lwTexture *tex ){ - unsigned int id; - unsigned short sz; - int rlen, pos; - - pos = _pico_memstream_tell( fp ); - id = getU4( fp ); - sz = getU2( fp ); - if ( 0 > get_flen() ) { - return 0; - } - - while ( 1 ) { - sz += sz & 1; - set_flen( 0 ); - - switch ( id ) { - case ID_TMAP: - if ( !lwGetTMap( fp, sz, &tex->tmap ) ) { - return 0; - } - break; - - case ID_PROJ: - tex->param.imap.projection = getU2( fp ); - break; - - case ID_VMAP: - tex->param.imap.vmap_name = getS0( fp ); - break; - - case ID_AXIS: - tex->param.imap.axis = getU2( fp ); - break; - - case ID_IMAG: - tex->param.imap.cindex = getVX( fp ); - break; - - case ID_WRAP: - tex->param.imap.wrapw_type = getU2( fp ); - tex->param.imap.wraph_type = getU2( fp ); - break; - - case ID_WRPW: - tex->param.imap.wrapw.val = getF4( fp ); - tex->param.imap.wrapw.eindex = getVX( fp ); - break; - - case ID_WRPH: - tex->param.imap.wraph.val = getF4( fp ); - tex->param.imap.wraph.eindex = getVX( fp ); - break; - - case ID_AAST: - tex->param.imap.aas_flags = getU2( fp ); - tex->param.imap.aa_strength = getF4( fp ); - break; - - case ID_PIXB: - tex->param.imap.pblend = getU2( fp ); - break; - - case ID_STCK: - tex->param.imap.stck.val = getF4( fp ); - tex->param.imap.stck.eindex = getVX( fp ); - break; - - case ID_TAMP: - tex->param.imap.amplitude.val = getF4( fp ); - tex->param.imap.amplitude.eindex = getVX( fp ); - break; - - default: - break; - } - - /* error while reading the current subchunk? */ - - rlen = get_flen(); - if ( rlen < 0 || rlen > sz ) { - return 0; - } - - /* skip unread parts of the current subchunk */ - - if ( rlen < sz ) { - _pico_memstream_seek( fp, sz - rlen, PICO_SEEK_CUR ); - } - - /* end of the image map? */ - - if ( rsz <= _pico_memstream_tell( fp ) - pos ) { - break; - } - - /* get the next subchunk header */ - - set_flen( 0 ); - id = getU4( fp ); - sz = getU2( fp ); - if ( 6 != get_flen() ) { - return 0; - } - } - - set_flen( _pico_memstream_tell( fp ) - pos ); - return 1; -} - - -/* - ====================================================================== - lwGetProcedural() - - Read an lwProcedural from a SURF.BLOK in an LWO2 file. - ====================================================================== */ - -int lwGetProcedural( picoMemStream_t *fp, int rsz, lwTexture *tex ){ - unsigned int id; - unsigned short sz; - int rlen, pos; - - pos = _pico_memstream_tell( fp ); - id = getU4( fp ); - sz = getU2( fp ); - if ( 0 > get_flen() ) { - return 0; - } - - while ( 1 ) { - sz += sz & 1; - set_flen( 0 ); - - switch ( id ) { - case ID_TMAP: - if ( !lwGetTMap( fp, sz, &tex->tmap ) ) { - return 0; - } - break; - - case ID_AXIS: - tex->param.proc.axis = getU2( fp ); - break; - - case ID_VALU: - tex->param.proc.value[ 0 ] = getF4( fp ); - if ( sz >= 8 ) { - tex->param.proc.value[ 1 ] = getF4( fp ); - } - if ( sz >= 12 ) { - tex->param.proc.value[ 2 ] = getF4( fp ); - } - break; - - case ID_FUNC: - tex->param.proc.name = getS0( fp ); - rlen = get_flen(); - tex->param.proc.data = getbytes( fp, sz - rlen ); - break; - - default: - break; - } - - /* error while reading the current subchunk? */ - - rlen = get_flen(); - if ( rlen < 0 || rlen > sz ) { - return 0; - } - - /* skip unread parts of the current subchunk */ - - if ( rlen < sz ) { - _pico_memstream_seek( fp, sz - rlen, PICO_SEEK_CUR ); - } - - /* end of the procedural block? */ - - if ( rsz <= _pico_memstream_tell( fp ) - pos ) { - break; - } - - /* get the next subchunk header */ - - set_flen( 0 ); - id = getU4( fp ); - sz = getU2( fp ); - if ( 6 != get_flen() ) { - return 0; - } - } - - set_flen( _pico_memstream_tell( fp ) - pos ); - return 1; -} - - -/* - ====================================================================== - lwGetGradient() - - Read an lwGradient from a SURF.BLOK in an LWO2 file. - ====================================================================== */ - -int lwGetGradient( picoMemStream_t *fp, int rsz, lwTexture *tex ){ - unsigned int id; - unsigned short sz; - int rlen, pos, i, j, nkeys; - - pos = _pico_memstream_tell( fp ); - id = getU4( fp ); - sz = getU2( fp ); - if ( 0 > get_flen() ) { - return 0; - } - - while ( 1 ) { - sz += sz & 1; - set_flen( 0 ); - - switch ( id ) { - case ID_TMAP: - if ( !lwGetTMap( fp, sz, &tex->tmap ) ) { - return 0; - } - break; - - case ID_PNAM: - tex->param.grad.paramname = getS0( fp ); - break; - - case ID_INAM: - tex->param.grad.itemname = getS0( fp ); - break; - - case ID_GRST: - tex->param.grad.start = getF4( fp ); - break; - - case ID_GREN: - tex->param.grad.end = getF4( fp ); - break; - - case ID_GRPT: - tex->param.grad.repeat = getU2( fp ); - break; - - case ID_FKEY: - nkeys = sz / sizeof( lwGradKey ); - tex->param.grad.key = _pico_calloc( nkeys, sizeof( lwGradKey ) ); - if ( !tex->param.grad.key ) { - return 0; - } - for ( i = 0; i < nkeys; i++ ) { - tex->param.grad.key[ i ].value = getF4( fp ); - for ( j = 0; j < 4; j++ ) - tex->param.grad.key[ i ].rgba[ j ] = getF4( fp ); - } - break; - - case ID_IKEY: - nkeys = sz / 2; - tex->param.grad.ikey = _pico_calloc( nkeys, sizeof( short ) ); - if ( !tex->param.grad.ikey ) { - return 0; - } - for ( i = 0; i < nkeys; i++ ) - tex->param.grad.ikey[ i ] = getU2( fp ); - break; - - default: - break; - } - - /* error while reading the current subchunk? */ - - rlen = get_flen(); - if ( rlen < 0 || rlen > sz ) { - return 0; - } - - /* skip unread parts of the current subchunk */ - - if ( rlen < sz ) { - _pico_memstream_seek( fp, sz - rlen, PICO_SEEK_CUR ); - } - - /* end of the gradient? */ - - if ( rsz <= _pico_memstream_tell( fp ) - pos ) { - break; - } - - /* get the next subchunk header */ - - set_flen( 0 ); - id = getU4( fp ); - sz = getU2( fp ); - if ( 6 != get_flen() ) { - return 0; - } - } - - set_flen( _pico_memstream_tell( fp ) - pos ); - return 1; -} - - -/* - ====================================================================== - lwGetTexture() - - Read an lwTexture from a SURF.BLOK in an LWO2 file. - ====================================================================== */ - -lwTexture *lwGetTexture( picoMemStream_t *fp, int bloksz, unsigned int type ){ - lwTexture *tex; - unsigned short sz; - int ok; - - tex = _pico_calloc( 1, sizeof( lwTexture ) ); - if ( !tex ) { - return NULL; - } - - tex->type = type; - tex->tmap.size.val[ 0 ] = - tex->tmap.size.val[ 1 ] = - tex->tmap.size.val[ 2 ] = 1.0f; - tex->opacity.val = 1.0f; - tex->enabled = 1; - - sz = getU2( fp ); - if ( !lwGetTHeader( fp, sz, tex ) ) { - _pico_free( tex ); - return NULL; - } - - sz = bloksz - sz - 6; - switch ( type ) { - case ID_IMAP: ok = lwGetImageMap( fp, sz, tex ); break; - case ID_PROC: ok = lwGetProcedural( fp, sz, tex ); break; - case ID_GRAD: ok = lwGetGradient( fp, sz, tex ); break; - default: - ok = !_pico_memstream_seek( fp, sz, PICO_SEEK_CUR ); - } - - if ( !ok ) { - lwFreeTexture( tex ); - return NULL; - } - - set_flen( bloksz ); - return tex; -} - - -/* - ====================================================================== - lwGetShader() - - Read a shader record from a SURF.BLOK in an LWO2 file. - ====================================================================== */ - -lwPlugin *lwGetShader( picoMemStream_t *fp, int bloksz ){ - lwPlugin *shdr; - unsigned int id; - unsigned short sz; - int hsz, rlen, pos; - - shdr = _pico_calloc( 1, sizeof( lwPlugin ) ); - if ( !shdr ) { - return NULL; - } - - pos = _pico_memstream_tell( fp ); - set_flen( 0 ); - hsz = getU2( fp ); - shdr->ord = getS0( fp ); - id = getU4( fp ); - sz = getU2( fp ); - if ( 0 > get_flen() ) { - goto Fail; - } - - while ( hsz > 0 ) { - sz += sz & 1; - hsz -= sz; - if ( id == ID_ENAB ) { - shdr->flags = getU2( fp ); - break; - } - else { - _pico_memstream_seek( fp, sz, PICO_SEEK_CUR ); - id = getU4( fp ); - sz = getU2( fp ); - } - } - - id = getU4( fp ); - sz = getU2( fp ); - if ( 0 > get_flen() ) { - goto Fail; - } - - while ( 1 ) { - sz += sz & 1; - set_flen( 0 ); - - switch ( id ) { - case ID_FUNC: - shdr->name = getS0( fp ); - rlen = get_flen(); - shdr->data = getbytes( fp, sz - rlen ); - break; - - default: - break; - } - - /* error while reading the current subchunk? */ - - rlen = get_flen(); - if ( rlen < 0 || rlen > sz ) { - goto Fail; - } - - /* skip unread parts of the current subchunk */ - - if ( rlen < sz ) { - _pico_memstream_seek( fp, sz - rlen, PICO_SEEK_CUR ); - } - - /* end of the shader block? */ - - if ( bloksz <= _pico_memstream_tell( fp ) - pos ) { - break; - } - - /* get the next subchunk header */ - - set_flen( 0 ); - id = getU4( fp ); - sz = getU2( fp ); - if ( 6 != get_flen() ) { - goto Fail; - } - } - - set_flen( _pico_memstream_tell( fp ) - pos ); - return shdr; - -Fail: - lwFreePlugin( shdr ); - return NULL; -} - - -/* - ====================================================================== - compare_textures() - compare_shaders() - - Callbacks for the lwListInsert() function, which is called to add - textures to surface channels and shaders to surfaces. - ====================================================================== */ - -static int compare_textures( lwTexture *a, lwTexture *b ){ - return strcmp( a->ord, b->ord ); -} - - -static int compare_shaders( lwPlugin *a, lwPlugin *b ){ - return strcmp( a->ord, b->ord ); -} - - -/* - ====================================================================== - add_texture() - - Finds the surface channel (lwTParam or lwCParam) to which a texture is - applied, then calls lwListInsert(). - ====================================================================== */ - -static int add_texture( lwSurface *surf, lwTexture *tex ){ - lwTexture **list; - - switch ( tex->chan ) { - case ID_COLR: list = &surf->color.tex; break; - case ID_LUMI: list = &surf->luminosity.tex; break; - case ID_DIFF: list = &surf->diffuse.tex; break; - case ID_SPEC: list = &surf->specularity.tex; break; - case ID_GLOS: list = &surf->glossiness.tex; break; - case ID_REFL: list = &surf->reflection.val.tex; break; - case ID_TRAN: list = &surf->transparency.val.tex; break; - case ID_RIND: list = &surf->eta.tex; break; - case ID_TRNL: list = &surf->translucency.tex; break; - case ID_BUMP: list = &surf->bump.tex; break; - default: return 0; - } - - lwListInsert( (void **) list, tex, ( void *) compare_textures ); - return 1; -} - - -/* - ====================================================================== - lwDefaultSurface() - - Allocate and initialize a surface. - ====================================================================== */ - -lwSurface *lwDefaultSurface( void ){ - lwSurface *surf; - - surf = _pico_calloc( 1, sizeof( lwSurface ) ); - if ( !surf ) { - return NULL; - } - - surf->color.rgb[ 0 ] = 0.78431f; - surf->color.rgb[ 1 ] = 0.78431f; - surf->color.rgb[ 2 ] = 0.78431f; - surf->diffuse.val = 1.0f; - surf->glossiness.val = 0.4f; - surf->bump.val = 1.0f; - surf->eta.val = 1.0f; - surf->sideflags = 1; - - return surf; -} - - -/* - ====================================================================== - lwGetSurface() - - Read an lwSurface from an LWO2 file. - ====================================================================== */ - -lwSurface *lwGetSurface( picoMemStream_t *fp, int cksize ){ - lwSurface *surf; - lwTexture *tex; - lwPlugin *shdr; - unsigned int id, type; - unsigned short sz; - int pos, rlen; - - - /* allocate the Surface structure */ - - surf = _pico_calloc( 1, sizeof( lwSurface ) ); - if ( !surf ) { - goto Fail; - } - - /* non-zero defaults */ - - surf->color.rgb[ 0 ] = 0.78431f; - surf->color.rgb[ 1 ] = 0.78431f; - surf->color.rgb[ 2 ] = 0.78431f; - surf->diffuse.val = 1.0f; - surf->glossiness.val = 0.4f; - surf->bump.val = 1.0f; - surf->eta.val = 1.0f; - surf->sideflags = 1; - - /* remember where we started */ - - set_flen( 0 ); - pos = _pico_memstream_tell( fp ); - - /* names */ - - surf->name = getS0( fp ); - surf->srcname = getS0( fp ); - - /* first subchunk header */ - - id = getU4( fp ); - sz = getU2( fp ); - if ( 0 > get_flen() ) { - goto Fail; - } - - /* process subchunks as they're encountered */ - - while ( 1 ) { - sz += sz & 1; - set_flen( 0 ); - - switch ( id ) { - case ID_COLR: - surf->color.rgb[ 0 ] = getF4( fp ); - surf->color.rgb[ 1 ] = getF4( fp ); - surf->color.rgb[ 2 ] = getF4( fp ); - surf->color.eindex = getVX( fp ); - break; - - case ID_LUMI: - surf->luminosity.val = getF4( fp ); - surf->luminosity.eindex = getVX( fp ); - break; - - case ID_DIFF: - surf->diffuse.val = getF4( fp ); - surf->diffuse.eindex = getVX( fp ); - break; - - case ID_SPEC: - surf->specularity.val = getF4( fp ); - surf->specularity.eindex = getVX( fp ); - break; - - case ID_GLOS: - surf->glossiness.val = getF4( fp ); - surf->glossiness.eindex = getVX( fp ); - break; - - case ID_REFL: - surf->reflection.val.val = getF4( fp ); - surf->reflection.val.eindex = getVX( fp ); - break; - - case ID_RFOP: - surf->reflection.options = getU2( fp ); - break; - - case ID_RIMG: - surf->reflection.cindex = getVX( fp ); - break; - - case ID_RSAN: - surf->reflection.seam_angle = getF4( fp ); - break; - - case ID_TRAN: - surf->transparency.val.val = getF4( fp ); - surf->transparency.val.eindex = getVX( fp ); - break; - - case ID_TROP: - surf->transparency.options = getU2( fp ); - break; - - case ID_TIMG: - surf->transparency.cindex = getVX( fp ); - break; - - case ID_RIND: - surf->eta.val = getF4( fp ); - surf->eta.eindex = getVX( fp ); - break; - - case ID_TRNL: - surf->translucency.val = getF4( fp ); - surf->translucency.eindex = getVX( fp ); - break; - - case ID_BUMP: - surf->bump.val = getF4( fp ); - surf->bump.eindex = getVX( fp ); - break; - - case ID_SMAN: - surf->smooth = getF4( fp ); - break; - - case ID_SIDE: - surf->sideflags = getU2( fp ); - break; - - case ID_CLRH: - surf->color_hilite.val = getF4( fp ); - surf->color_hilite.eindex = getVX( fp ); - break; - - case ID_CLRF: - surf->color_filter.val = getF4( fp ); - surf->color_filter.eindex = getVX( fp ); - break; - - case ID_ADTR: - surf->add_trans.val = getF4( fp ); - surf->add_trans.eindex = getVX( fp ); - break; - - case ID_SHRP: - surf->dif_sharp.val = getF4( fp ); - surf->dif_sharp.eindex = getVX( fp ); - break; - - case ID_GVAL: - surf->glow.val = getF4( fp ); - surf->glow.eindex = getVX( fp ); - break; - - case ID_LINE: - surf->line.enabled = 1; - if ( sz >= 2 ) { - surf->line.flags = getU2( fp ); - } - if ( sz >= 6 ) { - surf->line.size.val = getF4( fp ); - } - if ( sz >= 8 ) { - surf->line.size.eindex = getVX( fp ); - } - break; - - case ID_ALPH: - surf->alpha_mode = getU2( fp ); - surf->alpha = getF4( fp ); - break; - - case ID_AVAL: - surf->alpha = getF4( fp ); - break; - - case ID_BLOK: - type = getU4( fp ); - - switch ( type ) { - case ID_IMAP: - case ID_PROC: - case ID_GRAD: - tex = lwGetTexture( fp, sz - 4, type ); - if ( !tex ) { - goto Fail; - } - if ( !add_texture( surf, tex ) ) { - lwFreeTexture( tex ); - } - set_flen( 4 + get_flen() ); - break; - case ID_SHDR: - shdr = lwGetShader( fp, sz - 4 ); - if ( !shdr ) { - goto Fail; - } - lwListInsert( (void **) &surf->shader, shdr, (void *) compare_shaders ); - ++surf->nshaders; - set_flen( 4 + get_flen() ); - break; - } - break; - - default: - break; - } - - /* error while reading current subchunk? */ - - rlen = get_flen(); - if ( rlen < 0 || rlen > sz ) { - goto Fail; - } - - /* skip unread parts of the current subchunk */ - - if ( rlen < sz ) { - _pico_memstream_seek( fp, sz - rlen, PICO_SEEK_CUR ); - } - - /* end of the SURF chunk? */ - - if ( cksize <= _pico_memstream_tell( fp ) - pos ) { - break; - } - - /* get the next subchunk header */ - - set_flen( 0 ); - id = getU4( fp ); - sz = getU2( fp ); - if ( 6 != get_flen() ) { - goto Fail; - } - } - - return surf; - -Fail: - if ( surf ) { - lwFreeSurface( surf ); - } - return NULL; -} diff --git a/tools/urt/libs/picomodel/lwo/vecmath.c b/tools/urt/libs/picomodel/lwo/vecmath.c deleted file mode 100644 index f4ada60..0000000 --- a/tools/urt/libs/picomodel/lwo/vecmath.c +++ /dev/null @@ -1,34 +0,0 @@ -/* - ====================================================================== - vecmath.c - - Basic vector and matrix functions. - - Ernie Wright 17 Sep 00 - ====================================================================== */ - -#include - - -float dot( float a[], float b[] ){ - return a[ 0 ] * b[ 0 ] + a[ 1 ] * b[ 1 ] + a[ 2 ] * b[ 2 ]; -} - - -void cross( float a[], float b[], float c[] ){ - c[ 0 ] = a[ 1 ] * b[ 2 ] - a[ 2 ] * b[ 1 ]; - c[ 1 ] = a[ 2 ] * b[ 0 ] - a[ 0 ] * b[ 2 ]; - c[ 2 ] = a[ 0 ] * b[ 1 ] - a[ 1 ] * b[ 0 ]; -} - - -void normalize( float v[] ){ - float r; - - r = ( float ) sqrt( dot( v, v ) ); - if ( r > 0 ) { - v[ 0 ] /= r; - v[ 1 ] /= r; - v[ 2 ] /= r; - } -} diff --git a/tools/urt/libs/picomodel/lwo/vmap.c b/tools/urt/libs/picomodel/lwo/vmap.c deleted file mode 100644 index 8976572..0000000 --- a/tools/urt/libs/picomodel/lwo/vmap.c +++ /dev/null @@ -1,266 +0,0 @@ -/* - ====================================================================== - vmap.c - - Vertex map functions for an LWO2 reader. - - Ernie Wright 17 Sep 00 - ====================================================================== */ - -#include "../picointernal.h" -#include "lwo2.h" - - -/* - ====================================================================== - lwFreeVMap() - - Free memory used by an lwVMap. - ====================================================================== */ - -void lwFreeVMap( lwVMap *vmap ){ - if ( vmap ) { - if ( vmap->name ) { - _pico_free( vmap->name ); - } - if ( vmap->vindex ) { - _pico_free( vmap->vindex ); - } - if ( vmap->pindex ) { - _pico_free( vmap->pindex ); - } - if ( vmap->val ) { - if ( vmap->val[ 0 ] ) { - _pico_free( vmap->val[ 0 ] ); - } - _pico_free( vmap->val ); - } - _pico_free( vmap ); - } -} - - -/* - ====================================================================== - lwGetVMap() - - Read an lwVMap from a VMAP or VMAD chunk in an LWO2. - ====================================================================== */ - -lwVMap *lwGetVMap( picoMemStream_t *fp, int cksize, int ptoffset, int poloffset, - int perpoly ){ - unsigned char *buf, *bp; - lwVMap *vmap; - float *f; - int i, j, npts, rlen; - - - /* read the whole chunk */ - - set_flen( 0 ); - buf = getbytes( fp, cksize ); - if ( !buf ) { - return NULL; - } - - vmap = _pico_calloc( 1, sizeof( lwVMap ) ); - if ( !vmap ) { - _pico_free( buf ); - return NULL; - } - - /* initialize the vmap */ - - vmap->perpoly = perpoly; - - bp = buf; - set_flen( 0 ); - vmap->type = sgetU4( &bp ); - vmap->dim = sgetU2( &bp ); - vmap->name = sgetS0( &bp ); - rlen = get_flen(); - - /* count the vmap records */ - - npts = 0; - while ( bp < buf + cksize ) { - i = sgetVX( &bp ); - if ( perpoly ) { - i = sgetVX( &bp ); - } - bp += vmap->dim * sizeof( float ); - ++npts; - } - - /* allocate the vmap */ - - vmap->nverts = npts; - vmap->vindex = _pico_calloc( npts, sizeof( int ) ); - if ( !vmap->vindex ) { - goto Fail; - } - if ( perpoly ) { - vmap->pindex = _pico_calloc( npts, sizeof( int ) ); - if ( !vmap->pindex ) { - goto Fail; - } - } - - if ( vmap->dim > 0 ) { - vmap->val = _pico_calloc( npts, sizeof( float * ) ); - if ( !vmap->val ) { - goto Fail; - } - f = _pico_alloc( npts * vmap->dim * sizeof( float ) ); - if ( !f ) { - goto Fail; - } - for ( i = 0; i < npts; i++ ) - vmap->val[ i ] = f + i * vmap->dim; - } - - /* fill in the vmap values */ - - bp = buf + rlen; - for ( i = 0; i < npts; i++ ) { - vmap->vindex[ i ] = sgetVX( &bp ); - if ( perpoly ) { - vmap->pindex[ i ] = sgetVX( &bp ); - } - for ( j = 0; j < vmap->dim; j++ ) - vmap->val[ i ][ j ] = sgetF4( &bp ); - } - - _pico_free( buf ); - return vmap; - -Fail: - if ( buf ) { - _pico_free( buf ); - } - lwFreeVMap( vmap ); - return NULL; -} - - -/* - ====================================================================== - lwGetPointVMaps() - - Fill in the lwVMapPt structure for each point. - ====================================================================== */ - -int lwGetPointVMaps( lwPointList *point, lwVMap *vmap ){ - lwVMap *vm; - int i, j, n; - - /* count the number of vmap values for each point */ - - vm = vmap; - while ( vm ) { - if ( !vm->perpoly ) { - for ( i = 0; i < vm->nverts; i++ ) - ++point->pt[ vm->vindex[ i ]].nvmaps; - } - vm = vm->next; - } - - /* allocate vmap references for each mapped point */ - - for ( i = 0; i < point->count; i++ ) { - if ( point->pt[ i ].nvmaps ) { - point->pt[ i ].vm = _pico_calloc( point->pt[ i ].nvmaps, sizeof( lwVMapPt ) ); - if ( !point->pt[ i ].vm ) { - return 0; - } - point->pt[ i ].nvmaps = 0; - } - } - - /* fill in vmap references for each mapped point */ - - vm = vmap; - while ( vm ) { - if ( !vm->perpoly ) { - for ( i = 0; i < vm->nverts; i++ ) { - j = vm->vindex[ i ]; - n = point->pt[ j ].nvmaps; - point->pt[ j ].vm[ n ].vmap = vm; - point->pt[ j ].vm[ n ].index = i; - ++point->pt[ j ].nvmaps; - } - } - vm = vm->next; - } - - return 1; -} - - -/* - ====================================================================== - lwGetPolyVMaps() - - Fill in the lwVMapPt structure for each polygon vertex. - ====================================================================== */ - -int lwGetPolyVMaps( lwPolygonList *polygon, lwVMap *vmap ){ - lwVMap *vm; - lwPolVert *pv; - int i, j; - - /* count the number of vmap values for each polygon vertex */ - - vm = vmap; - while ( vm ) { - if ( vm->perpoly ) { - for ( i = 0; i < vm->nverts; i++ ) { - for ( j = 0; j < polygon->pol[ vm->pindex[ i ]].nverts; j++ ) { - pv = &polygon->pol[ vm->pindex[ i ]].v[ j ]; - if ( vm->vindex[ i ] == pv->index ) { - ++pv->nvmaps; - break; - } - } - } - } - vm = vm->next; - } - - /* allocate vmap references for each mapped vertex */ - - for ( i = 0; i < polygon->count; i++ ) { - for ( j = 0; j < polygon->pol[ i ].nverts; j++ ) { - pv = &polygon->pol[ i ].v[ j ]; - if ( pv->nvmaps ) { - pv->vm = _pico_calloc( pv->nvmaps, sizeof( lwVMapPt ) ); - if ( !pv->vm ) { - return 0; - } - pv->nvmaps = 0; - } - } - } - - /* fill in vmap references for each mapped point */ - - vm = vmap; - while ( vm ) { - if ( vm->perpoly ) { - for ( i = 0; i < vm->nverts; i++ ) { - for ( j = 0; j < polygon->pol[ vm->pindex[ i ]].nverts; j++ ) { - pv = &polygon->pol[ vm->pindex[ i ]].v[ j ]; - if ( vm->vindex[ i ] == pv->index ) { - pv->vm[ pv->nvmaps ].vmap = vm; - pv->vm[ pv->nvmaps ].index = i; - ++pv->nvmaps; - break; - } - } - } - } - vm = vm->next; - } - - return 1; -} diff --git a/tools/urt/libs/picomodel/picointernal.c b/tools/urt/libs/picomodel/picointernal.c deleted file mode 100644 index 0b28e4d..0000000 --- a/tools/urt/libs/picomodel/picointernal.c +++ /dev/null @@ -1,1355 +0,0 @@ -/* ----------------------------------------------------------------------------- - - PicoModel Library - - Copyright (c) 2002, Randy Reddig & seaw0lf - All rights reserved. - - Redistribution and use in source and binary forms, with or without modification, - are permitted provided that the following conditions are met: - - Redistributions of source code must retain the above copyright notice, this list - of conditions and the following disclaimer. - - Redistributions in binary form must reproduce the above copyright notice, this - list of conditions and the following disclaimer in the documentation and/or - other materials provided with the distribution. - - Neither the names of the copyright holders nor the names of its contributors may - be used to endorse or promote products derived from this software without - specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR - ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - ----------------------------------------------------------------------------- */ - - - -/* marker */ -#define PICOINTERNAL_C - - - -/* todo: - * - fix p->curLine for parser routines. increased twice - */ - -/* dependencies */ -#include -#include "picointernal.h" - - - -/* function pointers */ -void *( *_pico_ptr_malloc )( size_t ) = malloc; -void ( *_pico_ptr_free )( void* ) = free; -void ( *_pico_ptr_load_file )( char*, unsigned char**, int* ) = NULL; -void ( *_pico_ptr_free_file )( void* ) = NULL; -void ( *_pico_ptr_print )( int, const char* ) = NULL; - -typedef union -{ - float f; - char c[4]; -} -floatSwapUnion; - -/* _pico_alloc: - * kludged memory allocation wrapper - */ -void *_pico_alloc( size_t size ){ - void *ptr; - - /* some sanity checks */ - if ( size == 0 ) { - return NULL; - } - if ( _pico_ptr_malloc == NULL ) { - return NULL; - } - - /* allocate memory */ - ptr = _pico_ptr_malloc( size ); - if ( ptr == NULL ) { - return NULL; - } - - /* zero out allocated memory */ - memset( ptr,0,size ); - - /* return pointer to allocated memory */ - return ptr; -} - -/* _pico_calloc: - * _pico_calloc wrapper - */ -void *_pico_calloc( size_t num, size_t size ){ - void *ptr; - - /* some sanity checks */ - if ( num == 0 || size == 0 ) { - return NULL; - } - if ( _pico_ptr_malloc == NULL ) { - return NULL; - } - - /* allocate memory */ - ptr = _pico_ptr_malloc( num * size ); - if ( ptr == NULL ) { - return NULL; - } - - /* zero out allocated memory */ - memset( ptr,0,num * size ); - - /* return pointer to allocated memory */ - return ptr; -} - -/* _pico_realloc: - * memory reallocation wrapper (note: only grows, - * but never shrinks or frees) - */ -void *_pico_realloc( void **ptr, size_t oldSize, size_t newSize ){ - void *ptr2; - - /* sanity checks */ - if ( ptr == NULL ) { - return NULL; - } - if ( newSize < oldSize ) { - return *ptr; - } - if ( _pico_ptr_malloc == NULL ) { - return NULL; - } - - /* allocate new pointer */ - ptr2 = _pico_alloc( newSize ); - if ( ptr2 == NULL ) { - return NULL; - } - - /* copy */ - if ( *ptr != NULL ) { - memcpy( ptr2, *ptr, oldSize ); - _pico_free( *ptr ); - } - - /* fix up and return */ - *ptr = ptr2; - return *ptr; -} - -/* _pico_clone_alloc: - * handy function for quick string allocation/copy. it clones - * the given string and returns a pointer to the new allocated - * clone (which must be freed by caller of course) or returns - * NULL on memory alloc or param errors. if 'size' is -1 the - * length of the input string is used, otherwise 'size' is used - * as custom clone size (the string is cropped to fit into mem - * if needed). -sea - */ -char *_pico_clone_alloc( const char *str ){ - char* cloned; - - /* sanity check */ - if ( str == NULL ) { - return NULL; - } - - /* allocate memory */ - cloned = _pico_alloc( strlen( str ) + 1 ); - if ( cloned == NULL ) { - return NULL; - } - - /* copy input string to cloned string */ - strcpy( cloned, str ); - - /* return ptr to cloned string */ - return cloned; -} - -/* _pico_free: - * wrapper around the free function pointer - */ -void _pico_free( void *ptr ){ - /* sanity checks */ - if ( ptr == NULL ) { - return; - } - if ( _pico_ptr_free == NULL ) { - return; - } - - /* free the allocated memory */ - _pico_ptr_free( ptr ); -} - -/* _pico_load_file: - * wrapper around the loadfile function pointer - */ -void _pico_load_file( char *name, unsigned char **buffer, int *bufSize ){ - /* sanity checks */ - if ( name == NULL ) { - *bufSize = -1; - return; - } - if ( _pico_ptr_load_file == NULL ) { - *bufSize = -1; - return; - } - /* do the actual call to read in the file; */ - /* BUFFER IS ALLOCATED BY THE EXTERNAL LOADFILE FUNC */ - _pico_ptr_load_file( name,buffer,bufSize ); -} - -/* _pico_free_file: - * wrapper around the file free function pointer - */ -void _pico_free_file( void *buffer ){ - /* sanity checks */ - if ( buffer == NULL ) { - return; - } - - /* use default free */ - if ( _pico_ptr_free_file == NULL ) { - free( buffer ); - return; - } - /* free the allocated file */ - _pico_ptr_free_file( buffer ); -} - -/* _pico_printf: - * wrapper around the print function pointer -sea - */ -void _pico_printf( int level, const char *format, ... ){ - char str[4096]; - va_list argptr; - - /* sanity checks */ - if ( format == NULL ) { - return; - } - if ( _pico_ptr_print == NULL ) { - return; - } - - /* format string */ - va_start( argptr,format ); - vsprintf( str,format,argptr ); - va_end( argptr ); - - /* remove linefeeds */ - if ( str[ strlen( str ) - 1 ] == '\n' ) { - str[ strlen( str ) - 1 ] = '\0'; - } - - /* do the actual call */ - _pico_ptr_print( level,str ); -} - -/* _pico_first_token: - * trims everything after the first whitespace-delimited token - */ - -void _pico_first_token( char *str ){ - if ( !str || !*str ) { - return; - } - while ( *str && !isspace( *str ) ) - *str++; - *str = '\0'; -} - -/* _pico_strltrim: - * left trims the given string -sea - */ -char *_pico_strltrim( char *str ){ - char *str1 = str, *str2 = str; - - while ( isspace( *str2 ) ) str2++; - if ( str2 != str ) { - while ( *str2 != '\0' ) /* fix: ydnar */ - *str1++ = *str2++; - } - return str; -} - -/* _pico_strrtrim: - * right trims the given string -sea - */ -char *_pico_strrtrim( char *str ){ - if ( str && *str ) { - char *str1 = str; - int allspace = 1; - - while ( *str1 ) - { - if ( allspace && !isspace( *str1 ) ) { - allspace = 0; - } - str1++; - } - if ( allspace ) { - *str = '\0'; - } - else { - str1--; - while ( ( isspace( *str1 ) ) && ( str1 >= str ) ) - *str1-- = '\0'; - } - } - return str; -} - -/* _pico_strlwr: - * pico internal string-to-lower routine. - */ -char *_pico_strlwr( char *str ){ - char *cp; - for ( cp = str; *cp; ++cp ) - { - if ( 'A' <= *cp && *cp <= 'Z' ) { - *cp += ( 'a' - 'A' ); - } - } - return str; -} - -/* _pico_strchcount: - * counts how often the given char appears in str. -sea - */ -int _pico_strchcount( char *str, int ch ){ - int count = 0; - while ( *str++ ) if ( *str == ch ) { - count++; - } - return count; -} - -void _pico_zero_bounds( picoVec3_t mins, picoVec3_t maxs ){ - int i; - for ( i = 0; i < 3; i++ ) - { - mins[i] = +999999; - maxs[i] = -999999; - } -} - -void _pico_expand_bounds( picoVec3_t p, picoVec3_t mins, picoVec3_t maxs ){ - int i; - for ( i = 0; i < 3; i++ ) - { - float value = p[i]; - if ( value < mins[i] ) { - mins[i] = value; - } - if ( value > maxs[i] ) { - maxs[i] = value; - } - } -} - -void _pico_zero_vec( picoVec3_t vec ){ - vec[ 0 ] = vec[ 1 ] = vec[ 2 ] = 0; -} - -void _pico_zero_vec2( picoVec2_t vec ){ - vec[ 0 ] = vec[ 1 ] = 0; -} - -void _pico_zero_vec4( picoVec4_t vec ){ - vec[ 0 ] = vec[ 1 ] = vec[ 2 ] = vec[ 3 ] = 0; -} - -void _pico_set_vec( picoVec3_t v, float a, float b, float c ){ - v[ 0 ] = a; - v[ 1 ] = b; - v[ 2 ] = c; -} - -void _pico_set_vec4( picoVec4_t v, float a, float b, float c, float d ){ - v[ 0 ] = a; - v[ 1 ] = b; - v[ 2 ] = c; - v[ 3 ] = d; -} - -void _pico_copy_vec( picoVec3_t src, picoVec3_t dest ){ - dest[ 0 ] = src[ 0 ]; - dest[ 1 ] = src[ 1 ]; - dest[ 2 ] = src[ 2 ]; -} - -void _pico_copy_vec2( picoVec2_t src, picoVec2_t dest ){ - dest[ 0 ] = src[ 0 ]; - dest[ 1 ] = src[ 1 ]; -} - -void _pico_copy_vec4( picoVec4_t src, picoVec4_t dest ){ - dest[ 0 ] = src[ 0 ]; - dest[ 1 ] = src[ 1 ]; - dest[ 2 ] = src[ 2 ]; - dest[ 3 ] = src[ 3 ]; -} - -/* ydnar */ -picoVec_t _pico_normalize_vec( picoVec3_t vec ){ - double len, ilen; - - len = sqrt( vec[ 0 ] * vec[ 0 ] + vec[ 1 ] * vec[ 1 ] + vec[ 2 ] * vec[ 2 ] ); - if ( len == 0.0 ) { - return 0.0; - } - ilen = 1.0 / len; - vec[ 0 ] *= (picoVec_t) ilen; - vec[ 1 ] *= (picoVec_t) ilen; - vec[ 2 ] *= (picoVec_t) ilen; - return (picoVec_t) len; -} - -void _pico_add_vec( picoVec3_t a, picoVec3_t b, picoVec3_t dest ){ - dest[ 0 ] = a[ 0 ] + b[ 0 ]; - dest[ 1 ] = a[ 1 ] + b[ 1 ]; - dest[ 2 ] = a[ 2 ] + b[ 2 ]; -} - -void _pico_subtract_vec( picoVec3_t a, picoVec3_t b, picoVec3_t dest ){ - dest[ 0 ] = a[ 0 ] - b[ 0 ]; - dest[ 1 ] = a[ 1 ] - b[ 1 ]; - dest[ 2 ] = a[ 2 ] - b[ 2 ]; -} - -void _pico_scale_vec( picoVec3_t v, float scale, picoVec3_t dest ){ - dest[ 0 ] = v[ 0 ] * scale; - dest[ 1 ] = v[ 1 ] * scale; - dest[ 2 ] = v[ 2 ] * scale; -} - -void _pico_scale_vec4( picoVec4_t v, float scale, picoVec4_t dest ){ - dest[ 0 ] = v[ 0 ] * scale; - dest[ 1 ] = v[ 1 ] * scale; - dest[ 2 ] = v[ 2 ] * scale; - dest[ 3 ] = v[ 3 ] * scale; -} - -picoVec_t _pico_dot_vec( picoVec3_t a, picoVec3_t b ){ - return a[ 0 ] * b[ 0 ] + a[ 1 ] * b[ 1 ] + a[ 2 ] * b[ 2 ]; -} - -void _pico_cross_vec( picoVec3_t a, picoVec3_t b, picoVec3_t dest ){ - dest[ 0 ] = a[ 1 ] * b[ 2 ] - a[ 2 ] * b[ 1 ]; - dest[ 1 ] = a[ 2 ] * b[ 0 ] - a[ 0 ] * b[ 2 ]; - dest[ 2 ] = a[ 0 ] * b[ 1 ] - a[ 1 ] * b[ 0 ]; -} - -picoVec_t _pico_calc_plane( picoVec4_t plane, picoVec3_t a, picoVec3_t b, picoVec3_t c ){ - picoVec3_t ba, ca; - - _pico_subtract_vec( b, a, ba ); - _pico_subtract_vec( c, a, ca ); - _pico_cross_vec( ca, ba, plane ); - plane[ 3 ] = _pico_dot_vec( a, plane ); - return _pico_normalize_vec( plane ); -} - -/* separate from _pico_set_vec4 */ -void _pico_set_color( picoColor_t c, int r, int g, int b, int a ){ - c[ 0 ] = r; - c[ 1 ] = g; - c[ 2 ] = b; - c[ 3 ] = a; -} - -void _pico_copy_color( picoColor_t src, picoColor_t dest ){ - dest[ 0 ] = src[ 0 ]; - dest[ 1 ] = src[ 1 ]; - dest[ 2 ] = src[ 2 ]; - dest[ 3 ] = src[ 3 ]; -} - -#ifdef __BIG_ENDIAN__ - -int _pico_big_long( int src ) { return src; } -short _pico_big_short( short src ) { return src; } -float _pico_big_float( float src ) { return src; } - -int _pico_little_long( int src ){ - return ( ( src & 0xFF000000 ) >> 24 ) | - ( ( src & 0x00FF0000 ) >> 8 ) | - ( ( src & 0x0000FF00 ) << 8 ) | - ( ( src & 0x000000FF ) << 24 ); -} - -short _pico_little_short( short src ){ - return ( ( src & 0xFF00 ) >> 8 ) | - ( ( src & 0x00FF ) << 8 ); -} - -float _pico_little_float( float src ){ - floatSwapUnion in,out; - in.f = src; - out.c[ 0 ] = in.c[ 3 ]; - out.c[ 1 ] = in.c[ 2 ]; - out.c[ 2 ] = in.c[ 1 ]; - out.c[ 3 ] = in.c[ 0 ]; - return out.f; -} -#else /*__BIG_ENDIAN__*/ - -int _pico_little_long( int src ) { return src; } -short _pico_little_short( short src ) { return src; } -float _pico_little_float( float src ) { return src; } - -int _pico_big_long( int src ){ - return ( ( src & 0xFF000000 ) >> 24 ) | - ( ( src & 0x00FF0000 ) >> 8 ) | - ( ( src & 0x0000FF00 ) << 8 ) | - ( ( src & 0x000000FF ) << 24 ); -} - -short _pico_big_short( short src ){ - return ( ( src & 0xFF00 ) >> 8 ) | - ( ( src & 0x00FF ) << 8 ); -} - -float _pico_big_float( float src ){ - floatSwapUnion in,out; - in.f = src; - out.c[ 0 ] = in.c[ 3 ]; - out.c[ 1 ] = in.c[ 2 ]; - out.c[ 2 ] = in.c[ 1 ]; - out.c[ 3 ] = in.c[ 0 ]; - return out.f; -} -#endif /*__BIG_ENDIAN__*/ - -/* _pico_stristr: - * case-insensitive strstr. -sea - */ -char *_pico_stristr( char *str, const char *substr ){ - const size_t sublen = strlen( substr ); - while ( *str ) - { - if ( !_pico_strnicmp( str,substr,sublen ) ) { - break; - } - str++; - } - if ( !( *str ) ) { - str = NULL; - } - return str; -} - -/* - _pico_unixify() - changes dos \ style path separators to / - */ - -void _pico_unixify( char *path ){ - if ( path == NULL ) { - return; - } - while ( *path ) - { - if ( *path == '\\' ) { - *path = '/'; - } - path++; - } -} - -/* _pico_nofname: - * removes file name portion from given file path and converts - * the directory separators to un*x style. returns 1 on success - * or 0 when 'destSize' was exceeded. -sea - */ -int _pico_nofname( const char *path, char *dest, int destSize ){ - int left = destSize; - char *temp = dest; - - while ( ( *dest = *path ) != '\0' ) - { - if ( *dest == '/' || *dest == '\\' ) { - temp = ( dest + 1 ); - *dest = '/'; - } - dest++; path++; - - if ( --left < 1 ) { - *temp = '\0'; - return 0; - } - } - *temp = '\0'; - return 1; -} - -/* _pico_nopath: - * returns ptr to filename portion in given path or an empty - * string otherwise. given 'path' is not altered. -sea - */ -const char *_pico_nopath( const char *path ){ - const char *src; - src = path + ( strlen( path ) - 1 ); - - if ( path == NULL ) { - return ""; - } - if ( !strchr( path,'/' ) && !strchr( path,'\\' ) ) { - return ( path ); - } - - while ( ( src-- ) != path ) - { - if ( *src == '/' || *src == '\\' ) { - return ( ++src ); - } - } - return ""; -} - -/* _pico_setfext: - * sets/changes the file extension for the given filename - * or filepath's filename portion. the given 'path' *is* - * altered. leave 'ext' empty to remove extension. -sea - */ -char *_pico_setfext( char *path, const char *ext ){ - char *src; - int remfext = 0; - - src = path + ( strlen( path ) - 1 ); - - if ( ext == NULL ) { - ext = ""; - } - if ( strlen( ext ) < 1 ) { - remfext = 1; - } - if ( strlen( path ) < 1 ) { - return path; - } - - while ( ( src-- ) != path ) - { - if ( *src == '/' || *src == '\\' ) { - return path; - } - - if ( *src == '.' ) { - if ( remfext ) { - *src = '\0'; - return path; - } - *( ++src ) = '\0'; - break; - } - } - strcat( path,ext ); - return path; -} - -/* _pico_getline: - * extracts one line from the given buffer and stores it in dest. - * returns -1 on error or the length of the line on success. i've - * removed string trimming here. this can be done manually by the - * calling func. - */ -int _pico_getline( char *buf, int bufsize, char *dest, int destsize ){ - int pos; - - /* check output */ - if ( dest == NULL || destsize < 1 ) { - return -1; - } - memset( dest,0,destsize ); - - /* check input */ - if ( buf == NULL || bufsize < 1 ) { - return -1; - } - - /* get next line */ - for ( pos = 0; pos < bufsize && pos < destsize; pos++ ) - { - if ( buf[pos] == '\n' ) { - pos++; break; - } - dest[pos] = buf[pos]; - } - /* terminate dest and return */ - dest[pos] = '\0'; - return pos; -} - -/* _pico_parse_skip_white: - * skips white spaces in current pico parser, sets *hasLFs - * to 1 if linefeeds were skipped, and either returns the - * parser's cursor pointer or NULL on error. -sea - */ -void _pico_parse_skip_white( picoParser_t *p, int *hasLFs ){ - /* sanity checks */ - if ( p == NULL || p->cursor == NULL ) { - return; - } - - /* skin white spaces */ - while ( 1 ) - { - /* sanity checks */ - if ( p->cursor < p->buffer || - p->cursor >= p->max ) { - return; - } - /* break for chars other than white spaces */ - if ( *p->cursor > 0x20 ) { - break; - } - if ( *p->cursor == 0x00 ) { - return; - } - - /* a bit of linefeed handling */ - if ( *p->cursor == '\n' ) { - *hasLFs = 1; - p->curLine++; - } - /* go to next character */ - p->cursor++; - } -} - -/* _pico_new_parser: - * allocates a new ascii parser object. - */ -picoParser_t *_pico_new_parser( picoByte_t *buffer, int bufSize ){ - picoParser_t *p; - - /* sanity check */ - if ( buffer == NULL || bufSize <= 0 ) { - return NULL; - } - - /* allocate reader */ - p = _pico_alloc( sizeof( picoParser_t ) ); - if ( p == NULL ) { - return NULL; - } - memset( p,0,sizeof( picoParser_t ) ); - - /* allocate token space */ - p->tokenSize = 0; - p->tokenMax = 1024; - p->token = _pico_alloc( p->tokenMax ); - if ( p->token == NULL ) { - _pico_free( p ); - return NULL; - } - /* setup */ - p->buffer = buffer; - p->cursor = buffer; - p->bufSize = bufSize; - p->max = p->buffer + bufSize; - p->curLine = 1; /* sea: new */ - - /* return ptr to parser */ - return p; -} - -/* _pico_free_parser: - * frees an existing pico parser object. - */ -void _pico_free_parser( picoParser_t *p ){ - /* sanity check */ - if ( p == NULL ) { - return; - } - - /* free the parser */ - if ( p->token != NULL ) { - _pico_free( p->token ); - } - _pico_free( p ); -} - -/* _pico_parse_ex: - * reads the next token from given pico parser object. if param - * 'allowLFs' is 1 it will read beyond linefeeds and return 0 when - * the EOF is reached. if 'allowLFs' is 0 it will return 0 when - * the EOL is reached. if 'handleQuoted' is 1 the parser function - * will handle "quoted" strings and return the data between the - * quotes as token. returns 0 on end/error or 1 on success. -sea - */ -int _pico_parse_ex( picoParser_t *p, int allowLFs, int handleQuoted ){ - int hasLFs = 0; - char *old; - - /* sanity checks */ - if ( p == NULL || p->buffer == NULL || - p->cursor < p->buffer || - p->cursor >= p->max ) { - return 0; - } - /* clear parser token */ - p->tokenSize = 0; - p->token[ 0 ] = '\0'; - old = p->cursor; - - /* skip whitespaces */ - while ( p->cursor < p->max && *p->cursor <= 32 ) - { - if ( *p->cursor == '\n' ) { - p->curLine++; - hasLFs++; - } - p->cursor++; - } - /* return if we're not allowed to go beyond lfs */ - if ( ( hasLFs > 0 ) && !allowLFs ) { - p->cursor = old; - return 0; - } - /* get next quoted string */ - if ( *p->cursor == '\"' && handleQuoted ) { - p->cursor++; - while ( p->cursor < p->max && *p->cursor ) - { - if ( *p->cursor == '\\' ) { - if ( *( p->cursor + 1 ) == '"' ) { - p->cursor++; - } - p->token[ p->tokenSize++ ] = *p->cursor++; - continue; - } - else if ( *p->cursor == '\"' ) { - p->cursor++; - break; - } - else if ( *p->cursor == '\n' ) { - p->curLine++; - } - p->token[ p->tokenSize++ ] = *p->cursor++; - } - /* terminate token */ - p->token[ p->tokenSize ] = '\0'; - return 1; - } - /* otherwise get next word */ - while ( p->cursor < p->max && *p->cursor > 32 ) - { - if ( *p->cursor == '\n' ) { - p->curLine++; - } - p->token[ p->tokenSize++ ] = *p->cursor++; - } - /* terminate token */ - p->token[ p->tokenSize ] = '\0'; - return 1; -} - -/* _pico_parse_first: - * reads the first token from the next line and returns - * a pointer to it. returns NULL on EOL or EOF. -sea - */ -char *_pico_parse_first( picoParser_t *p ){ - /* sanity check */ - if ( p == NULL ) { - return NULL; - } - - /* try to read next token (with lfs & quots) */ - if ( !_pico_parse_ex( p,1,1 ) ) { - return NULL; - } - - /* return ptr to the token string */ - return p->token; -} - -/* _pico_parse: - * reads the next token from the parser and returns a pointer - * to it. quoted strings are handled as usual. returns NULL - * on EOL or EOF. -sea - */ -char *_pico_parse( picoParser_t *p, int allowLFs ){ - /* sanity check */ - if ( p == NULL ) { - return NULL; - } - - /* try to read next token (with quots) */ - if ( !_pico_parse_ex( p,allowLFs,1 ) ) { - return NULL; - } - - /* return ptr to the token string */ - return p->token; -} - -/* _pico_parse_skip_rest: - * skips the rest of the current line in parser. - */ -void _pico_parse_skip_rest( picoParser_t *p ){ - while ( _pico_parse_ex( p,0,0 ) ) ; -} - -/* _pico_parse_skip_braced: - * parses/skips over a braced section. returns 1 on success - * or 0 on error (when there was no closing bracket and the - * end of buffer was reached or when the opening bracket was - * missing). - */ -int _pico_parse_skip_braced( picoParser_t *p ){ - int firstToken = 1; - int level; - - /* sanity check */ - if ( p == NULL ) { - return 0; - } - - /* set the initial level for parsing */ - level = 0; - - /* skip braced section */ - while ( 1 ) - { - /* read next token (lfs allowed) */ - if ( !_pico_parse_ex( p,1,1 ) ) { - /* end of parser buffer reached */ - return 0; - } - /* first token must be an opening bracket */ - if ( firstToken && p->token[0] != '{' ) { - /* opening bracket missing */ - return 0; - } - /* we only check this once */ - firstToken = 0; - - /* update level */ - if ( p->token[1] == '\0' ) { - if ( p->token[0] == '{' ) { - level++; - } - if ( p->token[0] == '}' ) { - level--; - } - } - /* break if we're back at our starting level */ - if ( level == 0 ) { - break; - } - } - /* successfully skipped braced section */ - return 1; -} - -int _pico_parse_check( picoParser_t *p, int allowLFs, char *str ){ - if ( !_pico_parse_ex( p,allowLFs,1 ) ) { - return 0; - } - if ( !strcmp( p->token,str ) ) { - return 1; - } - return 0; -} - -int _pico_parse_checki( picoParser_t *p, int allowLFs, char *str ){ - if ( !_pico_parse_ex( p,allowLFs,1 ) ) { - return 0; - } - if ( !_pico_stricmp( p->token,str ) ) { - return 1; - } - return 0; -} - -int _pico_parse_int( picoParser_t *p, int *out ){ - char *token; - - /* sanity checks */ - if ( p == NULL || out == NULL ) { - return 0; - } - - /* get token and turn it into an integer */ - *out = 0; - token = _pico_parse( p,0 ); - if ( token == NULL ) { - return 0; - } - *out = atoi( token ); - - /* success */ - return 1; -} - -int _pico_parse_int_def( picoParser_t *p, int *out, int def ){ - char *token; - - /* sanity checks */ - if ( p == NULL || out == NULL ) { - return 0; - } - - /* get token and turn it into an integer */ - *out = def; - token = _pico_parse( p,0 ); - if ( token == NULL ) { - return 0; - } - *out = atoi( token ); - - /* success */ - return 1; -} - -int _pico_parse_float( picoParser_t *p, float *out ){ - char *token; - - /* sanity checks */ - if ( p == NULL || out == NULL ) { - return 0; - } - - /* get token and turn it into a float */ - *out = 0.0f; - token = _pico_parse( p,0 ); - if ( token == NULL ) { - return 0; - } - *out = (float) atof( token ); - - /* success */ - return 1; -} - -int _pico_parse_float_def( picoParser_t *p, float *out, float def ){ - char *token; - - /* sanity checks */ - if ( p == NULL || out == NULL ) { - return 0; - } - - /* get token and turn it into a float */ - *out = def; - token = _pico_parse( p,0 ); - if ( token == NULL ) { - return 0; - } - *out = (float) atof( token ); - - /* success */ - return 1; -} - -int _pico_parse_vec( picoParser_t *p, picoVec3_t out ){ - char *token; - int i; - - /* sanity checks */ - if ( p == NULL || out == NULL ) { - return 0; - } - - /* zero out outination vector */ - _pico_zero_vec( out ); - - /* parse three vector components */ - for ( i = 0; i < 3; i++ ) - { - token = _pico_parse( p,0 ); - if ( token == NULL ) { - _pico_zero_vec( out ); - return 0; - } - out[ i ] = (float) atof( token ); - } - /* success */ - return 1; -} - -int _pico_parse_vec_def( picoParser_t *p, picoVec3_t out, picoVec3_t def ){ - char *token; - int i; - - /* sanity checks */ - if ( p == NULL || out == NULL ) { - return 0; - } - - /* assign default vector value */ - _pico_copy_vec( def,out ); - - /* parse three vector components */ - for ( i = 0; i < 3; i++ ) - { - token = _pico_parse( p,0 ); - if ( token == NULL ) { - _pico_copy_vec( def,out ); - return 0; - } - out[ i ] = (float) atof( token ); - } - /* success */ - return 1; -} - -int _pico_parse_vec2( picoParser_t *p, picoVec2_t out ){ - char *token; - int i; - - /* sanity checks */ - if ( p == NULL || out == NULL ) { - return 0; - } - - /* zero out outination vector */ - _pico_zero_vec2( out ); - - /* parse two vector components */ - for ( i = 0; i < 2; i++ ) - { - token = _pico_parse( p,0 ); - if ( token == NULL ) { - _pico_zero_vec2( out ); - return 0; - } - out[ i ] = (float) atof( token ); - } - /* success */ - return 1; -} - -int _pico_parse_vec2_def( picoParser_t *p, picoVec2_t out, picoVec2_t def ){ - char *token; - int i; - - /* sanity checks */ - if ( p == NULL || out == NULL ) { - return 0; - } - - /* assign default vector value */ - _pico_copy_vec2( def,out ); - - /* parse two vector components */ - for ( i = 0; i < 2; i++ ) - { - token = _pico_parse( p,0 ); - if ( token == NULL ) { - _pico_copy_vec2( def,out ); - return 0; - } - out[ i ] = (float) atof( token ); - } - /* success */ - return 1; -} - -int _pico_parse_vec4( picoParser_t *p, picoVec4_t out ){ - char *token; - int i; - - /* sanity checks */ - if ( p == NULL || out == NULL ) { - return 0; - } - - /* zero out outination vector */ - _pico_zero_vec4( out ); - - /* parse four vector components */ - for ( i = 0; i < 4; i++ ) - { - token = _pico_parse( p,0 ); - if ( token == NULL ) { - _pico_zero_vec4( out ); - return 0; - } - out[ i ] = (float) atof( token ); - } - /* success */ - return 1; -} - -int _pico_parse_vec4_def( picoParser_t *p, picoVec4_t out, picoVec4_t def ){ - char *token; - int i; - - /* sanity checks */ - if ( p == NULL || out == NULL ) { - return 0; - } - - /* assign default vector value */ - _pico_copy_vec4( def,out ); - - /* parse four vector components */ - for ( i = 0; i < 4; i++ ) - { - token = _pico_parse( p,0 ); - if ( token == NULL ) { - _pico_copy_vec4( def,out ); - return 0; - } - out[ i ] = (float) atof( token ); - } - /* success */ - return 1; -} - -/* _pico_new_memstream: - * allocates a new memorystream object. - */ -picoMemStream_t *_pico_new_memstream( picoByte_t *buffer, int bufSize ){ - picoMemStream_t *s; - - /* sanity check */ - if ( buffer == NULL || bufSize <= 0 ) { - return NULL; - } - - /* allocate stream */ - s = _pico_alloc( sizeof( picoMemStream_t ) ); - if ( s == NULL ) { - return NULL; - } - memset( s,0,sizeof( picoMemStream_t ) ); - - /* setup */ - s->buffer = buffer; - s->curPos = buffer; - s->bufSize = bufSize; - s->flag = 0; - - /* return ptr to stream */ - return s; -} - -/* _pico_free_memstream: - * frees an existing pico memorystream object. - */ -void _pico_free_memstream( picoMemStream_t *s ){ - /* sanity check */ - if ( s == NULL ) { - return; - } - - /* free the stream */ - _pico_free( s ); -} - -/* _pico_memstream_read: - * reads data from a pico memorystream into a buffer. - */ -int _pico_memstream_read( picoMemStream_t *s, void *buffer, int len ){ - int ret = 1; - - /* sanity checks */ - if ( s == NULL || buffer == NULL ) { - return 0; - } - - if ( s->curPos + len > s->buffer + s->bufSize ) { - s->flag |= PICO_IOEOF; - len = s->buffer + s->bufSize - s->curPos; - ret = 0; - } - - /* read the data */ - memcpy( buffer, s->curPos, len ); - s->curPos += len; - return ret; -} - -/* _pico_memstream_read: - * reads a character from a pico memorystream - */ -int _pico_memstream_getc( picoMemStream_t *s ){ - int c = 0; - - /* sanity check */ - if ( s == NULL ) { - return -1; - } - - /* read the character */ - if ( _pico_memstream_read( s, &c, 1 ) == 0 ) { - return -1; - } - - return c; -} - -/* _pico_memstream_seek: - * sets the current read position to a different location - */ -int _pico_memstream_seek( picoMemStream_t *s, long offset, int origin ){ - int overflow; - - /* sanity check */ - if ( s == NULL ) { - return -1; - } - - if ( origin == PICO_SEEK_SET ) { - s->curPos = s->buffer + offset; - overflow = s->curPos - ( s->buffer + s->bufSize ); - if ( overflow > 0 ) { - s->curPos = s->buffer + s->bufSize; - return offset - overflow; - } - return 0; - } - else if ( origin == PICO_SEEK_CUR ) { - s->curPos += offset; - overflow = s->curPos - ( s->buffer + s->bufSize ); - if ( overflow > 0 ) { - s->curPos = s->buffer + s->bufSize; - return offset - overflow; - } - return 0; - } - else if ( origin == PICO_SEEK_END ) { - s->curPos = ( s->buffer + s->bufSize ) - offset; - overflow = s->buffer - s->curPos; - if ( overflow > 0 ) { - s->curPos = s->buffer; - return offset - overflow; - } - return 0; - } - - return -1; -} - -/* _pico_memstream_tell: - * returns the current read position in the pico memorystream - */ -long _pico_memstream_tell( picoMemStream_t *s ){ - /* sanity check */ - if ( s == NULL ) { - return -1; - } - - return s->curPos - s->buffer; -} diff --git a/tools/urt/libs/picomodel/picointernal.h b/tools/urt/libs/picomodel/picointernal.h deleted file mode 100644 index 6cc9d52..0000000 --- a/tools/urt/libs/picomodel/picointernal.h +++ /dev/null @@ -1,206 +0,0 @@ -/* ----------------------------------------------------------------------------- - - PicoModel Library - - Copyright (c) 2002, Randy Reddig & seaw0lf - All rights reserved. - - Redistribution and use in source and binary forms, with or without modification, - are permitted provided that the following conditions are met: - - Redistributions of source code must retain the above copyright notice, this list - of conditions and the following disclaimer. - - Redistributions in binary form must reproduce the above copyright notice, this - list of conditions and the following disclaimer in the documentation and/or - other materials provided with the distribution. - - Neither the names of the copyright holders nor the names of its contributors may - be used to endorse or promote products derived from this software without - specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR - ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - ----------------------------------------------------------------------------- */ - - - -/* marker */ -#ifndef PICOINTERNAL_H -#define PICOINTERNAL_H - -#ifdef __cplusplus -extern "C" -{ -#endif - - -/* dependencies */ -#include -#include -#include -#include -#include -#include - -#include "picomodel.h" - - -/* os dependent replacements */ -#if WIN32 || _WIN32 - #define _pico_stricmp stricmp - #define _pico_strnicmp strnicmp -#else - #define _pico_stricmp strcasecmp - #define _pico_strnicmp strncasecmp -#endif - - -/* constants */ -#define PICO_PI 3.14159265358979323846 - -#define PICO_SEEK_SET 0 -#define PICO_SEEK_CUR 1 -#define PICO_SEEK_END 2 - -#define PICO_IOEOF 1 -#define PICO_IOERR 2 - -/* types */ -typedef struct picoParser_s -{ - char *buffer; - int bufSize; - char *token; - int tokenSize; - int tokenMax; - char *cursor; - char *max; - int curLine; -} -picoParser_t; - -typedef struct picoMemStream_s -{ - picoByte_t *buffer; - int bufSize; - picoByte_t *curPos; - int flag; -} -picoMemStream_t; - - -/* variables */ -extern const picoModule_t *picoModules[]; - -extern void *( *_pico_ptr_malloc )( size_t ); -extern void ( *_pico_ptr_free )( void* ); -extern void ( *_pico_ptr_load_file )( char*, unsigned char**, int* ); -extern void ( *_pico_ptr_free_file )( void* ); -extern void ( *_pico_ptr_print )( int, const char* ); - - - -/* prototypes */ - -/* memory */ -void *_pico_alloc( size_t size ); -void *_pico_calloc( size_t num, size_t size ); -void *_pico_realloc( void **ptr, size_t oldSize, size_t newSize ); -char *_pico_clone_alloc( const char *str ); -void _pico_free( void *ptr ); - -/* files */ -void _pico_load_file( char *name, unsigned char **buffer, int *bufSize ); -void _pico_free_file( void *buffer ); - -/* strings */ -void _pico_first_token( char *str ); -char *_pico_strltrim( char *str ); -char *_pico_strrtrim( char *str ); -int _pico_strchcount( char *str, int ch ); -void _pico_printf( int level, const char *format, ... ); -char *_pico_stristr( char *str, const char *substr ); -void _pico_unixify( char *path ); -int _pico_nofname( const char *path, char *dest, int destSize ); -const char *_pico_nopath( const char *path ); -char *_pico_setfext( char *path, const char *ext ); -int _pico_getline( char *buf, int bufsize, char *dest, int destsize ); -char *_pico_strlwr( char *str ); - -/* vectors */ -void _pico_zero_bounds( picoVec3_t mins, picoVec3_t maxs ); -void _pico_expand_bounds( picoVec3_t p, picoVec3_t mins, picoVec3_t maxs ); -void _pico_zero_vec( picoVec3_t vec ); -void _pico_zero_vec2( picoVec2_t vec ); -void _pico_zero_vec4( picoVec4_t vec ); -void _pico_set_vec( picoVec3_t v, float a, float b, float c ); -void _pico_set_vec4( picoVec4_t v, float a, float b, float c, float d ); -void _pico_set_color( picoColor_t c, int r, int g, int b, int a ); -void _pico_copy_color( picoColor_t src, picoColor_t dest ); -void _pico_copy_vec( picoVec3_t src, picoVec3_t dest ); -void _pico_copy_vec2( picoVec2_t src, picoVec2_t dest ); -picoVec_t _pico_normalize_vec( picoVec3_t vec ); -void _pico_add_vec( picoVec3_t a, picoVec3_t b, picoVec3_t dest ); -void _pico_subtract_vec( picoVec3_t a, picoVec3_t b, picoVec3_t dest ); -picoVec_t _pico_dot_vec( picoVec3_t a, picoVec3_t b ); -void _pico_cross_vec( picoVec3_t a, picoVec3_t b, picoVec3_t dest ); -picoVec_t _pico_calc_plane( picoVec4_t plane, picoVec3_t a, picoVec3_t b, picoVec3_t c ); -void _pico_scale_vec( picoVec3_t v, float scale, picoVec3_t dest ); -void _pico_scale_vec4( picoVec4_t v, float scale, picoVec4_t dest ); - -/* endian */ -int _pico_big_long( int src ); -short _pico_big_short( short src ); -float _pico_big_float( float src ); - -int _pico_little_long( int src ); -short _pico_little_short( short src ); -float _pico_little_float( float src ); - -/* pico ascii parser */ -picoParser_t *_pico_new_parser( picoByte_t *buffer, int bufSize ); -void _pico_free_parser( picoParser_t *p ); -int _pico_parse_ex( picoParser_t *p, int allowLFs, int handleQuoted ); -char *_pico_parse_first( picoParser_t *p ); -char *_pico_parse( picoParser_t *p, int allowLFs ); -void _pico_parse_skip_rest( picoParser_t *p ); -int _pico_parse_skip_braced( picoParser_t *p ); -int _pico_parse_check( picoParser_t *p, int allowLFs, char *str ); -int _pico_parse_checki( picoParser_t *p, int allowLFs, char *str ); -int _pico_parse_int( picoParser_t *p, int *out ); -int _pico_parse_int_def( picoParser_t *p, int *out, int def ); -int _pico_parse_float( picoParser_t *p, float *out ); -int _pico_parse_float_def( picoParser_t *p, float *out, float def ); -int _pico_parse_vec( picoParser_t *p, picoVec3_t out ); -int _pico_parse_vec_def( picoParser_t *p, picoVec3_t out, picoVec3_t def ); -int _pico_parse_vec2( picoParser_t *p, picoVec2_t out ); -int _pico_parse_vec2_def( picoParser_t *p, picoVec2_t out, picoVec2_t def ); -int _pico_parse_vec4( picoParser_t *p, picoVec4_t out ); -int _pico_parse_vec4_def( picoParser_t *p, picoVec4_t out, picoVec4_t def ); - -/* pico memory stream */ -picoMemStream_t *_pico_new_memstream( picoByte_t *buffer, int bufSize ); -void _pico_free_memstream( picoMemStream_t *s ); -int _pico_memstream_read( picoMemStream_t *s, void *buffer, int len ); -int _pico_memstream_getc( picoMemStream_t *s ); -int _pico_memstream_seek( picoMemStream_t *s, long offset, int origin ); -long _pico_memstream_tell( picoMemStream_t *s ); -#define _pico_memstream_eof( _pico_memstream ) ( ( _pico_memstream )->flag & PICO_IOEOF ) -#define _pico_memstream_error( _pico_memstream ) ( ( _pico_memstream )->flag & PICO_IOERR ) - -/* end marker */ -#ifdef __cplusplus -} -#endif - -#endif diff --git a/tools/urt/libs/picomodel/picomodel.c b/tools/urt/libs/picomodel/picomodel.c deleted file mode 100644 index 39a570f..0000000 --- a/tools/urt/libs/picomodel/picomodel.c +++ /dev/null @@ -1,2316 +0,0 @@ -/* ----------------------------------------------------------------------------- - - PicoModel Library - - Copyright (c) 2002, Randy Reddig & seaw0lf - All rights reserved. - - Redistribution and use in source and binary forms, with or without modification, - are permitted provided that the following conditions are met: - - Redistributions of source code must retain the above copyright notice, this list - of conditions and the following disclaimer. - - Redistributions in binary form must reproduce the above copyright notice, this - list of conditions and the following disclaimer in the documentation and/or - other materials provided with the distribution. - - Neither the names of the copyright holders nor the names of its contributors may - be used to endorse or promote products derived from this software without - specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR - ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - ----------------------------------------------------------------------------- */ - - - -/* marker */ -#define PICOMODEL_C - - - -/* dependencies */ -#include "picointernal.h" - - - -/* - PicoInit() - initializes the picomodel library - */ - -int PicoInit( void ){ - /* successfully initialized -sea */ - return 1; -} - - - -/* - PicoShutdown() - shuts the pico model library down - */ - -void PicoShutdown( void ){ - /* do something interesting here in the future */ - return; -} - - - -/* - PicoError() - returns last picomodel error code (see PME_* defines) - */ - -int PicoError( void ){ - /* todo: do something here */ - return 0; -} - - - -/* - PicoSetMallocFunc() - sets the ptr to the malloc function - */ - -void PicoSetMallocFunc( void *( *func )( size_t ) ){ - if ( func != NULL ) { - _pico_ptr_malloc = func; - } -} - - - -/* - PicoSetFreeFunc() - sets the ptr to the free function - */ - -void PicoSetFreeFunc( void ( *func )( void* ) ){ - if ( func != NULL ) { - _pico_ptr_free = func; - } -} - - - -/* - PicoSetLoadFileFunc() - sets the ptr to the file load function - */ - -void PicoSetLoadFileFunc( void ( *func )( char*, unsigned char**, int* ) ){ - if ( func != NULL ) { - _pico_ptr_load_file = func; - } -} - - - -/* - PicoSetFreeFileFunc() - sets the ptr to the free function - */ - -void PicoSetFreeFileFunc( void ( *func )( void* ) ){ - if ( func != NULL ) { - _pico_ptr_free_file = func; - } -} - - - -/* - PicoSetPrintFunc() - sets the ptr to the print function - */ - -void PicoSetPrintFunc( void ( *func )( int, const char* ) ){ - if ( func != NULL ) { - _pico_ptr_print = func; - } -} - - - -picoModel_t *PicoModuleLoadModel( const picoModule_t* pm, char* fileName, picoByte_t* buffer, int bufSize, int frameNum ){ - char *modelFileName, *remapFileName; - - /* see whether this module can load the model file or not */ - if ( pm->canload( fileName, buffer, bufSize ) == PICO_PMV_OK ) { - /* use loader provided by module to read the model data */ - picoModel_t* model = pm->load( fileName, frameNum, buffer, bufSize ); - if ( model == NULL ) { - _pico_free_file( buffer ); - return NULL; - } - - /* assign pointer to file format module */ - model->module = pm; - - /* get model file name */ - modelFileName = PicoGetModelFileName( model ); - - /* apply model remappings from .remap */ - if ( strlen( modelFileName ) ) { - /* alloc copy of model file name */ - remapFileName = _pico_alloc( strlen( modelFileName ) + 20 ); - if ( remapFileName != NULL ) { - /* copy model file name and change extension */ - strcpy( remapFileName, modelFileName ); - _pico_setfext( remapFileName, "remap" ); - - /* try to remap model; we don't handle the result */ - PicoRemapModel( model, remapFileName ); - - /* free the remap file name string */ - _pico_free( remapFileName ); - } - } - - return model; - } - - return NULL; -} - -/* - PicoLoadModel() - the meat and potatoes function - */ - -picoModel_t *PicoLoadModel( char *fileName, int frameNum ){ - const picoModule_t **modules, *pm; - picoModel_t *model; - picoByte_t *buffer; - int bufSize; - - - /* init */ - model = NULL; - - /* make sure we've got a file name */ - if ( fileName == NULL ) { - _pico_printf( PICO_ERROR, "PicoLoadModel: No filename given (fileName == NULL)" ); - return NULL; - } - - /* load file data (buffer is allocated by host app) */ - _pico_load_file( fileName, &buffer, &bufSize ); - if ( bufSize < 0 ) { - _pico_printf( PICO_ERROR, "PicoLoadModel: Failed loading model %s", fileName ); - return NULL; - } - - /* get ptr to list of supported modules */ - modules = PicoModuleList( NULL ); - - /* run it through the various loader functions and try */ - /* to find a loader that fits the given file data */ - for ( ; *modules != NULL; modules++ ) - { - /* get module */ - pm = *modules; - - /* sanity check */ - if ( pm == NULL ) { - break; - } - - /* module must be able to load */ - if ( pm->canload == NULL || pm->load == NULL ) { - continue; - } - - model = PicoModuleLoadModel( pm, fileName, buffer, bufSize, frameNum ); - if ( model != NULL ) { - /* model was loaded, so break out of loop */ - break; - } - } - - /* free memory used by file buffer */ - if ( buffer ) { - _pico_free_file( buffer ); - } - - /* return */ - return model; -} - -picoModel_t *PicoModuleLoadModelStream( const picoModule_t* module, void* inputStream, PicoInputStreamReadFunc inputStreamRead, size_t streamLength, int frameNum ){ - picoModel_t *model; - picoByte_t *buffer; - int bufSize; - - - /* init */ - model = NULL; - - if ( inputStream == NULL ) { - _pico_printf( PICO_ERROR, "PicoLoadModel: invalid input stream (inputStream == NULL)" ); - return NULL; - } - - if ( inputStreamRead == NULL ) { - _pico_printf( PICO_ERROR, "PicoLoadModel: invalid input stream (inputStreamRead == NULL)" ); - return NULL; - } - - buffer = _pico_alloc( streamLength + 1 ); - - bufSize = (int)inputStreamRead( inputStream, buffer, streamLength ); - buffer[bufSize] = '\0'; - - { - // dummy filename - char fileName[128]; - fileName[0] = '.'; - strncpy( fileName + 1, module->defaultExts[0], 126 ); - fileName[127] = '\0'; - model = PicoModuleLoadModel( module, fileName, buffer, bufSize, frameNum ); - } - - _pico_free( buffer ); - - /* return */ - return model; -} - - -/* ---------------------------------------------------------------------------- - models - ---------------------------------------------------------------------------- */ - -/* - PicoNewModel() - creates a new pico model - */ - -picoModel_t *PicoNewModel( void ){ - picoModel_t *model; - - /* allocate */ - model = _pico_alloc( sizeof( picoModel_t ) ); - if ( model == NULL ) { - return NULL; - } - - /* clear */ - memset( model,0,sizeof( picoModel_t ) ); - - /* model set up */ - _pico_zero_bounds( model->mins,model->maxs ); - - /* set initial frame count to 1 -sea */ - model->numFrames = 1; - - /* return ptr to new model */ - return model; -} - - - -/* - PicoFreeModel() - frees a model and all associated data - */ - -void PicoFreeModel( picoModel_t *model ){ - int i; - - - /* sanity check */ - if ( model == NULL ) { - return; - } - - /* free bits */ - if ( model->name ) { - _pico_free( model->name ); - } - - if ( model->fileName ) { - _pico_free( model->fileName ); - } - - /* free shaders */ - for ( i = 0; i < model->numShaders; i++ ) - PicoFreeShader( model->shader[ i ] ); - free( model->shader ); - - /* free surfaces */ - for ( i = 0; i < model->numSurfaces; i++ ) - PicoFreeSurface( model->surface[ i ] ); - free( model->surface ); - - /* free the model */ - _pico_free( model ); -} - - - -/* - PicoAdjustModel() - adjusts a models's memory allocations to handle the requested sizes. - will always grow, never shrink - */ - -int PicoAdjustModel( picoModel_t *model, int numShaders, int numSurfaces ){ - /* dummy check */ - if ( model == NULL ) { - return 0; - } - - /* bare minimums */ - /* sea: null surface/shader fix (1s=>0s) */ - if ( numShaders < 0 ) { - numShaders = 0; - } - if ( numSurfaces < 0 ) { - numSurfaces = 0; - } - - /* additional shaders? */ - while ( numShaders > model->maxShaders ) - { - model->maxShaders += PICO_GROW_SHADERS; - if ( !_pico_realloc( (void *) &model->shader, model->numShaders * sizeof( *model->shader ), model->maxShaders * sizeof( *model->shader ) ) ) { - return 0; - } - } - - /* set shader count to higher */ - if ( numShaders > model->numShaders ) { - model->numShaders = numShaders; - } - - /* additional surfaces? */ - while ( numSurfaces > model->maxSurfaces ) - { - model->maxSurfaces += PICO_GROW_SURFACES; - if ( !_pico_realloc( (void *) &model->surface, model->numSurfaces * sizeof( *model->surface ), model->maxSurfaces * sizeof( *model->surface ) ) ) { - return 0; - } - } - - /* set shader count to higher */ - if ( numSurfaces > model->numSurfaces ) { - model->numSurfaces = numSurfaces; - } - - /* return ok */ - return 1; -} - - - -/* ---------------------------------------------------------------------------- - shaders - ---------------------------------------------------------------------------- */ - -/* - PicoNewShader() - creates a new pico shader and returns its index. -sea - */ - -picoShader_t *PicoNewShader( picoModel_t *model ){ - picoShader_t *shader; - - - /* allocate and clear */ - shader = _pico_alloc( sizeof( picoShader_t ) ); - if ( shader == NULL ) { - return NULL; - } - memset( shader, 0, sizeof( picoShader_t ) ); - - /* attach it to the model */ - if ( model != NULL ) { - /* adjust model */ - if ( !PicoAdjustModel( model, model->numShaders + 1, 0 ) ) { - _pico_free( shader ); - return NULL; - } - - /* attach */ - model->shader[ model->numShaders - 1 ] = shader; - shader->model = model; - } - - /* setup default shader colors */ - _pico_set_color( shader->ambientColor,0,0,0,0 ); - _pico_set_color( shader->diffuseColor,255,255,255,1 ); - _pico_set_color( shader->specularColor,0,0,0,0 ); - - /* no need to do this, but i do it anyway */ - shader->transparency = 0; - shader->shininess = 0; - - /* return the newly created shader */ - return shader; -} - - - -/* - PicoFreeShader() - frees a shader and all associated data -sea - */ - -void PicoFreeShader( picoShader_t *shader ){ - /* dummy check */ - if ( shader == NULL ) { - return; - } - - /* free bits */ - if ( shader->name ) { - _pico_free( shader->name ); - } - if ( shader->mapName ) { - _pico_free( shader->mapName ); - } - - /* free the shader */ - _pico_free( shader ); -} - - - -/* - PicoFindShader() - finds a named shader in a model - */ - -picoShader_t *PicoFindShader( picoModel_t *model, char *name, int caseSensitive ){ - int i; - - - /* sanity checks */ - if ( model == NULL || name == NULL ) { /* sea: null name fix */ - return NULL; - } - - /* walk list */ - for ( i = 0; i < model->numShaders; i++ ) - { - /* skip null shaders or shaders with null names */ - if ( model->shader[ i ] == NULL || - model->shader[ i ]->name == NULL ) { - continue; - } - - /* compare the shader name with name we're looking for */ - if ( caseSensitive ) { - if ( !strcmp( name, model->shader[ i ]->name ) ) { - return model->shader[ i ]; - } - } - else if ( !_pico_stricmp( name, model->shader[ i ]->name ) ) { - return model->shader[ i ]; - } - } - - /* named shader not found */ - return NULL; -} - - - -/* ---------------------------------------------------------------------------- - surfaces - ---------------------------------------------------------------------------- */ - -/* - PicoNewSurface() - creates a new pico surface - */ - -picoSurface_t *PicoNewSurface( picoModel_t *model ){ - picoSurface_t *surface; - char surfaceName[64]; - - /* allocate and clear */ - surface = _pico_alloc( sizeof( *surface ) ); - if ( surface == NULL ) { - return NULL; - } - memset( surface, 0, sizeof( *surface ) ); - - /* attach it to the model */ - if ( model != NULL ) { - /* adjust model */ - if ( !PicoAdjustModel( model, 0, model->numSurfaces + 1 ) ) { - _pico_free( surface ); - return NULL; - } - - /* attach */ - model->surface[ model->numSurfaces - 1 ] = surface; - surface->model = model; - - /* set default name */ - sprintf( surfaceName, "Unnamed_%d", model->numSurfaces ); - PicoSetSurfaceName( surface, surfaceName ); - } - - /* return */ - return surface; -} - - - -/* - PicoFreeSurface() - frees a surface and all associated data - */ -void PicoFreeSurface( picoSurface_t *surface ){ - int i; - - - /* dummy check */ - if ( surface == NULL ) { - return; - } - - /* free bits */ - _pico_free( surface->xyz ); - _pico_free( surface->normal ); - _pico_free( surface->smoothingGroup ); - _pico_free( surface->index ); - _pico_free( surface->faceNormal ); - - if ( surface->name ) { - _pico_free( surface->name ); - } - - /* free arrays */ - for ( i = 0; i < surface->numSTArrays; i++ ) - _pico_free( surface->st[ i ] ); - free( surface->st ); - for ( i = 0; i < surface->numColorArrays; i++ ) - _pico_free( surface->color[ i ] ); - free( surface->color ); - - /* free the surface */ - _pico_free( surface ); -} - - - -/* - PicoAdjustSurface() - adjusts a surface's memory allocations to handle the requested sizes. - will always grow, never shrink - */ - -int PicoAdjustSurface( picoSurface_t *surface, int numVertexes, int numSTArrays, int numColorArrays, int numIndexes, int numFaceNormals ){ - int i; - - - /* dummy check */ - if ( surface == NULL ) { - return 0; - } - - /* bare minimums */ - if ( numVertexes < 1 ) { - numVertexes = 1; - } - if ( numSTArrays < 1 ) { - numSTArrays = 1; - } - if ( numColorArrays < 1 ) { - numColorArrays = 1; - } - if ( numIndexes < 1 ) { - numIndexes = 1; - } - - /* additional vertexes? */ - while ( numVertexes > surface->maxVertexes ) /* fix */ - { - surface->maxVertexes += PICO_GROW_VERTEXES; - if ( !_pico_realloc( (void *) &surface->xyz, surface->numVertexes * sizeof( *surface->xyz ), surface->maxVertexes * sizeof( *surface->xyz ) ) ) { - return 0; - } - if ( !_pico_realloc( (void *) &surface->normal, surface->numVertexes * sizeof( *surface->normal ), surface->maxVertexes * sizeof( *surface->normal ) ) ) { - return 0; - } - if ( !_pico_realloc( (void *) &surface->smoothingGroup, surface->numVertexes * sizeof( *surface->smoothingGroup ), surface->maxVertexes * sizeof( *surface->smoothingGroup ) ) ) { - return 0; - } - for ( i = 0; i < surface->numSTArrays; i++ ) - if ( !_pico_realloc( (void*) &surface->st[ i ], surface->numVertexes * sizeof( *surface->st[ i ] ), surface->maxVertexes * sizeof( *surface->st[ i ] ) ) ) { - return 0; - } - for ( i = 0; i < surface->numColorArrays; i++ ) - if ( !_pico_realloc( (void*) &surface->color[ i ], surface->numVertexes * sizeof( *surface->color[ i ] ), surface->maxVertexes * sizeof( *surface->color[ i ] ) ) ) { - return 0; - } - } - - /* set vertex count to higher */ - if ( numVertexes > surface->numVertexes ) { - surface->numVertexes = numVertexes; - } - - /* additional st arrays? */ - while ( numSTArrays > surface->maxSTArrays ) /* fix */ - { - surface->maxSTArrays += PICO_GROW_ARRAYS; - if ( !_pico_realloc( (void*) &surface->st, surface->numSTArrays * sizeof( *surface->st ), surface->maxSTArrays * sizeof( *surface->st ) ) ) { - return 0; - } - while ( surface->numSTArrays < numSTArrays ) - { - surface->st[ surface->numSTArrays ] = _pico_alloc( surface->maxVertexes * sizeof( *surface->st[ 0 ] ) ); - memset( surface->st[ surface->numSTArrays ], 0, surface->maxVertexes * sizeof( *surface->st[ 0 ] ) ); - surface->numSTArrays++; - } - } - - /* additional color arrays? */ - while ( numColorArrays > surface->maxColorArrays ) /* fix */ - { - surface->maxColorArrays += PICO_GROW_ARRAYS; - if ( !_pico_realloc( (void*) &surface->color, surface->numColorArrays * sizeof( *surface->color ), surface->maxColorArrays * sizeof( *surface->color ) ) ) { - return 0; - } - while ( surface->numColorArrays < numColorArrays ) - { - surface->color[ surface->numColorArrays ] = _pico_alloc( surface->maxVertexes * sizeof( *surface->color[ 0 ] ) ); - memset( surface->color[ surface->numColorArrays ], 0, surface->maxVertexes * sizeof( *surface->color[ 0 ] ) ); - surface->numColorArrays++; - } - } - - /* additional indexes? */ - while ( numIndexes > surface->maxIndexes ) /* fix */ - { - surface->maxIndexes += PICO_GROW_INDEXES; - if ( !_pico_realloc( (void*) &surface->index, surface->numIndexes * sizeof( *surface->index ), surface->maxIndexes * sizeof( *surface->index ) ) ) { - return 0; - } - } - - /* set index count to higher */ - if ( numIndexes > surface->numIndexes ) { - surface->numIndexes = numIndexes; - } - - /* additional face normals? */ - while ( numFaceNormals > surface->maxFaceNormals ) /* fix */ - { - surface->maxFaceNormals += PICO_GROW_FACES; - if ( !_pico_realloc( (void *) &surface->faceNormal, surface->numFaceNormals * sizeof( *surface->faceNormal ), surface->maxFaceNormals * sizeof( *surface->faceNormal ) ) ) { - return 0; - } - } - - /* set face normal count to higher */ - if ( numFaceNormals > surface->numFaceNormals ) { - surface->numFaceNormals = numFaceNormals; - } - - /* return ok */ - return 1; -} - - -/* PicoFindSurface: - * Finds first matching named surface in a model. - */ -picoSurface_t *PicoFindSurface( - picoModel_t *model, char *name, int caseSensitive ){ - int i; - - /* sanity check */ - if ( model == NULL || name == NULL ) { - return NULL; - } - - /* walk list */ - for ( i = 0; i < model->numSurfaces; i++ ) - { - /* skip null surfaces or surfaces with null names */ - if ( model->surface[ i ] == NULL || - model->surface[ i ]->name == NULL ) { - continue; - } - - /* compare the surface name with name we're looking for */ - if ( caseSensitive ) { - if ( !strcmp( name,model->surface[ i ]->name ) ) { - return model->surface[ i ]; - } - } - else { - if ( !_pico_stricmp( name,model->surface[ i ]->name ) ) { - return model->surface[ i ]; - } - } - } - /* named surface not found */ - return NULL; -} - - - -/*---------------------------------------------------------------------------- - PicoSet*() Setter Functions - ----------------------------------------------------------------------------*/ - -void PicoSetModelName( picoModel_t *model, char *name ){ - if ( model == NULL || name == NULL ) { - return; - } - if ( model->name != NULL ) { - _pico_free( model->name ); - } - - model->name = _pico_clone_alloc( name ); -} - - - -void PicoSetModelFileName( picoModel_t *model, char *fileName ){ - if ( model == NULL || fileName == NULL ) { - return; - } - if ( model->fileName != NULL ) { - _pico_free( model->fileName ); - } - - model->fileName = _pico_clone_alloc( fileName ); -} - - - -void PicoSetModelFrameNum( picoModel_t *model, int frameNum ){ - if ( model == NULL ) { - return; - } - model->frameNum = frameNum; -} - - - -void PicoSetModelNumFrames( picoModel_t *model, int numFrames ){ - if ( model == NULL ) { - return; - } - model->numFrames = numFrames; -} - - - -void PicoSetModelData( picoModel_t *model, void *data ){ - if ( model == NULL ) { - return; - } - model->data = data; -} - - - -void PicoSetShaderName( picoShader_t *shader, char *name ){ - if ( shader == NULL || name == NULL ) { - return; - } - if ( shader->name != NULL ) { - _pico_free( shader->name ); - } - - shader->name = _pico_clone_alloc( name ); -} - - - -void PicoSetShaderMapName( picoShader_t *shader, char *mapName ){ - if ( shader == NULL || mapName == NULL ) { - return; - } - if ( shader->mapName != NULL ) { - _pico_free( shader->mapName ); - } - - shader->mapName = _pico_clone_alloc( mapName ); -} - - - -void PicoSetShaderAmbientColor( picoShader_t *shader, picoColor_t color ){ - if ( shader == NULL || color == NULL ) { - return; - } - shader->ambientColor[ 0 ] = color[ 0 ]; - shader->ambientColor[ 1 ] = color[ 1 ]; - shader->ambientColor[ 2 ] = color[ 2 ]; - shader->ambientColor[ 3 ] = color[ 3 ]; -} - - - -void PicoSetShaderDiffuseColor( picoShader_t *shader, picoColor_t color ){ - if ( shader == NULL || color == NULL ) { - return; - } - shader->diffuseColor[ 0 ] = color[ 0 ]; - shader->diffuseColor[ 1 ] = color[ 1 ]; - shader->diffuseColor[ 2 ] = color[ 2 ]; - shader->diffuseColor[ 3 ] = color[ 3 ]; -} - - - -void PicoSetShaderSpecularColor( picoShader_t *shader, picoColor_t color ){ - if ( shader == NULL || color == NULL ) { - return; - } - shader->specularColor[ 0 ] = color[ 0 ]; - shader->specularColor[ 1 ] = color[ 1 ]; - shader->specularColor[ 2 ] = color[ 2 ]; - shader->specularColor[ 3 ] = color[ 3 ]; -} - - - -void PicoSetShaderTransparency( picoShader_t *shader, float value ){ - if ( shader == NULL ) { - return; - } - shader->transparency = value; - - /* cap to 0..1 range */ - if ( shader->transparency < 0.0 ) { - shader->transparency = 0.0; - } - if ( shader->transparency > 1.0 ) { - shader->transparency = 1.0; - } -} - - - -void PicoSetShaderShininess( picoShader_t *shader, float value ){ - if ( shader == NULL ) { - return; - } - shader->shininess = value; - - /* cap to 0..127 range */ - if ( shader->shininess < 0.0 ) { - shader->shininess = 0.0; - } - if ( shader->shininess > 127.0 ) { - shader->shininess = 127.0; - } -} - - - -void PicoSetSurfaceData( picoSurface_t *surface, void *data ){ - if ( surface == NULL ) { - return; - } - surface->data = data; -} - - - -void PicoSetSurfaceType( picoSurface_t *surface, picoSurfaceType_t type ){ - if ( surface == NULL ) { - return; - } - surface->type = type; -} - - - -void PicoSetSurfaceName( picoSurface_t *surface, char *name ){ - if ( surface == NULL || name == NULL ) { - return; - } - if ( surface->name != NULL ) { - _pico_free( surface->name ); - } - - surface->name = _pico_clone_alloc( name ); -} - - - -void PicoSetSurfaceShader( picoSurface_t *surface, picoShader_t *shader ){ - if ( surface == NULL ) { - return; - } - surface->shader = shader; -} - - - -void PicoSetSurfaceXYZ( picoSurface_t *surface, int num, picoVec3_t xyz ){ - if ( surface == NULL || num < 0 || xyz == NULL ) { - return; - } - if ( !PicoAdjustSurface( surface, num + 1, 0, 0, 0, 0 ) ) { - return; - } - _pico_copy_vec( xyz, surface->xyz[ num ] ); - if ( surface->model != NULL ) { - _pico_expand_bounds( xyz, surface->model->mins, surface->model->maxs ); - } -} - - - -void PicoSetSurfaceNormal( picoSurface_t *surface, int num, picoVec3_t normal ){ - if ( surface == NULL || num < 0 || normal == NULL ) { - return; - } - if ( !PicoAdjustSurface( surface, num + 1, 0, 0, 0, 0 ) ) { - return; - } - _pico_copy_vec( normal, surface->normal[ num ] ); -} - - - -void PicoSetSurfaceST( picoSurface_t *surface, int array, int num, picoVec2_t st ){ - if ( surface == NULL || num < 0 || st == NULL ) { - return; - } - if ( !PicoAdjustSurface( surface, num + 1, array + 1, 0, 0, 0 ) ) { - return; - } - surface->st[ array ][ num ][ 0 ] = st[ 0 ]; - surface->st[ array ][ num ][ 1 ] = st[ 1 ]; -} - - - -void PicoSetSurfaceColor( picoSurface_t *surface, int array, int num, picoColor_t color ){ - if ( surface == NULL || num < 0 || color == NULL ) { - return; - } - if ( !PicoAdjustSurface( surface, num + 1, 0, array + 1, 0, 0 ) ) { - return; - } - surface->color[ array ][ num ][ 0 ] = color[ 0 ]; - surface->color[ array ][ num ][ 1 ] = color[ 1 ]; - surface->color[ array ][ num ][ 2 ] = color[ 2 ]; - surface->color[ array ][ num ][ 3 ] = color[ 3 ]; -} - - - -void PicoSetSurfaceIndex( picoSurface_t *surface, int num, picoIndex_t index ){ - if ( surface == NULL || num < 0 ) { - return; - } - if ( !PicoAdjustSurface( surface, 0, 0, 0, num + 1, 0 ) ) { - return; - } - surface->index[ num ] = index; -} - - - -void PicoSetSurfaceIndexes( picoSurface_t *surface, int num, picoIndex_t *index, int count ){ - if ( num < 0 || index == NULL || count < 1 ) { - return; - } - if ( !PicoAdjustSurface( surface, 0, 0, 0, num + count, 0 ) ) { - return; - } - memcpy( &surface->index[ num ], index, count * sizeof( surface->index[ num ] ) ); -} - - - -void PicoSetFaceNormal( picoSurface_t *surface, int num, picoVec3_t normal ){ - if ( surface == NULL || num < 0 || normal == NULL ) { - return; - } - if ( !PicoAdjustSurface( surface, 0, 0, 0, 0, num + 1 ) ) { - return; - } - _pico_copy_vec( normal, surface->faceNormal[ num ] ); -} - - -void PicoSetSurfaceSmoothingGroup( picoSurface_t *surface, int num, picoIndex_t smoothingGroup ){ - if ( num < 0 ) { - return; - } - if ( !PicoAdjustSurface( surface, num + 1, 0, 0, 0, 0 ) ) { - return; - } - surface->smoothingGroup[ num ] = smoothingGroup; -} - - -void PicoSetSurfaceSpecial( picoSurface_t *surface, int num, int special ){ - if ( surface == NULL || num < 0 || num >= PICO_MAX_SPECIAL ) { - return; - } - surface->special[ num ] = special; -} - - - -/*---------------------------------------------------------------------------- - PicoGet*() Getter Functions - ----------------------------------------------------------------------------*/ - -char *PicoGetModelName( picoModel_t *model ){ - if ( model == NULL ) { - return NULL; - } - if ( model->name == NULL ) { - return (char*) ""; - } - return model->name; -} - - - -char *PicoGetModelFileName( picoModel_t *model ){ - if ( model == NULL ) { - return NULL; - } - if ( model->fileName == NULL ) { - return (char*) ""; - } - return model->fileName; -} - - - -int PicoGetModelFrameNum( picoModel_t *model ){ - if ( model == NULL ) { - return 0; - } - return model->frameNum; -} - - - -int PicoGetModelNumFrames( picoModel_t *model ){ - if ( model == NULL ) { - return 0; - } - return model->numFrames; -} - - - -void *PicoGetModelData( picoModel_t *model ){ - if ( model == NULL ) { - return NULL; - } - return model->data; -} - - - -int PicoGetModelNumShaders( picoModel_t *model ){ - if ( model == NULL ) { - return 0; - } - return model->numShaders; -} - - - -picoShader_t *PicoGetModelShader( picoModel_t *model, int num ){ - /* a few sanity checks */ - if ( model == NULL ) { - return NULL; - } - if ( model->shader == NULL ) { - return NULL; - } - if ( num < 0 || num >= model->numShaders ) { - return NULL; - } - - /* return the shader */ - return model->shader[ num ]; -} - - - -int PicoGetModelNumSurfaces( picoModel_t *model ){ - if ( model == NULL ) { - return 0; - } - return model->numSurfaces; -} - - - -picoSurface_t *PicoGetModelSurface( picoModel_t *model, int num ){ - /* a few sanity checks */ - if ( model == NULL ) { - return NULL; - } - if ( model->surface == NULL ) { - return NULL; - } - if ( num < 0 || num >= model->numSurfaces ) { - return NULL; - } - - /* return the surface */ - return model->surface[ num ]; -} - - - -int PicoGetModelTotalVertexes( picoModel_t *model ){ - int i, count; - - - if ( model == NULL ) { - return 0; - } - if ( model->surface == NULL ) { - return 0; - } - - count = 0; - for ( i = 0; i < model->numSurfaces; i++ ) - count += PicoGetSurfaceNumVertexes( model->surface[ i ] ); - - return count; -} - - - -int PicoGetModelTotalIndexes( picoModel_t *model ){ - int i, count; - - - if ( model == NULL ) { - return 0; - } - if ( model->surface == NULL ) { - return 0; - } - - count = 0; - for ( i = 0; i < model->numSurfaces; i++ ) - count += PicoGetSurfaceNumIndexes( model->surface[ i ] ); - - return count; -} - - - -char *PicoGetShaderName( picoShader_t *shader ){ - if ( shader == NULL ) { - return NULL; - } - if ( shader->name == NULL ) { - return (char*) ""; - } - return shader->name; -} - - - -char *PicoGetShaderMapName( picoShader_t *shader ){ - if ( shader == NULL ) { - return NULL; - } - if ( shader->mapName == NULL ) { - return (char*) ""; - } - return shader->mapName; -} - - - -picoByte_t *PicoGetShaderAmbientColor( picoShader_t *shader ){ - if ( shader == NULL ) { - return NULL; - } - return shader->ambientColor; -} - - - -picoByte_t *PicoGetShaderDiffuseColor( picoShader_t *shader ){ - if ( shader == NULL ) { - return NULL; - } - return shader->diffuseColor; -} - - - -picoByte_t *PicoGetShaderSpecularColor( picoShader_t *shader ){ - if ( shader == NULL ) { - return NULL; - } - return shader->specularColor; -} - - - -float PicoGetShaderTransparency( picoShader_t *shader ){ - if ( shader == NULL ) { - return 0.0f; - } - return shader->transparency; -} - - - -float PicoGetShaderShininess( picoShader_t *shader ){ - if ( shader == NULL ) { - return 0.0f; - } - return shader->shininess; -} - - - -void *PicoGetSurfaceData( picoSurface_t *surface ){ - if ( surface == NULL ) { - return NULL; - } - return surface->data; -} - - - -picoSurfaceType_t PicoGetSurfaceType( picoSurface_t *surface ){ - if ( surface == NULL ) { - return PICO_BAD; - } - return surface->type; -} - - - -char *PicoGetSurfaceName( picoSurface_t *surface ){ - if ( surface == NULL ) { - return NULL; - } - if ( surface->name == NULL ) { - return (char*) ""; - } - return surface->name; -} - - - -picoShader_t *PicoGetSurfaceShader( picoSurface_t *surface ){ - if ( surface == NULL ) { - return NULL; - } - return surface->shader; -} - - - -int PicoGetSurfaceNumVertexes( picoSurface_t *surface ){ - if ( surface == NULL ) { - return 0; - } - return surface->numVertexes; -} - - - -picoVec_t *PicoGetSurfaceXYZ( picoSurface_t *surface, int num ){ - if ( surface == NULL || num < 0 || num > surface->numVertexes ) { - return NULL; - } - return surface->xyz[ num ]; -} - - - -picoVec_t *PicoGetSurfaceNormal( picoSurface_t *surface, int num ){ - if ( surface == NULL || num < 0 || num > surface->numVertexes ) { - return NULL; - } - return surface->normal[ num ]; -} - - - -picoVec_t *PicoGetSurfaceST( picoSurface_t *surface, int array, int num ){ - if ( surface == NULL || array < 0 || array > surface->numSTArrays || num < 0 || num > surface->numVertexes ) { - return NULL; - } - return surface->st[ array ][ num ]; -} - - - -picoByte_t *PicoGetSurfaceColor( picoSurface_t *surface, int array, int num ){ - if ( surface == NULL || array < 0 || array > surface->numColorArrays || num < 0 || num > surface->numVertexes ) { - return NULL; - } - return surface->color[ array ][ num ]; -} - - - -int PicoGetSurfaceNumIndexes( picoSurface_t *surface ){ - if ( surface == NULL ) { - return 0; - } - return surface->numIndexes; -} - - - -picoIndex_t PicoGetSurfaceIndex( picoSurface_t *surface, int num ){ - if ( surface == NULL || num < 0 || num > surface->numIndexes ) { - return 0; - } - return surface->index[ num ]; -} - - - -picoIndex_t *PicoGetSurfaceIndexes( picoSurface_t *surface, int num ){ - if ( surface == NULL || num < 0 || num > surface->numIndexes ) { - return NULL; - } - return &surface->index[ num ]; -} - - -picoVec_t *PicoGetFaceNormal( picoSurface_t *surface, int num ){ - if ( surface == NULL || num < 0 || num > surface->numFaceNormals ) { - return NULL; - } - return surface->faceNormal[ num ]; -} - -picoIndex_t PicoGetSurfaceSmoothingGroup( picoSurface_t *surface, int num ){ - if ( surface == NULL || num < 0 || num > surface->numVertexes ) { - return -1; - } - return surface->smoothingGroup[ num ]; -} - - -int PicoGetSurfaceSpecial( picoSurface_t *surface, int num ){ - if ( surface == NULL || num < 0 || num >= PICO_MAX_SPECIAL ) { - return 0; - } - return surface->special[ num ]; -} - - - -/* ---------------------------------------------------------------------------- - hashtable related functions - ---------------------------------------------------------------------------- */ - -/* hashtable code for faster vertex lookups */ -//#define HASHTABLE_SIZE 32768 // 2048 /* power of 2, use & */ -#define HASHTABLE_SIZE 7919 // 32749 // 2039 /* prime, use % */ - -int PicoGetHashTableSize( void ){ - return HASHTABLE_SIZE; -} - -#define HASH_USE_EPSILON - -#ifdef HASH_USE_EPSILON -#define HASH_XYZ_EPSILON 0.01f -#define HASH_XYZ_EPSILONSPACE_MULTIPLIER 1.f / HASH_XYZ_EPSILON -#define HASH_ST_EPSILON 0.0001f -#define HASH_NORMAL_EPSILON 0.02f -#endif - -unsigned int PicoVertexCoordGenerateHash( picoVec3_t xyz ){ - unsigned int hash = 0; - -#ifndef HASH_USE_EPSILON - hash += ~( *( (unsigned int*) &xyz[ 0 ] ) << 15 ); - hash ^= ( *( (unsigned int*) &xyz[ 0 ] ) >> 10 ); - hash += ( *( (unsigned int*) &xyz[ 1 ] ) << 3 ); - hash ^= ( *( (unsigned int*) &xyz[ 1 ] ) >> 6 ); - hash += ~( *( (unsigned int*) &xyz[ 2 ] ) << 11 ); - hash ^= ( *( (unsigned int*) &xyz[ 2 ] ) >> 16 ); -#else - picoVec3_t xyz_epsilonspace; - - _pico_scale_vec( xyz, HASH_XYZ_EPSILONSPACE_MULTIPLIER, xyz_epsilonspace ); - xyz_epsilonspace[ 0 ] = (float)floor( xyz_epsilonspace[ 0 ] ); - xyz_epsilonspace[ 1 ] = (float)floor( xyz_epsilonspace[ 1 ] ); - xyz_epsilonspace[ 2 ] = (float)floor( xyz_epsilonspace[ 2 ] ); - - hash += ~( *( (unsigned int*) &xyz_epsilonspace[ 0 ] ) << 15 ); - hash ^= ( *( (unsigned int*) &xyz_epsilonspace[ 0 ] ) >> 10 ); - hash += ( *( (unsigned int*) &xyz_epsilonspace[ 1 ] ) << 3 ); - hash ^= ( *( (unsigned int*) &xyz_epsilonspace[ 1 ] ) >> 6 ); - hash += ~( *( (unsigned int*) &xyz_epsilonspace[ 2 ] ) << 11 ); - hash ^= ( *( (unsigned int*) &xyz_epsilonspace[ 2 ] ) >> 16 ); -#endif - - //hash = hash & (HASHTABLE_SIZE-1); - hash = hash % ( HASHTABLE_SIZE ); - return hash; -} - -picoVertexCombinationHash_t **PicoNewVertexCombinationHashTable( void ){ - picoVertexCombinationHash_t **hashTable = _pico_alloc( HASHTABLE_SIZE * sizeof( picoVertexCombinationHash_t* ) ); - - memset( hashTable, 0, HASHTABLE_SIZE * sizeof( picoVertexCombinationHash_t* ) ); - - return hashTable; -} - -void PicoFreeVertexCombinationHashTable( picoVertexCombinationHash_t **hashTable ){ - int i; - picoVertexCombinationHash_t *vertexCombinationHash; - picoVertexCombinationHash_t *nextVertexCombinationHash; - - /* dummy check */ - if ( hashTable == NULL ) { - return; - } - - for ( i = 0; i < HASHTABLE_SIZE; i++ ) - { - if ( hashTable[ i ] ) { - nextVertexCombinationHash = NULL; - - for ( vertexCombinationHash = hashTable[ i ]; vertexCombinationHash; vertexCombinationHash = nextVertexCombinationHash ) - { - nextVertexCombinationHash = vertexCombinationHash->next; - if ( vertexCombinationHash->data != NULL ) { - _pico_free( vertexCombinationHash->data ); - } - _pico_free( vertexCombinationHash ); - } - } - } - - _pico_free( hashTable ); -} - -picoVertexCombinationHash_t *PicoFindVertexCombinationInHashTable( picoVertexCombinationHash_t **hashTable, picoVec3_t xyz, picoVec3_t normal, picoVec3_t st, picoColor_t color ){ - unsigned int hash; - picoVertexCombinationHash_t *vertexCombinationHash; - - /* dumy check */ - if ( hashTable == NULL || xyz == NULL || normal == NULL || st == NULL || color == NULL ) { - return NULL; - } - - hash = PicoVertexCoordGenerateHash( xyz ); - - for ( vertexCombinationHash = hashTable[ hash ]; vertexCombinationHash; vertexCombinationHash = vertexCombinationHash->next ) - { -#ifndef HASH_USE_EPSILON - /* check xyz */ - if ( ( vertexCombinationHash->vcd.xyz[ 0 ] != xyz[ 0 ] || vertexCombinationHash->vcd.xyz[ 1 ] != xyz[ 1 ] || vertexCombinationHash->vcd.xyz[ 2 ] != xyz[ 2 ] ) ) { - continue; - } - - /* check normal */ - if ( ( vertexCombinationHash->vcd.normal[ 0 ] != normal[ 0 ] || vertexCombinationHash->vcd.normal[ 1 ] != normal[ 1 ] || vertexCombinationHash->vcd.normal[ 2 ] != normal[ 2 ] ) ) { - continue; - } - - /* check st */ - if ( vertexCombinationHash->vcd.st[ 0 ] != st[ 0 ] || vertexCombinationHash->vcd.st[ 1 ] != st[ 1 ] ) { - continue; - } -#else - /* check xyz */ - if ( ( fabs( xyz[ 0 ] - vertexCombinationHash->vcd.xyz[ 0 ] ) ) > HASH_XYZ_EPSILON || - ( fabs( xyz[ 1 ] - vertexCombinationHash->vcd.xyz[ 1 ] ) ) > HASH_XYZ_EPSILON || - ( fabs( xyz[ 2 ] - vertexCombinationHash->vcd.xyz[ 2 ] ) ) > HASH_XYZ_EPSILON ) { - continue; - } - - /* check normal */ - if ( ( fabs( normal[ 0 ] - vertexCombinationHash->vcd.normal[ 0 ] ) ) > HASH_NORMAL_EPSILON || - ( fabs( normal[ 1 ] - vertexCombinationHash->vcd.normal[ 1 ] ) ) > HASH_NORMAL_EPSILON || - ( fabs( normal[ 2 ] - vertexCombinationHash->vcd.normal[ 2 ] ) ) > HASH_NORMAL_EPSILON ) { - continue; - } - - /* check st */ - if ( ( fabs( st[ 0 ] - vertexCombinationHash->vcd.st[ 0 ] ) ) > HASH_ST_EPSILON || - ( fabs( st[ 1 ] - vertexCombinationHash->vcd.st[ 1 ] ) ) > HASH_ST_EPSILON ) { - continue; - } -#endif - - /* check color */ - if ( *( (int*) vertexCombinationHash->vcd.color ) != *( (int*) color ) ) { - continue; - } - - /* gotcha */ - return vertexCombinationHash; - } - - return NULL; -} - -picoVertexCombinationHash_t *PicoAddVertexCombinationToHashTable( picoVertexCombinationHash_t **hashTable, picoVec3_t xyz, picoVec3_t normal, picoVec3_t st, picoColor_t color, picoIndex_t index ){ - unsigned int hash; - picoVertexCombinationHash_t *vertexCombinationHash; - - /* dumy check */ - if ( hashTable == NULL || xyz == NULL || normal == NULL || st == NULL || color == NULL ) { - return NULL; - } - - vertexCombinationHash = _pico_alloc( sizeof( picoVertexCombinationHash_t ) ); - - if ( !vertexCombinationHash ) { - return NULL; - } - - hash = PicoVertexCoordGenerateHash( xyz ); - - _pico_copy_vec( xyz, vertexCombinationHash->vcd.xyz ); - _pico_copy_vec( normal, vertexCombinationHash->vcd.normal ); - _pico_copy_vec2( st, vertexCombinationHash->vcd.st ); - _pico_copy_color( color, vertexCombinationHash->vcd.color ); - vertexCombinationHash->index = index; - vertexCombinationHash->data = NULL; - vertexCombinationHash->next = hashTable[ hash ]; - hashTable[ hash ] = vertexCombinationHash; - - return vertexCombinationHash; -} - -/* ---------------------------------------------------------------------------- - specialized routines - ---------------------------------------------------------------------------- */ - -/* - PicoFindSurfaceVertex() - finds a vertex matching the set parameters - fixme: needs non-naive algorithm - */ - -int PicoFindSurfaceVertexNum( picoSurface_t *surface, picoVec3_t xyz, picoVec3_t normal, int numSTs, picoVec2_t *st, int numColors, picoColor_t *color, picoIndex_t smoothingGroup ){ - int i, j; - -// Sys_Printf(" %f %f %f\n", normal[0] , normal[1] , normal[2] ); - - /* dummy check */ - if ( surface == NULL || surface->numVertexes <= 0 ) { - return -1; - } - - /* walk vertex list */ - for ( i = 0; i < surface->numVertexes; i++ ) - { - /* check xyz */ - if ( xyz != NULL && ( surface->xyz[ i ][ 0 ] != xyz[ 0 ] || surface->xyz[ i ][ 1 ] != xyz[ 1 ] || surface->xyz[ i ][ 2 ] != xyz[ 2 ] ) ) { - continue; - } - - /* check normal */ - if ( normal != NULL && ( surface->normal[ i ][ 0 ] != normal[ 0 ] || surface->normal[ i ][ 1 ] != normal[ 1 ] || surface->normal[ i ][ 2 ] != normal[ 2 ] ) ) { - continue; - } - - /* check normal */ - if ( surface->smoothingGroup[ i ] != smoothingGroup ) { - continue; - } - - /* check st */ - if ( numSTs > 0 && st != NULL ) { - for ( j = 0; j < numSTs; j++ ) - { - if ( surface->st[ j ][ i ][ 0 ] != st[ j ][ 0 ] || surface->st[ j ][ i ][ 1 ] != st[ j ][ 1 ] ) { - break; - } - } - if ( j != numSTs ) { - continue; - } - } - - /* check color */ - if ( numColors > 0 && color != NULL ) { - for ( j = 0; j < numSTs; j++ ) - { - if ( *( (int*) surface->color[ j ] ) != *( (int*) color[ j ] ) ) { - break; - } - } - if ( j != numColors ) { - continue; - } - } - - /* vertex matches */ - return i; - } - - /* nada */ - return -1; -} - - - - -typedef struct _IndexArray IndexArray; -struct _IndexArray -{ - picoIndex_t* data; - picoIndex_t* last; -}; - -void indexarray_push_back( IndexArray* self, picoIndex_t value ){ - *self->last++ = value; -} - -size_t indexarray_size( IndexArray* self ){ - return self->last - self->data; -} - -void indexarray_reserve( IndexArray* self, size_t size ){ - self->data = self->last = _pico_calloc( size, sizeof( picoIndex_t ) ); -} - -void indexarray_clear( IndexArray* self ){ - _pico_free( self->data ); -} - -typedef struct _BinaryTreeNode BinaryTreeNode; -struct _BinaryTreeNode -{ - picoIndex_t left; - picoIndex_t right; -}; - -typedef struct _BinaryTree BinaryTree; -struct _BinaryTree -{ - BinaryTreeNode* data; - BinaryTreeNode* last; -}; - -void binarytree_extend( BinaryTree* self ){ - self->last->left = 0; - self->last->right = 0; - ++self->last; -} - -size_t binarytree_size( BinaryTree* self ){ - return self->last - self->data; -} - -void binarytree_reserve( BinaryTree* self, size_t size ){ - self->data = self->last = _pico_calloc( size, sizeof( BinaryTreeNode ) ); -} - -void binarytree_clear( BinaryTree* self ){ - _pico_free( self->data ); -} - -typedef int ( *LessFunc )( void*, picoIndex_t, picoIndex_t ); - -typedef struct _UniqueIndices UniqueIndices; -struct _UniqueIndices -{ - BinaryTree tree; - IndexArray indices; - LessFunc lessFunc; - void* lessData; -}; - -size_t UniqueIndices_size( UniqueIndices* self ){ - return binarytree_size( &self->tree ); -} - -void UniqueIndices_reserve( UniqueIndices* self, size_t size ){ - binarytree_reserve( &self->tree, size ); - indexarray_reserve( &self->indices, size ); -} - -void UniqueIndices_init( UniqueIndices* self, LessFunc lessFunc, void* lessData ){ - self->lessFunc = lessFunc; - self->lessData = lessData; -} - -void UniqueIndices_destroy( UniqueIndices* self ){ - binarytree_clear( &self->tree ); - indexarray_clear( &self->indices ); -} - - -picoIndex_t UniqueIndices_find_or_insert( UniqueIndices* self, picoIndex_t value ){ - picoIndex_t index = 0; - - for (;; ) - { - if ( self->lessFunc( self->lessData, value, self->indices.data[index] ) ) { - BinaryTreeNode* node = self->tree.data + index; - if ( node->left != 0 ) { - index = node->left; - continue; - } - else - { - node->left = (picoIndex_t)binarytree_size( &self->tree ); - binarytree_extend( &self->tree ); - indexarray_push_back( &self->indices, value ); - return node->left; - } - } - if ( self->lessFunc( self->lessData, self->indices.data[index], value ) ) { - BinaryTreeNode* node = self->tree.data + index; - if ( node->right != 0 ) { - index = node->right; - continue; - } - else - { - node->right = (picoIndex_t)binarytree_size( &self->tree ); - binarytree_extend( &self->tree ); - indexarray_push_back( &self->indices, value ); - return node->right; - } - } - - return index; - } -} - -picoIndex_t UniqueIndices_insert( UniqueIndices* self, picoIndex_t value ){ - if ( self->tree.data == self->tree.last ) { - binarytree_extend( &self->tree ); - indexarray_push_back( &self->indices, value ); - return 0; - } - else - { - return UniqueIndices_find_or_insert( self, value ); - } -} - -typedef struct picoSmoothVertices_s picoSmoothVertices_t; -struct picoSmoothVertices_s -{ - picoVec3_t* xyz; - picoIndex_t* smoothingGroups; -}; - -int lessSmoothVertex( void* data, picoIndex_t first, picoIndex_t second ){ - picoSmoothVertices_t* smoothVertices = data; - - if ( smoothVertices->xyz[first][0] != smoothVertices->xyz[second][0] ) { - return smoothVertices->xyz[first][0] < smoothVertices->xyz[second][0]; - } - if ( smoothVertices->xyz[first][1] != smoothVertices->xyz[second][1] ) { - return smoothVertices->xyz[first][1] < smoothVertices->xyz[second][1]; - } - if ( smoothVertices->xyz[first][2] != smoothVertices->xyz[second][2] ) { - return smoothVertices->xyz[first][2] < smoothVertices->xyz[second][2]; - } - if ( smoothVertices->smoothingGroups[first] != smoothVertices->smoothingGroups[second] ) { - return smoothVertices->smoothingGroups[first] < smoothVertices->smoothingGroups[second]; - } - return 0; -} - -void _pico_vertices_combine_shared_normals( picoVec3_t* xyz, picoIndex_t* smoothingGroups, picoVec3_t* normals, picoIndex_t numVertices ){ - UniqueIndices vertices; - IndexArray indices; - picoSmoothVertices_t smoothVertices = { xyz, smoothingGroups }; - UniqueIndices_init( &vertices, lessSmoothVertex, &smoothVertices ); - UniqueIndices_reserve( &vertices, numVertices ); - indexarray_reserve( &indices, numVertices ); - - - { - picoIndex_t i = 0; - for (; i < numVertices; ++i ) - { - size_t size = UniqueIndices_size( &vertices ); - picoIndex_t index = UniqueIndices_insert( &vertices, i ); - if ( (size_t)index != size ) { - float* normal = normals[vertices.indices.data[index]]; - _pico_add_vec( normal, normals[i], normal ); - } - indexarray_push_back( &indices, index ); - } - } - - { - picoIndex_t maxIndex = 0; - picoIndex_t* i = indices.data; - for (; i != indices.last; ++i ) - { - if ( *i <= maxIndex ) { - _pico_copy_vec( normals[vertices.indices.data[*i]], normals[i - indices.data] ); - } - else - { - maxIndex = *i; - } - } - } - - UniqueIndices_destroy( &vertices ); - indexarray_clear( &indices ); -} - -typedef picoVec3_t* picoNormalIter_t; -typedef picoIndex_t* picoIndexIter_t; - -void _pico_triangles_generate_weighted_normals( picoIndexIter_t first, picoIndexIter_t end, picoVec3_t* xyz, picoVec3_t* normals ){ - for (; first != end; first += 3 ) - { - picoVec3_t weightedNormal; - { - float* a = xyz[*( first + 0 )]; - float* b = xyz[*( first + 1 )]; - float* c = xyz[*( first + 2 )]; - picoVec3_t ba, ca; - _pico_subtract_vec( b, a, ba ); - _pico_subtract_vec( c, a, ca ); - _pico_cross_vec( ca, ba, weightedNormal ); - } - { - int j = 0; - for (; j < 3; ++j ) - { - float* normal = normals[*( first + j )]; - _pico_add_vec( weightedNormal, normal, normal ); - } - } - } -} - -void _pico_normals_zero( picoNormalIter_t first, picoNormalIter_t last ){ - for (; first != last; ++first ) - { - _pico_zero_vec( *first ); - } -} - -void _pico_normals_normalize( picoNormalIter_t first, picoNormalIter_t last ){ - for (; first != last; ++first ) - { - _pico_normalize_vec( *first ); - } -} - -double _pico_length_vec( picoVec3_t vec ){ - return sqrt( vec[ 0 ] * vec[ 0 ] + vec[ 1 ] * vec[ 1 ] + vec[ 2 ] * vec[ 2 ] ); -} - -#define NORMAL_UNIT_LENGTH_EPSILON 0.01 -#define FLOAT_EQUAL_EPSILON( f, other, epsilon ) ( fabs( f - other ) < epsilon ) - -int _pico_normal_is_unit_length( picoVec3_t normal ){ - return FLOAT_EQUAL_EPSILON( _pico_length_vec( normal ), 1.0, NORMAL_UNIT_LENGTH_EPSILON ); -} - -int _pico_normal_within_tolerance( picoVec3_t normal, picoVec3_t other ){ - return _pico_dot_vec( normal, other ) > 0.0f; -} - - -void _pico_normals_assign_generated_normals( picoNormalIter_t first, picoNormalIter_t last, picoNormalIter_t generated ){ - for (; first != last; ++first, ++generated ) - { - //27 - fix for badly generated normals thing. - // if(!_pico_normal_is_unit_length(*first) || !_pico_normal_within_tolerance(*first, *generated)) - { - _pico_copy_vec( *generated, *first ); - } - } -} - -void PicoFixSurfaceNormals( picoSurface_t* surface ){ - picoVec3_t* normals = (picoVec3_t*)_pico_calloc( surface->numVertexes, sizeof( picoVec3_t ) ); - - _pico_normals_zero( normals, normals + surface->numVertexes ); - - //Just build standard no sg normals for now - _pico_triangles_generate_weighted_normals( surface->index, surface->index + surface->numIndexes, surface->xyz, normals ); - _pico_vertices_combine_shared_normals( surface->xyz, surface->smoothingGroup, normals, surface->numVertexes ); - - _pico_normals_normalize( normals, normals + surface->numVertexes ); - - _pico_normals_assign_generated_normals( surface->normal, surface->normal + surface->numVertexes, normals ); - - _pico_free( normals ); -} - - -/* - PicoRemapModel() - sea - remaps model material/etc. information using the remappings - contained in the given 'remapFile' (full path to the ascii file to open) - returns 1 on success or 0 on error - */ - -#define _prm_error_return \ - { \ - _pico_free_parser( p ); \ - _pico_free_file( remapBuffer ); \ - return 0; \ - } - -int PicoRemapModel( picoModel_t *model, char *remapFile ){ - picoParser_t *p; - picoByte_t *remapBuffer; - int remapBufSize; - - - /* sanity checks */ - if ( model == NULL || remapFile == NULL ) { - return 0; - } - - /* load remap file contents */ - _pico_load_file( remapFile,&remapBuffer,&remapBufSize ); - - /* check result */ - if ( remapBufSize == 0 ) { - return 1; /* file is empty: no error */ - } - if ( remapBufSize < 0 ) { - return 0; /* load failed: error */ - - } - /* create a new pico parser */ - p = _pico_new_parser( remapBuffer, remapBufSize ); - if ( p == NULL ) { - /* ram is really cheap nowadays... */ - _prm_error_return; - } - - /* doo teh parse */ - while ( 1 ) - { - /* get next token in remap file */ - if ( !_pico_parse( p,1 ) ) { - break; - } - - /* skip over c++ style comment lines */ - if ( !_pico_stricmp( p->token,"//" ) ) { - _pico_parse_skip_rest( p ); - continue; - } - - /* block for quick material shader name remapping */ - /* materials { "m" (=>|->|=) "s" } */ - if ( !_pico_stricmp( p->token, "materials" ) ) { - int level = 1; - - /* check bracket */ - if ( !_pico_parse_check( p,1,"{" ) ) { - _prm_error_return; - } - - /* process assignments */ - while ( 1 ) - { - picoShader_t *shader; - char *materialName; - - - /* get material name */ - if ( _pico_parse( p,1 ) == NULL ) { - break; - } - if ( !strlen( p->token ) ) { - continue; - } - materialName = _pico_clone_alloc( p->token ); - if ( materialName == NULL ) { - _prm_error_return; - } - - /* handle levels */ - if ( p->token[0] == '{' ) { - level++; - } - if ( p->token[0] == '}' ) { - level--; - } - if ( !level ) { - break; - } - - /* get next token (assignment token or shader name) */ - if ( !_pico_parse( p,0 ) ) { - _pico_free( materialName ); - _prm_error_return; - } - /* skip assignment token (if present) */ - if ( !strcmp( p->token,"=>" ) || - !strcmp( p->token,"->" ) || - !strcmp( p->token,"=" ) ) { - /* simply grab the next token */ - if ( !_pico_parse( p,0 ) ) { - _pico_free( materialName ); - _prm_error_return; - } - } - /* try to find material by name */ - shader = PicoFindShader( model,materialName,0 ); - - /* we've found a material matching the name */ - if ( shader != NULL ) { - PicoSetShaderName( shader,p->token ); - } - /* free memory used by material name */ - _pico_free( materialName ); - - /* skip rest */ - _pico_parse_skip_rest( p ); - } - } - /* block for detailed single material remappings */ - /* materials[ "m" ] { key data... } */ - else if ( !_pico_stricmp( p->token,"materials[" ) ) { - picoShader_t *shader; - char *tempMaterialName; - int level = 1; - - /* get material name */ - if ( !_pico_parse( p,0 ) ) { - _prm_error_return; - } - - /* temporary copy of material name */ - tempMaterialName = _pico_clone_alloc( p->token ); - if ( tempMaterialName == NULL ) { - _prm_error_return; - } - - /* check square closing bracket */ - if ( !_pico_parse_check( p,0,"]" ) ) { - _prm_error_return; - } - - /* try to find material by name */ - shader = PicoFindShader( model,tempMaterialName,0 ); - - /* free memory used by temporary material name */ - _pico_free( tempMaterialName ); - - /* we haven't found a material matching the name */ - /* so we simply skip the braced section now and */ - /* continue parsing with the next main token */ - if ( shader == NULL ) { - _pico_parse_skip_braced( p ); - continue; - } - /* check opening bracket */ - if ( !_pico_parse_check( p,1,"{" ) ) { - _prm_error_return; - } - - /* process material info keys */ - while ( 1 ) - { - /* get key name */ - if ( _pico_parse( p,1 ) == NULL ) { - break; - } - if ( !strlen( p->token ) ) { - continue; - } - - /* handle levels */ - if ( p->token[0] == '{' ) { - level++; - } - if ( p->token[0] == '}' ) { - level--; - } - if ( !level ) { - break; - } - - /* remap shader name */ - if ( !_pico_stricmp( p->token,"shader" ) ) { - if ( !_pico_parse( p,0 ) ) { - _prm_error_return; - } - PicoSetShaderName( shader,p->token ); - } - /* remap shader map name */ - else if ( !_pico_stricmp( p->token,"mapname" ) ) { - if ( !_pico_parse( p,0 ) ) { - _prm_error_return; - } - PicoSetShaderMapName( shader,p->token ); - } - /* remap shader's ambient color */ - else if ( !_pico_stricmp( p->token,"ambient" ) ) { - picoColor_t color; - picoVec3_t v; - - /* get vector from parser */ - if ( !_pico_parse_vec( p,v ) ) { - _prm_error_return; - } - - /* store as color */ - color[ 0 ] = (picoByte_t)v[ 0 ]; - color[ 1 ] = (picoByte_t)v[ 1 ]; - color[ 2 ] = (picoByte_t)v[ 2 ]; - - /* set new ambient color */ - PicoSetShaderAmbientColor( shader,color ); - } - /* remap shader's diffuse color */ - else if ( !_pico_stricmp( p->token,"diffuse" ) ) { - picoColor_t color; - picoVec3_t v; - - /* get vector from parser */ - if ( !_pico_parse_vec( p,v ) ) { - _prm_error_return; - } - - /* store as color */ - color[ 0 ] = (picoByte_t)v[ 0 ]; - color[ 1 ] = (picoByte_t)v[ 1 ]; - color[ 2 ] = (picoByte_t)v[ 2 ]; - - /* set new ambient color */ - PicoSetShaderDiffuseColor( shader,color ); - } - /* remap shader's specular color */ - else if ( !_pico_stricmp( p->token,"specular" ) ) { - picoColor_t color; - picoVec3_t v; - - /* get vector from parser */ - if ( !_pico_parse_vec( p,v ) ) { - _prm_error_return; - } - - /* store as color */ - color[ 0 ] = (picoByte_t)v[ 0 ]; - color[ 1 ] = (picoByte_t)v[ 1 ]; - color[ 2 ] = (picoByte_t)v[ 2 ]; - - /* set new ambient color */ - PicoSetShaderSpecularColor( shader,color ); - } - /* skip rest */ - _pico_parse_skip_rest( p ); - } - } - /* end 'materials[' */ - } - - /* free both parser and file buffer */ - _pico_free_parser( p ); - _pico_free_file( remapBuffer ); - - /* return with success */ - return 1; -} - - -/* - PicoAddTriangleToModel() - jhefty - A nice way to add individual triangles to the model. - Chooses an appropriate surface based on the shader, or adds a new surface if necessary - */ - -void PicoAddTriangleToModel( picoModel_t *model, picoVec3_t** xyz, picoVec3_t** normals, - int numSTs, picoVec2_t **st, int numColors, picoColor_t **colors, - picoShader_t* shader, picoIndex_t* smoothingGroup,int submodel ){ - int i,j; - int vertDataIndex; - picoSurface_t* workSurface = NULL; - - /* see if a surface already has the shader */ - for ( i = 0 ; i < model->numSurfaces ; i++ ) - { - workSurface = model->surface[i]; - if ( ( workSurface->shader == shader ) && ( workSurface->submodel == submodel ) ) { - break; - } - } - - /* no surface uses this shader yet, so create a new surface */ - if ( !workSurface || i >= model->numSurfaces ) { - /* create a new surface in the model for the unique shader */ - workSurface = PicoNewSurface( model ); - if ( !workSurface ) { - _pico_printf( PICO_ERROR, "Could not allocate a new surface!\n" ); - return; - } - - /* do surface setup */ - PicoSetSurfaceType( workSurface, PICO_TRIANGLES ); - PicoSetSurfaceName( workSurface, shader->name ); - PicoSetSurfaceShader( workSurface, shader ); - workSurface->submodel = submodel; - } - - /* add the triangle data to the surface */ - for ( i = 0 ; i < 3 ; i++ ) - { - /* get the next free spot in the index array */ - int newVertIndex = PicoGetSurfaceNumIndexes( workSurface ); - - /* get the index of the vertex that we're going to store at newVertIndex */ - vertDataIndex = -1; // PicoFindSurfaceVertexNum ( workSurface , *xyz[i] , *normals[i] , numSTs , st[i] , numColors , colors[i], smoothingGroup[i]); - - /* the vertex wasn't found, so create a new vertex in the pool from the data we have */ - if ( vertDataIndex == -1 ) { - /* find the next spot for a new vertex */ - vertDataIndex = PicoGetSurfaceNumVertexes( workSurface ); - - /* assign the data to it */ - PicoSetSurfaceXYZ( workSurface,vertDataIndex, *xyz[i] ); - PicoSetSurfaceNormal( workSurface, vertDataIndex, *normals[i] ); - - /* make sure to copy over all available ST's and colors for the vertex */ - for ( j = 0 ; j < numColors ; j++ ) - { - PicoSetSurfaceColor( workSurface, j, vertDataIndex, colors[i][j] ); - } - for ( j = 0 ; j < numSTs ; j++ ) - { - PicoSetSurfaceST( workSurface, j, vertDataIndex, st[i][j] ); - } - - PicoSetSurfaceSmoothingGroup( workSurface, vertDataIndex, smoothingGroup[i] ); - } - - /* add this vertex to the triangle */ - PicoSetSurfaceIndex( workSurface, newVertIndex, vertDataIndex ); - } -} diff --git a/tools/urt/libs/picomodel/picomodel.dsp b/tools/urt/libs/picomodel/picomodel.dsp deleted file mode 100644 index 8d72277..0000000 --- a/tools/urt/libs/picomodel/picomodel.dsp +++ /dev/null @@ -1,210 +0,0 @@ -# Microsoft Developer Studio Project File - Name="picomodel" - Package Owner=<4> -# Microsoft Developer Studio Generated Build File, Format Version 6.00 -# ** DO NOT EDIT ** - -# TARGTYPE "Win32 (x86) Static Library" 0x0104 - -CFG=picomodel - Win32 Debug -!MESSAGE This is not a valid makefile. To build this project using NMAKE, -!MESSAGE use the Export Makefile command and run -!MESSAGE -!MESSAGE NMAKE /f "picomodel.mak". -!MESSAGE -!MESSAGE You can specify a configuration when running NMAKE -!MESSAGE by defining the macro CFG on the command line. For example: -!MESSAGE -!MESSAGE NMAKE /f "picomodel.mak" CFG="picomodel - Win32 Debug" -!MESSAGE -!MESSAGE Possible choices for configuration are: -!MESSAGE -!MESSAGE "picomodel - Win32 Release" (based on "Win32 (x86) Static Library") -!MESSAGE "picomodel - Win32 Debug" (based on "Win32 (x86) Static Library") -!MESSAGE - -# Begin Project -# PROP AllowPerConfigDependencies 0 -# PROP Scc_ProjName "picomodel" -# PROP Scc_LocalPath ".." -CPP=cl.exe -RSC=rc.exe - -!IF "$(CFG)" == "picomodel - Win32 Release" - -# PROP BASE Use_MFC 0 -# PROP BASE Use_Debug_Libraries 0 -# PROP BASE Output_Dir "Release" -# PROP BASE Intermediate_Dir "Release" -# PROP BASE Target_Dir "" -# PROP Use_MFC 0 -# PROP Use_Debug_Libraries 0 -# PROP Output_Dir "Release" -# PROP Intermediate_Dir "Release" -# PROP Target_Dir "" -MTL=midl.exe -F90=df.exe -# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_MBCS" /D "_LIB" /YX /FD /c -# ADD CPP /nologo /MD /W3 /Zi /O2 /I ".." /D "WIN32" /D "NDEBUG" /D "_MBCS" /D "_LIB" /FR /FD /c -# SUBTRACT CPP /YX -# ADD BASE RSC /l 0x40c /d "NDEBUG" -# ADD RSC /l 0x40c /d "NDEBUG" -BSC32=bscmake.exe -# ADD BASE BSC32 /nologo -# ADD BSC32 /nologo -LIB32=link.exe -lib -# ADD BASE LIB32 /nologo -# ADD LIB32 /nologo - -!ELSEIF "$(CFG)" == "picomodel - Win32 Debug" - -# PROP BASE Use_MFC 0 -# PROP BASE Use_Debug_Libraries 1 -# PROP BASE Output_Dir "Debug" -# PROP BASE Intermediate_Dir "Debug" -# PROP BASE Target_Dir "" -# PROP Use_MFC 0 -# PROP Use_Debug_Libraries 1 -# PROP Output_Dir "Debug" -# PROP Intermediate_Dir "Debug" -# PROP Target_Dir "" -MTL=midl.exe -F90=df.exe -# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_MBCS" /D "_LIB" /YX /FD /GZ /c -# ADD CPP /nologo /MDd /W3 /Gm /ZI /Od /I ".." /D "WIN32" /D "_DEBUG" /D "_MBCS" /D "_LIB" /FR /FD /GZ /c -# SUBTRACT CPP /YX -# ADD BASE RSC /l 0x40c /d "_DEBUG" -# ADD RSC /l 0x40c /d "_DEBUG" -BSC32=bscmake.exe -# ADD BASE BSC32 /nologo -# ADD BSC32 /nologo -LIB32=link.exe -lib -# ADD BASE LIB32 /nologo -# ADD LIB32 /nologo - -!ENDIF - -# Begin Target - -# Name "picomodel - Win32 Release" -# Name "picomodel - Win32 Debug" -# Begin Group "src" - -# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat" -# Begin Group "lwo" - -# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat" -# Begin Source File - -SOURCE=.\lwo\clip.c -# End Source File -# Begin Source File - -SOURCE=.\lwo\envelope.c -# End Source File -# Begin Source File - -SOURCE=.\lwo\list.c -# End Source File -# Begin Source File - -SOURCE=.\lwo\lwio.c -# End Source File -# Begin Source File - -SOURCE=.\lwo\lwo2.c -# End Source File -# Begin Source File - -SOURCE=.\lwo\lwob.c -# End Source File -# Begin Source File - -SOURCE=.\lwo\pntspols.c -# End Source File -# Begin Source File - -SOURCE=.\lwo\surface.c -# End Source File -# Begin Source File - -SOURCE=.\lwo\vecmath.c -# End Source File -# Begin Source File - -SOURCE=.\lwo\vmap.c -# End Source File -# End Group -# Begin Source File - -SOURCE=.\picointernal.c -# End Source File -# Begin Source File - -SOURCE=.\picomodel.c -# End Source File -# Begin Source File - -SOURCE=.\picomodules.c -# End Source File -# Begin Source File - -SOURCE=.\pm_3ds.c -# End Source File -# Begin Source File - -SOURCE=.\pm_ase.c -# End Source File -# Begin Source File - -SOURCE=.\pm_fm.c -# End Source File -# Begin Source File - -SOURCE=.\pm_lwo.c -# End Source File -# Begin Source File - -SOURCE=.\pm_md2.c -# End Source File -# Begin Source File - -SOURCE=.\pm_md3.c -# End Source File -# Begin Source File - -SOURCE=.\pm_mdc.c -# End Source File -# Begin Source File - -SOURCE=.\pm_ms3d.c -# End Source File -# Begin Source File - -SOURCE=.\pm_obj.c -# End Source File -# Begin Source File - -SOURCE=.\pm_terrain.c -# End Source File -# End Group -# Begin Group "include" - -# PROP Default_Filter "h;hpp;hxx;hm;inl" -# Begin Source File - -SOURCE=.\lwo\lwo2.h -# End Source File -# Begin Source File - -SOURCE=.\picointernal.h -# End Source File -# Begin Source File - -SOURCE=..\picomodel.h -# End Source File -# Begin Source File - -SOURCE=.\pm_fm.h -# End Source File -# End Group -# End Target -# End Project diff --git a/tools/urt/libs/picomodel/picomodel.plg b/tools/urt/libs/picomodel/picomodel.plg deleted file mode 100644 index c8a6fff..0000000 --- a/tools/urt/libs/picomodel/picomodel.plg +++ /dev/null @@ -1,16 +0,0 @@ - - -
-

Build Log

-

---------------------Configuration: picomodel - Win32 Debug-------------------- -

-

Command Lines

- - - -

Results

-picomodel.lib - 0 error(s), 0 warning(s) -
- - diff --git a/tools/urt/libs/picomodel/picomodel.vcproj b/tools/urt/libs/picomodel/picomodel.vcproj deleted file mode 100644 index 442e02c..0000000 --- a/tools/urt/libs/picomodel/picomodel.vcproj +++ /dev/null @@ -1,713 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/tools/urt/libs/picomodel/picomodules.c b/tools/urt/libs/picomodel/picomodules.c deleted file mode 100644 index 9a97372..0000000 --- a/tools/urt/libs/picomodel/picomodules.c +++ /dev/null @@ -1,94 +0,0 @@ -/* ----------------------------------------------------------------------------- - - PicoModel Library - - Copyright (c) 2002, Randy Reddig & seaw0lf - All rights reserved. - - Redistribution and use in source and binary forms, with or without modification, - are permitted provided that the following conditions are met: - - Redistributions of source code must retain the above copyright notice, this list - of conditions and the following disclaimer. - - Redistributions in binary form must reproduce the above copyright notice, this - list of conditions and the following disclaimer in the documentation and/or - other materials provided with the distribution. - - Neither the names of the copyright holders nor the names of its contributors may - be used to endorse or promote products derived from this software without - specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR - ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - ----------------------------------------------------------------------------- */ - - - -/* marker */ -#define PICOMODULES_C - - - -/* dependencies */ -#include "picointernal.h" - - - -/* external modules */ -extern const picoModule_t picoModuleMD3; -extern const picoModule_t picoModule3DS; -extern const picoModule_t picoModuleASE; -extern const picoModule_t picoModuleOBJ; -extern const picoModule_t picoModuleMS3D; -extern const picoModule_t picoModuleMDC; -extern const picoModule_t picoModuleMD2; -extern const picoModule_t picoModuleFM; -extern const picoModule_t picoModuleLWO; -extern const picoModule_t picoModuleTerrain; - - - -/* list of all supported file format modules */ -const picoModule_t *picoModules[] = -{ - &picoModuleMD3, /* quake3 arena md3 */ - &picoModule3DS, /* autodesk 3ds */ - &picoModuleASE, /* autodesk ase */ - &picoModuleMS3D, /* milkshape3d */ - &picoModuleMDC, /* return to castle wolfenstein mdc */ - &picoModuleMD2, /* quake2 md2 */ - &picoModuleFM, /* heretic2 fm */ - &picoModuleLWO, /* lightwave object */ - &picoModuleTerrain, /* picoterrain object */ - &picoModuleOBJ, /* wavefront object */ - NULL /* arnold */ -}; - - - -/* - PicoModuleList() - returns a pointer to the module list and optionally stores - the number of supported modules in 'numModules'. Note that - this param can be NULL when the count is not needed. - */ - -const picoModule_t **PicoModuleList( int *numModules ){ - /* get module count */ - if ( numModules != NULL ) { - for ( ( *numModules ) = 0; picoModules[ *numModules ] != NULL; ( *numModules )++ ) ; - } - - /* return list of modules */ - return (const picoModule_t**) picoModules; -} diff --git a/tools/urt/libs/picomodel/pm_3ds.c b/tools/urt/libs/picomodel/pm_3ds.c deleted file mode 100644 index 9d84c47..0000000 --- a/tools/urt/libs/picomodel/pm_3ds.c +++ /dev/null @@ -1,782 +0,0 @@ -/* ----------------------------------------------------------------------------- - - PicoModel Library - - Copyright (c) 2002, Randy Reddig & seaw0lf - All rights reserved. - - Redistribution and use in source and binary forms, with or without modification, - are permitted provided that the following conditions are met: - - Redistributions of source code must retain the above copyright notice, this list - of conditions and the following disclaimer. - - Redistributions in binary form must reproduce the above copyright notice, this - list of conditions and the following disclaimer in the documentation and/or - other materials provided with the distribution. - - Neither the names of the copyright holders nor the names of its contributors may - be used to endorse or promote products derived from this software without - specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR - ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - ----------------------------------------------------------------------------- */ - - - -/* marker */ -#define PM_3DS_C - -/* dependencies */ -#include "picointernal.h" - -/* ydnar */ -static picoColor_t white = { 255,255,255,255 }; - -/* remarks: - * - 3ds file version is stored in pico special field 0 on load (ydnar: removed) - * todo: - * - sometimes there is one unnamed surface 0 having 0 verts as - * well as 0 faces. this error occurs since pm 0.6 (ydnar?) - */ -/* uncomment when debugging this module */ -/* #define DEBUG_PM_3DS - #define DEBUG_PM_3DS_EX */ - -/* structure holding persistent 3ds loader specific data used */ -/* to store formerly static vars to keep the module reentrant */ -/* safe. put everything that needs to be static in here. */ -typedef struct S3dsLoaderPers -{ - picoModel_t *model; /* ptr to output model */ - picoSurface_t *surface; /* ptr to current surface */ - picoShader_t *shader; /* ptr to current shader */ - picoByte_t *bufptr; /* ptr to raw data */ - char *basename; /* ptr to model base name (eg. jeep) */ - int cofs; - int maxofs; -} -T3dsLoaderPers; - -/* 3ds chunk types that we use */ -enum { - /* primary chunk */ - CHUNK_MAIN = 0x4D4D, - - /* main chunks */ - CHUNK_VERSION = 0x0002, - CHUNK_EDITOR_CONFIG = 0x3D3E, - CHUNK_EDITOR_DATA = 0x3D3D, - CHUNK_KEYFRAME_DATA = 0xB000, - - /* editor data sub chunks */ - CHUNK_MATERIAL = 0xAFFF, - CHUNK_OBJECT = 0x4000, - - /* material sub chunks */ - CHUNK_MATNAME = 0xA000, - CHUNK_MATDIFFUSE = 0xA020, - CHUNK_MATMAP = 0xA200, - CHUNK_MATMAPFILE = 0xA300, - - /* lets us know we're reading a new object */ - CHUNK_OBJECT_MESH = 0x4100, - - /* object mesh sub chunks */ - CHUNK_OBJECT_VERTICES = 0x4110, - CHUNK_OBJECT_FACES = 0x4120, - CHUNK_OBJECT_MATERIAL = 0x4130, - CHUNK_OBJECT_UV = 0x4140, -}; -#ifdef DEBUG_PM_3DS -static struct -{ - int id; - char *name; -} -debugChunkNames[] = -{ - { CHUNK_MAIN, "CHUNK_MAIN" }, - { CHUNK_VERSION, "CHUNK_VERSION" }, - { CHUNK_EDITOR_CONFIG, "CHUNK_EDITOR_CONFIG" }, - { CHUNK_EDITOR_DATA, "CHUNK_EDITOR_DATA" }, - { CHUNK_KEYFRAME_DATA, "CHUNK_KEYFRAME_DATA" }, - { CHUNK_MATERIAL, "CHUNK_MATERIAL" }, - { CHUNK_OBJECT, "CHUNK_OBJECT" }, - { CHUNK_MATNAME, "CHUNK_MATNAME" }, - { CHUNK_MATDIFFUSE, "CHUNK_MATDIFFUSE" }, - { CHUNK_MATMAP, "CHUNK_MATMAP" }, - { CHUNK_MATMAPFILE, "CHUNK_MATMAPFILE" }, - { CHUNK_OBJECT_MESH, "CHUNK_OBJECT_MESH" }, - { CHUNK_OBJECT_VERTICES, "CHUNK_OBJECT_VERTICES" }, - { CHUNK_OBJECT_FACES, "CHUNK_OBJECT_FACES" }, - { CHUNK_OBJECT_MATERIAL, "CHUNK_OBJECT_MATERIAL" }, - { CHUNK_OBJECT_UV, "CHUNK_OBJECT_UV" }, - { 0, NULL } -}; -static char *DebugGetChunkName( int id ){ - int i,max; /* imax? ;) */ - max = sizeof( debugChunkNames ) / sizeof( debugChunkNames[0] ); - - for ( i = 0; i < max; i++ ) - { - if ( debugChunkNames[i].id == id ) { - /* gaynux update -sea */ - return _pico_strlwr( debugChunkNames[i].name ); - } - } - return "chunk_unknown"; -} -#endif /*DEBUG_PM_3DS*/ - -/* this funky loader needs byte alignment */ -#pragma pack(push, 1) - -typedef struct S3dsIndices -{ - unsigned short a,b,c; - unsigned short visible; -} -T3dsIndices; - -typedef struct S3dsChunk -{ - unsigned short id; - unsigned int len; -} -T3dsChunk; - -/* restore previous data alignment */ -#pragma pack(pop) - -/* _3ds_canload: - * validates an autodesk 3ds model file. - */ -static int _3ds_canload( PM_PARAMS_CANLOAD ){ - T3dsChunk *chunk; - - /* to keep the compiler happy */ - *fileName = *fileName; - - /* sanity check */ - if ( bufSize < sizeof( T3dsChunk ) ) { - return PICO_PMV_ERROR_SIZE; - } - - /* get pointer to 3ds header chunk */ - chunk = (T3dsChunk *)buffer; - - /* check data length */ - if ( bufSize < _pico_little_long( chunk->len ) ) { - return PICO_PMV_ERROR_SIZE; - } - - /* check 3ds magic */ - if ( _pico_little_short( chunk->id ) != CHUNK_MAIN ) { - return PICO_PMV_ERROR_IDENT; - } - - /* file seems to be a valid 3ds */ - return PICO_PMV_OK; -} - -static T3dsChunk *GetChunk( T3dsLoaderPers *pers ){ - T3dsChunk *chunk; - - /* sanity check */ - if ( pers->cofs > pers->maxofs ) { - return 0; - } - -#ifdef DEBUG_PM_3DS -/* printf("GetChunk: pers->cofs %x\n",pers->cofs); */ -#endif - /* fill in pointer to chunk */ - chunk = (T3dsChunk *)&pers->bufptr[ pers->cofs ]; - if ( !chunk ) { - return NULL; - } - - chunk->id = _pico_little_short( chunk->id ); - chunk->len = _pico_little_long( chunk->len ); - - /* advance in buffer */ - pers->cofs += sizeof( T3dsChunk ); - - /* this means yay */ - return chunk; -} - -static int GetASCIIZ( T3dsLoaderPers *pers, char *dest, int max ){ - int pos = 0; - int ch; - - for (;; ) - { - ch = pers->bufptr[ pers->cofs++ ]; - if ( ch == '\0' ) { - break; - } - if ( pers->cofs >= pers->maxofs ) { - dest[ pos ] = '\0'; - return 0; - } - dest[ pos++ ] = ch; - if ( pos >= max ) { - break; - } - } - dest[ pos ] = '\0'; - return 1; -} - -static picoByte_t GetByte( T3dsLoaderPers *pers ){ - picoByte_t *value; - - /* sanity check */ - if ( pers->cofs > pers->maxofs ) { - return 0; - } - - /* get and return value */ - value = (picoByte_t *)( pers->bufptr + pers->cofs ); - pers->cofs += 1; - return *value; -} - -static int GetWord( T3dsLoaderPers *pers ){ - unsigned short *value; - - /* sanity check */ - if ( pers->cofs > pers->maxofs ) { - return 0; - } - - /* get and return value */ - value = (unsigned short *)( pers->bufptr + pers->cofs ); - pers->cofs += 2; - return _pico_little_short( *value ); -} - -static float GetFloat( T3dsLoaderPers *pers ){ - float *value; - - /* sanity check */ - if ( pers->cofs > pers->maxofs ) { - return 0; - } - - /* get and return value */ - value = (float *)( pers->bufptr + pers->cofs ); - pers->cofs += 4; - return _pico_little_float( *value ); -} - -static int GetMeshVertices( T3dsLoaderPers *pers ){ - int numVerts; - int i; - - /* get number of verts for this surface */ - numVerts = GetWord( pers ); - -#ifdef DEBUG_PM_3DS - printf( "GetMeshVertices: numverts %d\n",numVerts ); -#endif - /* read in vertices for current surface */ - for ( i = 0; i < numVerts; i++ ) - { - picoVec3_t v; - v[0] = GetFloat( pers ); - v[1] = GetFloat( pers ); /* ydnar: unflipped */ - v[2] = GetFloat( pers ); /* ydnar: unflipped and negated */ - - /* add current vertex */ - PicoSetSurfaceXYZ( pers->surface,i,v ); - PicoSetSurfaceColor( pers->surface,0,i,white ); /* ydnar */ - -#ifdef DEBUG_PM_3DS_EX - printf( "Vertex: x: %f y: %f z: %f\n",v[0],v[1],v[2] ); -#endif - } - /* success (no errors occured) */ - return 1; -} - -static int GetMeshFaces( T3dsLoaderPers *pers ){ - int numFaces; - int i; - - /* get number of faces for this surface */ - numFaces = GetWord( pers ); - -#ifdef DEBUG_PM_3DS - printf( "GetMeshFaces: numfaces %d\n",numFaces ); -#endif - /* read in vertex indices for current surface */ - for ( i = 0; i < numFaces; i++ ) - { - /* remember, we only need 3 of 4 values read in for each */ - /* face. the 4th value is a vis flag for 3dsmax which is */ - /* being ignored by us here */ - T3dsIndices face; - face.a = GetWord( pers ); - face.c = GetWord( pers ); /* ydnar: flipped order */ - face.b = GetWord( pers ); /* ydnar: flipped order */ - face.visible = GetWord( pers ); - - /* copy indexes */ - PicoSetSurfaceIndex( pers->surface, ( i * 3 + 0 ), (picoIndex_t)face.a ); - PicoSetSurfaceIndex( pers->surface, ( i * 3 + 1 ), (picoIndex_t)face.b ); - PicoSetSurfaceIndex( pers->surface, ( i * 3 + 2 ), (picoIndex_t)face.c ); - -#ifdef DEBUG_PM_3DS_EX - printf( "Face: a: %d b: %d c: %d (%d)\n",face.a,face.b,face.c,face.visible ); -#endif - } - /* success (no errors occured) */ - return 1; -} - -static int GetMeshTexCoords( T3dsLoaderPers *pers ){ - int numTexCoords; - int i; - - /* get number of uv coords for this surface */ - numTexCoords = GetWord( pers ); - -#ifdef DEBUG_PM_3DS - printf( "GetMeshTexCoords: numcoords %d\n",numTexCoords ); -#endif - /* read in uv coords for current surface */ - for ( i = 0; i < numTexCoords; i++ ) - { - picoVec2_t uv; - uv[0] = GetFloat( pers ); - uv[1] = -GetFloat( pers ); /* ydnar: we use origin at bottom */ - - /* to make sure we don't mess up memory */ - if ( pers->surface == NULL ) { - continue; - } - - /* add current uv */ - PicoSetSurfaceST( pers->surface,0,i,uv ); - -#ifdef DEBUG_PM_3DS_EX - printf( "u: %f v: %f\n",uv[0],uv[1] ); -#endif - } - /* success (no errors occured) */ - return 1; -} - -static int GetMeshShader( T3dsLoaderPers *pers ){ - char shaderName[255] = { 0 }; - picoShader_t *shader; - int numSharedVerts; - int setShaderName = 0; - int i; - - /* the shader is either the color or the texture map of the */ - /* object. it can also hold other information like the brightness, */ - /* shine, etc. stuff we don't really care about. we just want the */ - /* color, or the texture map file name really */ - - /* get in the shader name */ - if ( !GetASCIIZ( pers,shaderName,sizeof( shaderName ) ) ) { - return 0; - } - - /* ydnar: trim to first whitespace */ - _pico_first_token( shaderName ); - - /* now that we have the shader name we need to go through all of */ - /* the shaders and check the name against each shader. when we */ - /* find a shader in our shader list that matches this name we */ - /* just read in, then we assign the shader's id of the object to */ - /* that shader */ - - /* get shader id for shader name */ - shader = PicoFindShader( pers->model, shaderName, 1 ); - - /* we've found a matching shader */ - if ( ( shader != NULL ) && pers->surface ) { - char mapName[1024 + 1]; - char *mapNamePtr; - memset( mapName,0,sizeof( mapName ) ); - - /* get ptr to shader's map name */ - mapNamePtr = PicoGetShaderMapName( shader ); - - /* we have a valid map name ptr */ - if ( mapNamePtr != NULL ) { - char temp[128]; - const char *name; - - /* copy map name to local buffer */ - strcpy( mapName,mapNamePtr ); - - /* extract file name */ - name = _pico_nopath( mapName ); - strncpy( temp, name, sizeof( temp ) ); - - /* remove file extension */ - /* name = _pico_setfext( name,"" ); */ - - /* assign default name if no name available */ - if ( strlen( temp ) < 1 ) { - strcpy( temp,pers->basename ); - } - - /* build shader name */ - _pico_strlwr( temp ); /* gaynux update -sea */ - sprintf( mapName,"models/mapobjects/%s/%s",pers->basename,temp ); - - /* set shader name */ - /* PicoSetShaderName( shader,mapName ); */ /* ydnar: this will screw up the named shader */ - - /* set surface's shader index */ - PicoSetSurfaceShader( pers->surface, shader ); - - setShaderName = 1; - } - } - /* we didn't set a shader name; throw out warning */ - if ( !setShaderName ) { - _pico_printf( PICO_WARNING,"3DS mesh is missing shader name" ); - } - /* we don't process the list of shared vertices here; there is a */ - /* short int that gives the number of faces of the mesh concerned */ - /* by this shader, then there is the list itself of these faces. */ - /* 0000 means the first face of the (4120) face list */ - - /* get number of shared verts */ - numSharedVerts = GetWord( pers ); - -#ifdef DEBUG_PM_3DS - printf( "GetMeshShader: uses shader '%s' (nsv %d)\n",shaderName,numSharedVerts ); -#endif - /* skip list of shared verts */ - for ( i = 0; i < numSharedVerts; i++ ) - { - GetWord( pers ); - } - /* success (no errors occured) */ - return 1; -} - -static int GetDiffuseColor( T3dsLoaderPers *pers ){ - /* todo: support all 3ds specific color formats; */ - /* that means: rgb,tru,trug,rgbg */ - - /* get rgb color (range 0..255; 3 bytes) */ - picoColor_t color; - - color[0] = GetByte( pers ); - color[1] = GetByte( pers ); - color[2] = GetByte( pers ); - color[3] = 255; - - /* store this as the current shader's diffuse color */ - if ( pers->shader ) { - PicoSetShaderDiffuseColor( pers->shader,color ); - } -#ifdef DEBUG_PM_3DS - printf( "GetDiffuseColor: %d %d %d\n",color[0],color[1],color[2] ); -#endif - /* success (no errors occured) */ - return 1; -} - -static int DoNextEditorDataChunk( T3dsLoaderPers *pers, long endofs ){ - T3dsChunk *chunk; - -#ifdef DEBUG_PM_3DS_EX - printf( "DoNextEditorDataChunk: endofs %d\n",endofs ); -#endif - while ( pers->cofs < endofs ) - { - long nextofs = pers->cofs; - if ( ( chunk = GetChunk( pers ) ) == NULL ) { - return 0; - } - if ( !chunk->len ) { - return 0; - } - nextofs += chunk->len; - -#ifdef DEBUG_PM_3DS_EX - printf( "Chunk %04x (%s), len %d pers->cofs %x\n",chunk->id,DebugGetChunkName( chunk->id ),chunk->len,pers->cofs ); -#endif - /*** meshes ***/ - if ( chunk->id == CHUNK_OBJECT ) { - picoSurface_t *surface; - char surfaceName[ 0xff ] = { 0 }; - - /* read in surface name */ - if ( !GetASCIIZ( pers,surfaceName,sizeof( surfaceName ) ) ) { - return 0; /* this is bad */ - - } -//PicoGetSurfaceName - /* ignore NULL name surfaces */ -// if( surfaceName - - /* allocate a pico surface */ - surface = PicoNewSurface( pers->model ); - if ( surface == NULL ) { - pers->surface = NULL; - return 0; /* this is bad too */ - } - /* assign ptr to current surface */ - pers->surface = surface; - - /* 3ds models surfaces are all triangle meshes */ - PicoSetSurfaceType( pers->surface,PICO_TRIANGLES ); - - /* set surface name */ - PicoSetSurfaceName( pers->surface,surfaceName ); - - /* continue mess with object's sub chunks */ - DoNextEditorDataChunk( pers,nextofs ); - continue; - } - if ( chunk->id == CHUNK_OBJECT_MESH ) { - /* continue mess with mesh's sub chunks */ - if ( !DoNextEditorDataChunk( pers,nextofs ) ) { - return 0; - } - continue; - } - if ( chunk->id == CHUNK_OBJECT_VERTICES ) { - if ( !GetMeshVertices( pers ) ) { - return 0; - } - continue; - } - if ( chunk->id == CHUNK_OBJECT_FACES ) { - if ( !GetMeshFaces( pers ) ) { - return 0; - } - continue; - } - if ( chunk->id == CHUNK_OBJECT_UV ) { - if ( !GetMeshTexCoords( pers ) ) { - return 0; - } - continue; - } - if ( chunk->id == CHUNK_OBJECT_MATERIAL ) { - if ( !GetMeshShader( pers ) ) { - return 0; - } - continue; - } - /*** materials ***/ - if ( chunk->id == CHUNK_MATERIAL ) { - /* new shader specific things should be */ - /* initialized right here */ - picoShader_t *shader; - - /* allocate a pico shader */ - shader = PicoNewShader( pers->model ); /* ydnar */ - if ( shader == NULL ) { - pers->shader = NULL; - return 0; /* this is bad too */ - } - - /* assign ptr to current shader */ - pers->shader = shader; - - /* continue and process the material's sub chunks */ - DoNextEditorDataChunk( pers,nextofs ); - continue; - } - if ( chunk->id == CHUNK_MATNAME ) { - /* new material's names should be stored here. note that */ - /* GetMeshMaterial returns the name of the material that */ - /* is used by the mesh. new material names are set HERE. */ - /* but for now we skip the new material's name ... */ - if ( pers->shader ) { - char *name = (char*) ( pers->bufptr + pers->cofs ); - char *cleanedName = _pico_clone_alloc( name ); - _pico_first_token( cleanedName ); - PicoSetShaderName( pers->shader, cleanedName ); -#ifdef DEBUG_PM_3DS - printf( "NewShader: '%s'\n", cleanedName ); -#endif - _pico_free( cleanedName ); - } - } - if ( chunk->id == CHUNK_MATDIFFUSE ) { - /* todo: color for last inserted new material should be */ - /* stored somewhere by GetDiffuseColor */ - if ( !GetDiffuseColor( pers ) ) { - return 0; - } - - /* rest of chunk is skipped here */ - } - if ( chunk->id == CHUNK_MATMAP ) { - /* continue and process the material map sub chunks */ - DoNextEditorDataChunk( pers,nextofs ); - continue; - } - if ( chunk->id == CHUNK_MATMAPFILE ) { - /* map file name for last inserted new material should */ - /* be stored here. but for now we skip this too ... */ - if ( pers->shader ) { - char *name = (char *)( pers->bufptr + pers->cofs ); - PicoSetShaderMapName( pers->shader,name ); -#ifdef DEBUG_PM_3DS - printf( "NewShaderMapfile: '%s'\n",name ); -#endif - } - } - /*** keyframes ***/ - if ( chunk->id == CHUNK_KEYFRAME_DATA ) { - /* well umm, this is a bit too much since we don't really */ - /* need model animation sequences right now. we skip this */ -#ifdef DEBUG_PM_3DS - printf( "KeyframeData: len %d\n",chunk->len ); -#endif - } - /* skip unknown chunk */ - pers->cofs = nextofs; - if ( pers->cofs >= pers->maxofs ) { - break; - } - } - return 1; -} - -static int DoNextChunk( T3dsLoaderPers *pers, int endofs ){ - T3dsChunk *chunk; - -#ifdef DEBUG_PM_3DS - printf( "DoNextChunk: endofs %d\n",endofs ); -#endif - while ( pers->cofs < endofs ) - { - long nextofs = pers->cofs; - if ( ( chunk = GetChunk( pers ) ) == NULL ) { - return 0; - } - if ( !chunk->len ) { - return 0; - } - nextofs += chunk->len; - -#ifdef DEBUG_PM_3DS_EX - printf( "Chunk %04x (%s), len %d pers->cofs %x\n",chunk->id,DebugGetChunkName( chunk->id ),chunk->len,pers->cofs ); -#endif - /*** version ***/ - if ( chunk->id == CHUNK_VERSION ) { - /* at this point i get the 3ds file version. since there */ - /* might be new additions to the 3ds file format in 4.0 */ - /* it might be a good idea to store the version somewhere */ - /* for later handling or message displaying */ - - /* get the version */ - int version; - version = GetWord( pers ); - GetWord( pers ); -#ifdef DEBUG_PM_3DS - printf( "FileVersion: %d\n",version ); -#endif - - /* throw out a warning for version 4 models */ - if ( version == 4 ) { - _pico_printf( PICO_WARNING, - "3DS version is 4. Model might load incorrectly." ); - } - /* store the 3ds file version in pico special field 0 */ - /* PicoSetSurfaceSpecial(pers->surface,0,version); */ /* ydnar: this was causing a crash accessing uninitialized surface */ - - /* rest of chunk is skipped here */ - } - /*** editor data ***/ - if ( chunk->id == CHUNK_EDITOR_DATA ) { - if ( !DoNextEditorDataChunk( pers,nextofs ) ) { - return 0; - } - continue; - } - /* skip unknown chunk */ - pers->cofs = nextofs; - if ( pers->cofs >= pers->maxofs ) { - break; - } - } - return 1; -} - -/* _3ds_load: - * loads an autodesk 3ds model file. - */ -static picoModel_t *_3ds_load( PM_PARAMS_LOAD ){ - T3dsLoaderPers pers; - picoModel_t *model; - char basename[128]; - - /* create a new pico model */ - model = PicoNewModel(); - if ( model == NULL ) { - /* user must have some serious ram problems ;) */ - return NULL; - } - /* get model's base name (eg. jeep from c:\models\jeep.3ds) */ - memset( basename,0,sizeof( basename ) ); - strncpy( basename,_pico_nopath( fileName ),sizeof( basename ) ); - _pico_setfext( basename,"" ); - - /* initialize persistant vars (formerly static) */ - pers.model = model; - pers.bufptr = (picoByte_t *)buffer; - pers.basename = (char *)basename; - pers.maxofs = bufSize; - pers.cofs = 0L; - - /* do model setup */ - PicoSetModelFrameNum( model,frameNum ); - PicoSetModelName( model,fileName ); - PicoSetModelFileName( model,fileName ); - - /* skip first chunk in file (magic) */ - GetChunk( &pers ); - - /* process chunks */ - if ( !DoNextChunk( &pers,pers.maxofs ) ) { - /* well, bleh i guess */ - PicoFreeModel( model ); - return NULL; - } - /* return allocated pico model */ - return model; -} - -/* pico file format module definition */ -const picoModule_t picoModule3DS = -{ - "0.86-b", /* module version string */ - "Autodesk 3Dstudio", /* module display name */ - "seaw0lf", /* author's name */ - "2002 seaw0lf", /* module copyright */ - { - "3ds",NULL,NULL,NULL /* default extensions to use */ - }, - _3ds_canload, /* validation routine */ - _3ds_load, /* load routine */ - NULL, /* save validation routine */ - NULL /* save routine */ -}; diff --git a/tools/urt/libs/picomodel/pm_ase.c b/tools/urt/libs/picomodel/pm_ase.c deleted file mode 100644 index fd20565..0000000 --- a/tools/urt/libs/picomodel/pm_ase.c +++ /dev/null @@ -1,1419 +0,0 @@ -/* ----------------------------------------------------------------------------- - - PicoModel Library - - Copyright (c) 2002, Randy Reddig & seaw0lf - All rights reserved. - - Redistribution and use in source and binary forms, with or without modification, - are permitted provided that the following conditions are met: - - Redistributions of source code must retain the above copyright notice, this list - of conditions and the following disclaimer. - - Redistributions in binary form must reproduce the above copyright notice, this - list of conditions and the following disclaimer in the documentation and/or - other aseMaterialList provided with the distribution. - - Neither the names of the copyright holders nor the names of its contributors may - be used to endorse or promote products derived from this software without - specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR - ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - ----------------------------------------------------------------------------- */ - -void Sys_Printf( const char *format, ... ); - -/* marker */ -#define PM_ASE_C - -/* uncomment when debugging this module */ -//#define DEBUG_PM_ASE -//#define DEBUG_PM_ASE_EX - - -/* dependencies */ -#include "picointernal.h" - -#ifdef DEBUG_PM_ASE -#include "time.h" -#endif - -/* plain white */ -static picoColor_t white = { 255, 255, 255, 255 }; - -/* jhefty - multi-subobject material support */ - -/* Material/SubMaterial management */ -/* A material should have 1..n submaterials assigned to it */ - -typedef struct aseSubMaterial_s -{ - struct aseSubMaterial_s* next; - int subMtlId; - picoShader_t* shader; - -} aseSubMaterial_t; - -typedef struct aseMaterial_s -{ - struct aseMaterial_s* next; - struct aseSubMaterial_s* subMtls; - int mtlId; -} aseMaterial_t; - -/* Material/SubMaterial management functions */ -static aseMaterial_t* _ase_get_material( aseMaterial_t* list, int mtlIdParent ){ - aseMaterial_t* mtl = list; - - while ( mtl ) - { - if ( mtlIdParent == mtl->mtlId ) { - break; - } - mtl = mtl->next; - } - return mtl; -} - -static aseSubMaterial_t* _ase_get_submaterial( aseMaterial_t* list, int mtlIdParent, int subMtlId ){ - aseMaterial_t* parent = _ase_get_material( list, mtlIdParent ); - aseSubMaterial_t* subMtl = NULL; - - if ( !parent ) { - _pico_printf( PICO_ERROR, "No ASE material exists with id %i\n", mtlIdParent ); - return NULL; - } - - subMtl = parent->subMtls; - while ( subMtl ) - { - if ( subMtlId == subMtl->subMtlId ) { - break; - } - subMtl = subMtl->next; - } - return subMtl; -} - -aseSubMaterial_t* _ase_get_submaterial_or_default( aseMaterial_t* materials, int mtlIdParent, int subMtlId ){ - aseSubMaterial_t* subMtl = _ase_get_submaterial( materials, mtlIdParent, subMtlId ); - if ( subMtl != NULL ) { - return subMtl; - } - - /* ydnar: trying default submaterial */ - subMtl = _ase_get_submaterial( materials, mtlIdParent, 0 ); - if ( subMtl != NULL ) { - return subMtl; - } - - _pico_printf( PICO_ERROR, "Could not find material/submaterial for id %d/%d\n", mtlIdParent, subMtlId ); - return NULL; -} - - - - -static aseMaterial_t* _ase_add_material( aseMaterial_t **list, int mtlIdParent ){ - aseMaterial_t *mtl = _pico_calloc( 1, sizeof( aseMaterial_t ) ); - mtl->mtlId = mtlIdParent; - mtl->subMtls = NULL; - mtl->next = *list; - *list = mtl; - - return mtl; -} - -static aseSubMaterial_t* _ase_add_submaterial( aseMaterial_t **list, int mtlIdParent, int subMtlId, picoShader_t* shader ){ - aseMaterial_t *parent = _ase_get_material( *list, mtlIdParent ); - aseSubMaterial_t *subMtl = _pico_calloc( 1, sizeof( aseSubMaterial_t ) ); - - if ( !parent ) { - parent = _ase_add_material( list, mtlIdParent ); - } - - subMtl->shader = shader; - subMtl->subMtlId = subMtlId; - subMtl->next = parent->subMtls; - parent->subMtls = subMtl; - - return subMtl; -} - -static void _ase_free_materials( aseMaterial_t **list ){ - aseMaterial_t* mtl = *list; - aseSubMaterial_t* subMtl = NULL; - - aseMaterial_t* mtlTemp = NULL; - aseSubMaterial_t* subMtlTemp = NULL; - - while ( mtl ) - { - subMtl = mtl->subMtls; - while ( subMtl ) - { - subMtlTemp = subMtl->next; - _pico_free( subMtl ); - subMtl = subMtlTemp; - } - mtlTemp = mtl->next; - _pico_free( mtl ); - mtl = mtlTemp; - } - ( *list ) = NULL; -} - -#ifdef DEBUG_PM_ASE -static void _ase_print_materials( aseMaterial_t *list ){ - aseMaterial_t* mtl = list; - aseSubMaterial_t* subMtl = NULL; - - while ( mtl ) - { - _pico_printf( PICO_NORMAL, "ASE Material %i", mtl->mtlId ); - subMtl = mtl->subMtls; - while ( subMtl ) - { - _pico_printf( PICO_NORMAL, " -- ASE SubMaterial %i - %s\n", subMtl->subMtlId, subMtl->shader->name ); - subMtl = subMtl->next; - } - mtl = mtl->next; - } -} -#endif //DEBUG_PM_ASE - -/* todo: - * - apply material specific uv offsets to uv coordinates - */ - -/* _ase_canload: - * validates a 3dsmax ase model file. - */ -static int _ase_canload( PM_PARAMS_CANLOAD ){ - picoParser_t *p; - - - /* quick data length validation */ - if ( bufSize < 80 ) { - return PICO_PMV_ERROR_SIZE; - } - - /* keep the friggin compiler happy */ - *fileName = *fileName; - - /* create pico parser */ - p = _pico_new_parser( (picoByte_t*) buffer, bufSize ); - if ( p == NULL ) { - return PICO_PMV_ERROR_MEMORY; - } - - /* get first token */ - if ( _pico_parse_first( p ) == NULL ) { - return PICO_PMV_ERROR_IDENT; - } - - /* check first token */ - if ( _pico_stricmp( p->token, "*3dsmax_asciiexport" ) ) { - _pico_free_parser( p ); - return PICO_PMV_ERROR_IDENT; - } - - /* free the pico parser object */ - _pico_free_parser( p ); - - /* file seems to be a valid ase file */ - return PICO_PMV_OK; -} - -typedef struct aseVertex_s aseVertex_t; -struct aseVertex_s -{ - picoVec3_t xyz; - picoIndex_t id; -}; - -typedef struct aseTexCoord_s aseTexCoord_t; -struct aseTexCoord_s -{ - picoVec2_t texcoord; -}; - -typedef struct aseColor_s aseColor_t; -struct aseColor_s -{ - picoColor_t color; -}; - -typedef struct aseFace_s aseFace_t; -struct aseFace_s -{ - picoIndex_t indices[9]; - picoIndex_t smoothingGroup; - picoIndex_t materialId; - picoIndex_t subMaterialId; - picoVec3_t facenormal; - picoVec3_t vertexnormal[3]; -}; -typedef aseFace_t* aseFacesIter_t; - -picoSurface_t* PicoModelFindOrAddSurface( picoModel_t *model, picoShader_t* shader ){ - /* see if a surface already has the shader */ - int i = 0; - for ( ; i < model->numSurfaces ; i++ ) - { - picoSurface_t* workSurface = model->surface[i]; - if ( workSurface->shader == shader ) { - return workSurface; - } - } - - /* no surface uses this shader yet, so create a new surface */ - - { - /* create a new surface in the model for the unique shader */ - picoSurface_t* workSurface = PicoNewSurface( model ); - if ( !workSurface ) { - _pico_printf( PICO_ERROR, "Could not allocate a new surface!\n" ); - return 0; - } - - /* do surface setup */ - PicoSetSurfaceType( workSurface, PICO_TRIANGLES ); - PicoSetSurfaceName( workSurface, shader->name ); - PicoSetSurfaceShader( workSurface, shader ); - - return workSurface; - } -} - -/* _ase_submit_triangles - jhefty - use the surface and the current face list to look up material/submaterial IDs - and submit them to the model for proper processing - - The following still holds from ydnar's _ase_make_surface: - indexes 0 1 2 = vert indexes - indexes 3 4 5 = st indexes - indexes 6 7 8 = color indexes (new) - */ - -#if 0 -typedef picoIndex_t* picoIndexIter_t; - -typedef struct aseUniqueIndices_s aseUniqueIndices_t; -struct aseUniqueIndices_s -{ - picoIndex_t* data; - picoIndex_t* last; - - aseFace_t* faces; -}; - -size_t aseUniqueIndices_size( aseUniqueIndices_t* self ){ - return self->last - self->data; -} - -void aseUniqueIndices_reserve( aseUniqueIndices_t* self, picoIndex_t size ){ - self->data = self->last = (picoIndex_t*)_pico_calloc( size, sizeof( picoIndex_t ) ); -} - -void aseUniqueIndices_clear( aseUniqueIndices_t* self ){ - _pico_free( self->data ); -} - -void aseUniqueIndices_pushBack( aseUniqueIndices_t* self, picoIndex_t index ){ - *self->last++ = index; -} - -picoIndex_t aseFaces_getVertexIndex( aseFace_t* faces, picoIndex_t index ){ - return faces[index / 3].indices[index % 3]; -} - -picoIndex_t aseFaces_getTexCoordIndex( aseFace_t* faces, picoIndex_t index ){ - return faces[index / 3].indices[( index % 3 ) + 3]; -} - -picoIndex_t aseFaces_getColorIndex( aseFace_t* faces, picoIndex_t index ){ - return faces[index / 3].indices[( index % 3 ) + 6]; -} - -int aseUniqueIndex_equal( aseFace_t* faces, picoIndex_t index, picoIndex_t other ){ - return aseFaces_getVertexIndex( faces, index ) == aseFaces_getVertexIndex( faces, other ) - && aseFaces_getTexCoordIndex( faces, index ) == aseFaces_getTexCoordIndex( faces, other ) - && aseFaces_getColorIndex( faces, index ) == aseFaces_getColorIndex( faces, other ); -} - -picoIndex_t aseUniqueIndices_insertUniqueVertex( aseUniqueIndices_t* self, picoIndex_t index ){ - picoIndexIter_t i = self->data; - for (; i != self->last; ++i ) - { - picoIndex_t other = (picoIndex_t)( i - self->data ); - if ( aseUniqueIndex_equal( self->faces, index, other ) ) { - return other; - } - } - - aseUniqueIndices_pushBack( self, index ); - return (picoIndex_t)( aseUniqueIndices_size( self ) - 1 ); -} - -static void _ase_submit_triangles_unshared( picoModel_t* model, aseMaterial_t* materials, aseVertex_t* vertices, aseTexCoord_t* texcoords, aseColor_t* colors, aseFace_t* faces, int numFaces, int meshHasNormals ){ - aseFacesIter_t i = faces, end = faces + numFaces; - - aseUniqueIndices_t indices; - aseUniqueIndices_t remap; - aseUniqueIndices_reserve( &indices, numFaces * 3 ); - aseUniqueIndices_reserve( &remap, numFaces * 3 ); - indices.faces = faces; - - for (; i != end; ++i ) - { - /* look up the shader for the material/submaterial pair */ - aseSubMaterial_t* subMtl = _ase_get_submaterial_or_default( materials, ( *i ).materialId, ( *i ).subMaterialId ); - if ( subMtl == NULL ) { - return; - } - - { - picoSurface_t* surface = PicoModelFindOrAddSurface( model, subMtl->shader ); - int j; - /* we pull the data from the vertex, color and texcoord arrays using the face index data */ - for ( j = 0 ; j < 3 ; j++ ) - { - picoIndex_t index = (picoIndex_t)( ( ( i - faces ) * 3 ) + j ); - picoIndex_t size = (picoIndex_t)aseUniqueIndices_size( &indices ); - picoIndex_t unique = aseUniqueIndices_insertUniqueVertex( &indices, index ); - - picoIndex_t numVertexes = PicoGetSurfaceNumVertexes( surface ); - picoIndex_t numIndexes = PicoGetSurfaceNumIndexes( surface ); - - aseUniqueIndices_pushBack( &remap, numIndexes ); - - PicoSetSurfaceIndex( surface, numIndexes, remap.data[unique] ); - - if ( unique == size ) { - PicoSetSurfaceXYZ( surface, numVertexes, vertices[( *i ).indices[j]].xyz ); - PicoSetSurfaceNormal( surface, numVertexes, vertices[( *i ).indices[j]].normal ); - PicoSetSurfaceST( surface, 0, numVertexes, texcoords[( *i ).indices[j + 3]].texcoord ); - - if ( ( *i ).indices[j + 6] >= 0 ) { - PicoSetSurfaceColor( surface, 0, numVertexes, colors[( *i ).indices[j + 6]].color ); - } - else - { - PicoSetSurfaceColor( surface, 0, numVertexes, white ); - } - - PicoSetSurfaceSmoothingGroup( surface, numVertexes, ( vertices[( *i ).indices[j]].id * ( 1 << 16 ) ) + ( *i ).smoothingGroup ); - } - } - } - } - - aseUniqueIndices_clear( &indices ); - aseUniqueIndices_clear( &remap ); -} - -#endif - -static int VectorCompareExtn( picoVec3_t n1, picoVec3_t n2, float epsilon ){ - int i; - - - /* test */ - for ( i = 0; i < 3; i++ ) - if ( fabs( n1[ i ] - n2[ i ] ) > epsilon ) { - return -1; - } - return 1; -} - -#define CrossProductTemp( a,b,c ) ( ( c )[0] = ( a )[1] * ( b )[2] - ( a )[2] * ( b )[1],( c )[1] = ( a )[2] * ( b )[0] - ( a )[0] * ( b )[2],( c )[2] = ( a )[0] * ( b )[1] - ( a )[1] * ( b )[0] ) - - -#define MAX_FACEREFS 64 -//maximum number of faces that can share a vert. likely 1-4, but who knows. -typedef struct -{ - int count; - aseFace_t* faces[MAX_FACEREFS]; -} faceref_t; - -static void _ase_submit_triangles( picoModel_t* model, aseMaterial_t* materials, aseVertex_t* vertices, aseTexCoord_t* texcoords, aseColor_t* colors, aseFace_t* faces, int numFaces,int numVerts, int submodel ){ - - picoVec3_t accum; - int index; - int counter; - faceref_t* faceref; - int *normalsC; - int fc = 0; - - aseFacesIter_t i = faces, end = faces + numFaces; - counter = 0; - - - //allocate room for sg optimization - faceref = (faceref_t*)malloc( numVerts * sizeof( faceref_t ) ); - memset( faceref,0,numVerts * sizeof( faceref_t ) ); - - //rebuild face normals - for ( i = faces; i != end; ++i ) - { - - picoVec3_t a,b,c; - picoVec3_t v1,v2,v3; - int j; - counter++; - - for ( j = 0; j < 3; j++ ) - { - a[j] = vertices[( *i ).indices[0]].xyz[j]; - b[j] = vertices[( *i ).indices[1]].xyz[j]; - c[j] = vertices[( *i ).indices[2]].xyz[j]; - } - for ( j = 0; j < 3; j++ ) - { - v1[j] = a[j] - b[j]; - v2[j] = c[j] - b[j]; - } - - CrossProductTemp( v1,v2,v3 ); - _pico_normalize_vec( v3 ); - ( *i ).facenormal[0] = v3[0]; - ( *i ).facenormal[1] = v3[1]; - ( *i ).facenormal[2] = v3[2]; - - - //throw this face into the index pools - for ( j = 0 ; j < 3 ; j++ ) - { - index = ( *i ).indices[j]; - if ( faceref[index].count >= MAX_FACEREFS - 1 ) { - - } - else - { - faceref[index].faces[faceref[index].count++] = i; - } - } - - } - - //if (counter>0) Sys_Printf( "Rebuilding %d Normals\n", counter * 3 ); - for ( i = faces; i != end; ++i ) - { - /* look up the shader for the material/submaterial pair */ - aseSubMaterial_t* subMtl = _ase_get_submaterial_or_default( materials, ( *i ).materialId, ( *i ).subMaterialId ); - - if ( subMtl == NULL ) { - continue; - } - - { - picoVec3_t* xyz[3]; - picoVec3_t *a[3]; - picoVec3_t* normal[3]; - picoVec2_t* st[3]; - picoColor_t* color[3]; - picoIndex_t smooth[3]; - - int j,z; - - - - /* we pull the data from the vertex, color and texcoord arrays using the face index data */ - for ( j = 0 ; j < 3 ; j++ ) - { - aseFacesIter_t q = faces; - aseFacesIter_t qend = faces + numFaces; - - xyz[j] = &vertices[( *i ).indices[j]].xyz; - - // Use Face normal - normal[j] = &( *i ).facenormal; - - - //Oooor we can use the smoothing group - - //Slow method, but testing - //Find All faces that use this vertex, average their facenormals. - // skip where smoothgroups both equal 0, or don't have any shared bits (x & y) - index = ( *i ).indices[j]; - - accum[0] = ( *i ).facenormal[0]; - accum[1] = ( *i ).facenormal[1]; - accum[2] = ( *i ).facenormal[2]; - counter = 1; - - - z = 0; - - for ( fc = 0; fc < faceref[index].count; fc++ ) - { - z++; - q = faceref[index].faces[fc]; - if ( q == i ) { - continue; //skip us. - - - } - // if ( (*q).indices[0]==index || (*q).indices[1]==index || (*q).indices[2]==index) - a[0] = &vertices[( *q ).indices[0] ].xyz; - a[1] = &vertices[( *q ).indices[1] ].xyz; - a[2] = &vertices[( *q ).indices[2] ].xyz; - - if ( VectorCompareExtn( *a[0],*xyz[j],0.01f ) > 0 || - VectorCompareExtn( *a[1],*xyz[j],0.01f ) > 0 || - VectorCompareExtn( *a[2],*xyz[j],0.01f ) > 0 - ) { - if ( ( *i ).smoothingGroup == 0 && ( *q ).smoothingGroup == 0 ) { - continue; - } - - if ( ( *i ).smoothingGroup & ( *q ).smoothingGroup ) { - accum[0] += ( *q ).facenormal[0]; - accum[1] += ( *q ).facenormal[1]; - accum[2] += ( *q ).facenormal[2]; - - counter++; - - } - } - } - _pico_normalize_vec( accum ); - - ( *i ).vertexnormal[j][0] = accum[0]; - ( *i ).vertexnormal[j][1] = accum[1]; - ( *i ).vertexnormal[j][2] = accum[2]; - normal[j] = &( *i ).vertexnormal[j]; - - st[j] = &texcoords[( *i ).indices[j + 3]].texcoord; - - if ( colors != NULL && ( *i ).indices[j + 6] >= 0 ) { - color[j] = &colors[( *i ).indices[j + 6]].color; - } - else - { - color[j] = &white; - } - - smooth[j] = 0; // (vertices[(*i).indices[j]].id * (1 << 16)) + (*i).smoothingGroup; /* don't merge vertices */ - - } - - /* submit the triangle to the model */ - PicoAddTriangleToModel( model, xyz, normal, 1, st, 1, color, subMtl->shader, smooth, submodel ); - } - - } - free( faceref ); -} - - -/* _ase_load: - * loads a 3dsmax ase model file. - */ -static picoModel_t *_ase_load( PM_PARAMS_LOAD ){ - picoModel_t *model; - picoParser_t *p; - char lastNodeName[ 1024 ]; - - aseVertex_t* vertices = NULL; - aseTexCoord_t* texcoords = NULL; - aseColor_t* colors = NULL; - aseFace_t* faces = NULL; - int numVertices = 0; - int numFaces = 0; - int numTextureVertices = 0; - int numTextureVertexFaces = 0; - int numColorVertices = 0; - int numColorVertexFaces = 0; - int vertexId = 0; - int currentVertexFace = 0; - int currentVertexIndex = 0; - int counter = 0; - int submodel = 0; - - aseMaterial_t* materials = NULL; - -#ifdef DEBUG_PM_ASE - clock_t start, finish; - double elapsed; - start = clock(); -#endif - - /* helper */ - #define _ase_error_return( m ) \ - { \ - _pico_printf( PICO_ERROR,"%s in ASE, line %d.",m,p->curLine ); \ - _pico_free_parser( p ); \ - PicoFreeModel( model ); \ - return NULL; \ - } - /* create a new pico parser */ - p = _pico_new_parser( (picoByte_t *)buffer,bufSize ); - if ( p == NULL ) { - return NULL; - } - - /* create a new pico model */ - model = PicoNewModel(); - if ( model == NULL ) { - _pico_free_parser( p ); - return NULL; - } - /* do model setup */ - PicoSetModelFrameNum( model, frameNum ); - PicoSetModelName( model, fileName ); - PicoSetModelFileName( model, fileName ); - - /* initialize some stuff */ - memset( lastNodeName,0,sizeof( lastNodeName ) ); - - /* parse ase model file */ - while ( 1 ) - { - /* get first token on line */ - if ( _pico_parse_first( p ) == NULL ) { - break; - } - - /* we just skip empty lines */ - if ( p->token == NULL || !strlen( p->token ) ) { - continue; - } - - /* we skip invalid ase statements */ - if ( p->token[0] != '*' && p->token[0] != '{' && p->token[0] != '}' ) { - _pico_parse_skip_rest( p ); - continue; - } - /* remember node name */ - if ( !_pico_stricmp( p->token,"*node_name" ) ) { - /* read node name */ - char *ptr = _pico_parse( p,0 ); - if ( ptr == NULL ) { - _ase_error_return( "Node name parse error" ); - } - - /* remember node name */ - strncpy( lastNodeName,ptr,sizeof( lastNodeName ) ); - } - /* model mesh (originally contained within geomobject) */ - else if ( !_pico_stricmp( p->token,"*mesh" ) ) { - /* finish existing surface */ - _ase_submit_triangles( model, materials, vertices, texcoords, colors, faces, numFaces,numVertices,submodel++ ); - _pico_free( faces ); - _pico_free( vertices ); - _pico_free( texcoords ); - _pico_free( colors ); - } - else if ( !_pico_stricmp( p->token,"*mesh_numvertex" ) ) { - if ( !_pico_parse_int( p, &numVertices ) ) { - _ase_error_return( "Missing MESH_NUMVERTEX value" ); - } - - vertices = _pico_calloc( numVertices, sizeof( aseVertex_t ) ); - currentVertexIndex = 0; - } - else if ( !_pico_stricmp( p->token,"*mesh_numfaces" ) ) { - if ( !_pico_parse_int( p, &numFaces ) ) { - _ase_error_return( "Missing MESH_NUMFACES value" ); - } - - faces = _pico_calloc( numFaces, sizeof( aseFace_t ) ); - - } - else if ( !_pico_stricmp( p->token,"*mesh_numtvertex" ) ) { - if ( !_pico_parse_int( p, &numTextureVertices ) ) { - _ase_error_return( "Missing MESH_NUMTVERTEX value" ); - } - - texcoords = _pico_calloc( numTextureVertices, sizeof( aseTexCoord_t ) ); - } - else if ( !_pico_stricmp( p->token,"*mesh_numtvfaces" ) ) { - if ( !_pico_parse_int( p, &numTextureVertexFaces ) ) { - _ase_error_return( "Missing MESH_NUMTVFACES value" ); - } - } - else if ( !_pico_stricmp( p->token,"*mesh_numcvertex" ) ) { - if ( !_pico_parse_int( p, &numColorVertices ) ) { - _ase_error_return( "Missing MESH_NUMCVERTEX value" ); - } - - colors = _pico_calloc( numColorVertices, sizeof( aseColor_t ) ); - memset( colors, 255, numColorVertices * sizeof( aseColor_t ) ); /* ydnar: force colors to white initially */ - } - else if ( !_pico_stricmp( p->token,"*mesh_numcvfaces" ) ) { - if ( !_pico_parse_int( p, &numColorVertexFaces ) ) { - _ase_error_return( "Missing MESH_NUMCVFACES value" ); - } - } - /* mesh material reference. this usually comes at the end of */ - /* geomobjects after the mesh blocks. we must assume that the */ - /* new mesh was already created so all we can do here is assign */ - /* the material reference id (shader index) now. */ - else if ( !_pico_stricmp( p->token,"*material_ref" ) ) { - int mtlId; - - /* get the material ref (0..n) */ - if ( !_pico_parse_int( p,&mtlId ) ) { - _ase_error_return( "Missing material reference ID" ); - } - - { - int i = 0; - /* fix up all of the aseFaceList in the surface to point to the parent material */ - /* we've already saved off their subMtl */ - for (; i < numFaces; ++i ) - { - faces[i].materialId = mtlId; - } - } - } - /* model mesh vertex */ - else if ( !_pico_stricmp( p->token,"*mesh_vertex" ) ) { - int index; - - if ( numVertices == 0 ) { - _ase_error_return( "Vertex parse error" ); - } - - /* get vertex data (orig: index +y -x +z) */ - if ( !_pico_parse_int( p,&index ) ) { - _ase_error_return( "Vertex parse error" ); - } - if ( !_pico_parse_vec( p,vertices[index].xyz ) ) { - _ase_error_return( "Vertex parse error" ); - } - - vertices[index].id = vertexId++; - } - else if ( !_pico_stricmp( p->token,"*mesh_facenormal" ) ) { - //Grab the faceindex for the next vertex normals. - if ( numVertices == 0 ) { - _ase_error_return( "Vertex parse error (facenormals)" ); - } - - if ( !_pico_parse_int( p,¤tVertexFace ) ) { - _ase_error_return( "Vertex parse error" ); - } - - if ( !_pico_parse_vec( p,faces[currentVertexFace].facenormal ) ) { - _ase_error_return( "Vertex parse error" ); - } - - } - /* model mesh vertex normal */ - else if ( !_pico_stricmp( p->token,"*mesh_vertexnormal" ) ) { - int index; - - if ( numVertices == 0 ) { - _ase_error_return( "Vertex parse error" ); - } - - /* get vertex data (orig: index +y -x +z) */ - if ( !_pico_parse_int( p,&index ) ) { - _ase_error_return( "Vertex parse error" ); - } - - //^^ Index is 'wrong' in .ase models. they reference the same vert index with multiple normals.. - // I've tried, this is a lost cause. Use the SG's - // - /* - - if (!_pico_parse_vec( p,vertices[counter].normal )) - _ase_error_return("Vertex parse error"); - vertices[counter].faceid=index; - counter++; - */ - } - /* model mesh face */ - else if ( !_pico_stricmp( p->token,"*mesh_normals" ) ) { - // counter=0; //part of the above vertex normals fix - } - - /* model mesh face */ - else if ( !_pico_stricmp( p->token,"*mesh_face" ) ) { - picoIndex_t indexes[3]; - int index; - - if ( numFaces == 0 ) { - _ase_error_return( "Face parse error" ); - } - - /* get face index */ - if ( !_pico_parse_int( p,&index ) ) { - _ase_error_return( "Face parse error" ); - } - - /* get 1st vertex index */ - _pico_parse( p,0 ); - if ( !_pico_parse_int( p,&indexes[0] ) ) { - _ase_error_return( "Face parse error" ); - } - - /* get 2nd vertex index */ - _pico_parse( p,0 ); - if ( !_pico_parse_int( p,&indexes[1] ) ) { - _ase_error_return( "Face parse error" ); - } - - /* get 3rd vertex index */ - _pico_parse( p,0 ); - if ( !_pico_parse_int( p,&indexes[2] ) ) { - _ase_error_return( "Face parse error" ); - } - - /* parse to the subMaterial ID */ - while ( 1 ) - { - if ( !_pico_parse( p,0 ) ) { /* EOL */ - break; - } - if ( !_pico_stricmp( p->token,"*MESH_SMOOTHING" ) ) { - int total = 0; - char* point; - char* start; - _pico_parse( p,0 ); - - point = p->token; - start = point; - faces[index].smoothingGroup = 0; - - //Super dodgy comma delimited string parse - while ( *point < 'A' ) - { - if ( *point <= 32 || *point == ',' ) { - total = atoi( start ); - if ( total != 0 ) { - faces[index].smoothingGroup += 1 << total; - } - start = point + 1; - } - - point++; - } - - - - - } - if ( !_pico_stricmp( p->token,"*MESH_MTLID" ) ) { - _pico_parse_int( p, &faces[index].subMaterialId ); - } - } - - faces[index].materialId = 0; - faces[index].indices[0] = indexes[2]; - faces[index].indices[1] = indexes[1]; - faces[index].indices[2] = indexes[0]; - } - /* model texture vertex */ - else if ( !_pico_stricmp( p->token,"*mesh_tvert" ) ) { - int index; - - if ( numVertices == 0 ) { - _ase_error_return( "Vertex parse error" ); - } - - /* get uv vertex index */ - if ( !_pico_parse_int( p,&index ) ) { - _ase_error_return( "UV vertex parse error" ); - } - - /* get uv vertex s */ - if ( !_pico_parse_float( p,&texcoords[index].texcoord[0] ) ) { - _ase_error_return( "UV vertex parse error" ); - } - - /* get uv vertex t */ - if ( !_pico_parse_float( p,&texcoords[index].texcoord[1] ) ) { - _ase_error_return( "UV vertex parse error" ); - } - - /* ydnar: invert t */ - texcoords[index].texcoord[ 1 ] = 1.0f - texcoords[index].texcoord[ 1 ]; - } - /* ydnar: model mesh texture face */ - else if ( !_pico_stricmp( p->token, "*mesh_tface" ) ) { - picoIndex_t indexes[3]; - int index; - - if ( numFaces == 0 ) { - _ase_error_return( "Texture face parse error" ); - } - - /* get face index */ - if ( !_pico_parse_int( p,&index ) ) { - _ase_error_return( "Texture face parse error" ); - } - - /* get 1st vertex index */ - if ( !_pico_parse_int( p,&indexes[0] ) ) { - _ase_error_return( "Texture face parse error" ); - } - - /* get 2nd vertex index */ - if ( !_pico_parse_int( p,&indexes[1] ) ) { - _ase_error_return( "Texture face parse error" ); - } - - /* get 3rd vertex index */ - if ( !_pico_parse_int( p,&indexes[2] ) ) { - _ase_error_return( "Texture face parse error" ); - } - - faces[index].indices[3] = indexes[2]; - faces[index].indices[4] = indexes[1]; - faces[index].indices[5] = indexes[0]; - } - /* model color vertex */ - else if ( !_pico_stricmp( p->token,"*mesh_vertcol" ) ) { - int index; - float colorInput; - - if ( numVertices == 0 ) { - _ase_error_return( "Color Vertex parse error" ); - } - - /* get color vertex index */ - if ( !_pico_parse_int( p,&index ) ) { - _ase_error_return( "Color vertex parse error" ); - } - - /* get R component */ - if ( !_pico_parse_float( p,&colorInput ) ) { - _ase_error_return( "Color vertex parse error" ); - } - colors[index].color[0] = (picoByte_t)( colorInput * 255 ); - - /* get G component */ - if ( !_pico_parse_float( p,&colorInput ) ) { - _ase_error_return( "Color vertex parse error" ); - } - colors[index].color[1] = (picoByte_t)( colorInput * 255 ); - - /* get B component */ - if ( !_pico_parse_float( p,&colorInput ) ) { - _ase_error_return( "Color vertex parse error" ); - } - colors[index].color[2] = (picoByte_t)( colorInput * 255 ); - - /* leave alpha alone since we don't get any data from the ASE format */ - colors[index].color[3] = 255; - - /* 27 hack, red as alpha */ - colors[index].color[3] = colors[index].color[0]; - colors[index].color[0] = 255; - colors[index].color[1] = 255; - colors[index].color[2] = 255; - - } - /* model color face */ - else if ( !_pico_stricmp( p->token,"*mesh_cface" ) ) { - picoIndex_t indexes[3]; - int index; - - if ( numFaces == 0 ) { - _ase_error_return( "Face parse error" ); - } - - /* get face index */ - if ( !_pico_parse_int( p,&index ) ) { - _ase_error_return( "Face parse error" ); - } - - /* get 1st cvertex index */ - // _pico_parse( p,0 ); - if ( !_pico_parse_int( p,&indexes[0] ) ) { - _ase_error_return( "Face parse error" ); - } - - /* get 2nd cvertex index */ - // _pico_parse( p,0 ); - if ( !_pico_parse_int( p,&indexes[1] ) ) { - _ase_error_return( "Face parse error" ); - } - - /* get 3rd cvertex index */ - // _pico_parse( p,0 ); - if ( !_pico_parse_int( p,&indexes[2] ) ) { - _ase_error_return( "Face parse error" ); - } - - faces[index].indices[6] = indexes[2]; - faces[index].indices[7] = indexes[1]; - faces[index].indices[8] = indexes[0]; - } - /* model material */ - else if ( !_pico_stricmp( p->token, "*material" ) ) { - aseSubMaterial_t* subMaterial = NULL; - picoShader_t *shader; - int level = 1, index; - char materialName[ 1024 ]; - float transValue = 0.0f, shineValue = 1.0f; - picoColor_t ambientColor, diffuseColor, specularColor; - char *mapname = NULL; - int subMtlId, subMaterialLevel = -1; - - - /* get material index */ - _pico_parse_int( p,&index ); - - /* check brace */ - if ( !_pico_parse_check( p,1,"{" ) ) { - _ase_error_return( "Material missing opening brace" ); - } - - /* parse material block */ - while ( 1 ) - { - /* get next token */ - if ( _pico_parse( p,1 ) == NULL ) { - break; - } - if ( !strlen( p->token ) ) { - continue; - } - - /* handle levels */ - if ( p->token[0] == '{' ) { - level++; - } - if ( p->token[0] == '}' ) { - level--; - } - if ( !level ) { - break; - } - - if ( level == subMaterialLevel ) { - /* set material name */ - _pico_first_token( materialName ); - PicoSetShaderName( shader, materialName ); - - /* set shader's transparency */ - PicoSetShaderTransparency( shader,transValue ); - - /* set shader's ambient color */ - PicoSetShaderAmbientColor( shader,ambientColor ); - - /* set diffuse alpha to transparency */ - diffuseColor[3] = (picoByte_t)( transValue * 255.0 ); - - /* set shader's diffuse color */ - PicoSetShaderDiffuseColor( shader,diffuseColor ); - - /* set shader's specular color */ - PicoSetShaderSpecularColor( shader,specularColor ); - - /* set shader's shininess */ - PicoSetShaderShininess( shader,shineValue ); - - /* set material map name */ - PicoSetShaderMapName( shader, mapname ); - - subMaterial = _ase_add_submaterial( &materials, index, subMtlId, shader ); - subMaterialLevel = -1; - } - - /* parse submaterial index */ - if ( !_pico_stricmp( p->token,"*submaterial" ) ) { - /* allocate new pico shader */ - _pico_parse_int( p, &subMtlId ); - - shader = PicoNewShader( model ); - if ( shader == NULL ) { - PicoFreeModel( model ); - return NULL; - } - subMaterialLevel = level; - } - /* parse material name */ - else if ( !_pico_stricmp( p->token,"*material_name" ) ) { - char* name = _pico_parse( p,0 ); - if ( name == NULL ) { - _ase_error_return( "Missing material name" ); - } - - strcpy( materialName, name ); - /* skip rest and continue with next token */ - _pico_parse_skip_rest( p ); - continue; - } - /* parse material transparency */ - else if ( !_pico_stricmp( p->token,"*material_transparency" ) ) { - /* get transparency value from ase */ - if ( !_pico_parse_float( p,&transValue ) ) { - _ase_error_return( "Material transparency parse error" ); - } - - /* skip rest and continue with next token */ - _pico_parse_skip_rest( p ); - continue; - } - /* parse material shininess */ - else if ( !_pico_stricmp( p->token,"*material_shine" ) ) { - /* remark: - * - not sure but instead of '*material_shine' i might - * need to use '*material_shinestrength' */ - - /* get shine value from ase */ - if ( !_pico_parse_float( p,&shineValue ) ) { - _ase_error_return( "Material shine parse error" ); - } - - /* scale ase shine range 0..1 to pico range 0..127 */ - shineValue *= 128.0; - - /* skip rest and continue with next token */ - _pico_parse_skip_rest( p ); - continue; - } - /* parse ambient material color */ - else if ( !_pico_stricmp( p->token,"*material_ambient" ) ) { - picoVec3_t vec; - /* get r,g,b float values from ase */ - if ( !_pico_parse_vec( p,vec ) ) { - _ase_error_return( "Material color parse error" ); - } - - /* setup 0..255 range color values */ - ambientColor[ 0 ] = (int)( vec[ 0 ] * 255.0 ); - ambientColor[ 1 ] = (int)( vec[ 1 ] * 255.0 ); - ambientColor[ 2 ] = (int)( vec[ 2 ] * 255.0 ); - ambientColor[ 3 ] = (int)( 255 ); - - /* skip rest and continue with next token */ - _pico_parse_skip_rest( p ); - continue; - } - /* parse diffuse material color */ - else if ( !_pico_stricmp( p->token,"*material_diffuse" ) ) { - picoVec3_t vec; - - /* get r,g,b float values from ase */ - if ( !_pico_parse_vec( p,vec ) ) { - _ase_error_return( "Material color parse error" ); - } - - /* setup 0..255 range color */ - diffuseColor[ 0 ] = (int)( vec[ 0 ] * 255.0 ); - diffuseColor[ 1 ] = (int)( vec[ 1 ] * 255.0 ); - diffuseColor[ 2 ] = (int)( vec[ 2 ] * 255.0 ); - diffuseColor[ 3 ] = (int)( 255 ); - - /* skip rest and continue with next token */ - _pico_parse_skip_rest( p ); - continue; - } - /* parse specular material color */ - else if ( !_pico_stricmp( p->token,"*material_specular" ) ) { - picoVec3_t vec; - - /* get r,g,b float values from ase */ - if ( !_pico_parse_vec( p,vec ) ) { - _ase_error_return( "Material color parse error" ); - } - - /* setup 0..255 range color */ - specularColor[ 0 ] = (int)( vec[ 0 ] * 255 ); - specularColor[ 1 ] = (int)( vec[ 1 ] * 255 ); - specularColor[ 2 ] = (int)( vec[ 2 ] * 255 ); - specularColor[ 3 ] = (int)( 255 ); - - /* skip rest and continue with next token */ - _pico_parse_skip_rest( p ); - continue; - } - /* material diffuse map */ - else if ( !_pico_stricmp( p->token,"*map_diffuse" ) ) { - int sublevel = 0; - - /* parse material block */ - while ( 1 ) - { - /* get next token */ - if ( _pico_parse( p,1 ) == NULL ) { - break; - } - if ( !strlen( p->token ) ) { - continue; - } - - /* handle levels */ - if ( p->token[0] == '{' ) { - sublevel++; - } - if ( p->token[0] == '}' ) { - sublevel--; - } - if ( !sublevel ) { - break; - } - - /* parse diffuse map bitmap */ - if ( !_pico_stricmp( p->token,"*bitmap" ) ) { - char* name = _pico_parse( p,0 ); - if ( name == NULL ) { - _ase_error_return( "Missing material map bitmap name" ); - } - mapname = _pico_alloc( strlen( name ) + 1 ); - strcpy( mapname, name ); - /* skip rest and continue with next token */ - _pico_parse_skip_rest( p ); - continue; - } - } - } - /* end map_diffuse block */ - } - /* end material block */ - - if ( subMaterial == NULL ) { - /* allocate new pico shader */ - shader = PicoNewShader( model ); - if ( shader == NULL ) { - PicoFreeModel( model ); - return NULL; - } - - /* set material name */ - PicoSetShaderName( shader,materialName ); - - /* set shader's transparency */ - PicoSetShaderTransparency( shader,transValue ); - - /* set shader's ambient color */ - PicoSetShaderAmbientColor( shader,ambientColor ); - - /* set diffuse alpha to transparency */ - diffuseColor[3] = (picoByte_t)( transValue * 255.0 ); - - /* set shader's diffuse color */ - PicoSetShaderDiffuseColor( shader,diffuseColor ); - - /* set shader's specular color */ - PicoSetShaderSpecularColor( shader,specularColor ); - - /* set shader's shininess */ - PicoSetShaderShininess( shader,shineValue ); - - /* set material map name */ - PicoSetShaderMapName( shader, mapname ); - - /* extract shadername from bitmap path */ - if ( mapname != NULL ) { - char* p = mapname; - - /* convert to shader-name format */ - { - /* unix-style path separators */ - char* s = mapname; - for (; *s != '\0'; ++s ) - { - if ( *s == '\\' ) { - *s = '/'; - } - } - } - { - /* remove extension */ - char* last_period = strrchr( p, '.' ); - if ( last_period != NULL ) { - *last_period = '\0'; - } - } - - /* find game root */ - for (; *p != '\0'; ++p ) - { - if ( _pico_strnicmp( p, "quake", 5 ) == 0 || _pico_strnicmp( p, "doom", 4 ) == 0 ) { - break; - } - } - /* root-relative */ - for (; *p != '\0'; ++p ) - { - if ( *p == '/' ) { - ++p; - break; - } - } - /* game-relative */ - for (; *p != '\0'; ++p ) - { - if ( *p == '/' ) { - ++p; - break; - } - } - - if ( *p != '\0' ) { - /* set material name */ - PicoSetShaderName( shader,p ); - } - } - - /* this is just a material with 1 submaterial */ - subMaterial = _ase_add_submaterial( &materials, index, 0, shader ); - } - - /* ydnar: free mapname */ - if ( mapname != NULL ) { - _pico_free( mapname ); - } - } // !_pico_stricmp ( "*material" ) - - /* skip unparsed rest of line and continue */ - _pico_parse_skip_rest( p ); - } - - /* ydnar: finish existing surface */ - _ase_submit_triangles( model, materials, vertices, texcoords, colors, faces, numFaces,numVertices,submodel++ ); - _pico_free( faces ); - _pico_free( vertices ); - _pico_free( texcoords ); - _pico_free( colors ); - -#ifdef DEBUG_PM_ASE - _ase_print_materials( materials ); - finish = clock(); - elapsed = (double)( finish - start ) / CLOCKS_PER_SEC; - _pico_printf( PICO_NORMAL, "Loaded model in in %-.2f second(s)\n", elapsed ); -#endif //DEBUG_PM_ASE - - _ase_free_materials( &materials ); - - _pico_free_parser( p ); - - /* return allocated pico model */ - return model; -} - -/* pico file format module definition */ -const picoModule_t picoModuleASE = -{ - "1.0", /* module version string */ - "Autodesk 3DSMAX ASCII", /* module display name */ - "Jared Hefty, seaw0lf", /* author's name */ - "2003 Jared Hefty, 2002 seaw0lf", /* module copyright */ - { - "ase",NULL,NULL,NULL /* default extensions to use */ - }, - _ase_canload, /* validation routine */ - _ase_load, /* load routine */ - NULL, /* save validation routine */ - NULL /* save routine */ -}; diff --git a/tools/urt/libs/picomodel/pm_fm.c b/tools/urt/libs/picomodel/pm_fm.c deleted file mode 100644 index 8313dca..0000000 --- a/tools/urt/libs/picomodel/pm_fm.c +++ /dev/null @@ -1,639 +0,0 @@ -/* ----------------------------------------------------------------------------- - - PicoModel Library - - Copyright (c) 2002, Randy Reddig & seaw0lf - All rights reserved. - - Redistribution and use in source and binary forms, with or without modification, - are permitted provided that the following conditions are met: - - Redistributions of source code must retain the above copyright notice, this list - of conditions and the following disclaimer. - - Redistributions in binary form must reproduce the above copyright notice, this - list of conditions and the following disclaimer in the documentation and/or - other materials provided with the distribution. - - Neither the names of the copyright holders nor the names of its contributors may - be used to endorse or promote products derived from this software without - specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR - ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - ----------------------------------------------------------------------------- */ - -/* - Nurail: Used pm_md3.c (Randy Reddig) as a template. - */ - -/* marker */ -#define PM_FM_C - -/* dependencies */ -#include "pm_fm.h" - -//#define FM_VERBOSE_DBG 0 -#undef FM_VERBOSE_DBG -#undef FM_DBG - -typedef struct index_LUT_s -{ - short Vert; - short ST; - struct index_LUT_s *next; - -} index_LUT_t; - -typedef struct index_DUP_LUT_s -{ - short ST; - short OldVert; - -} index_DUP_LUT_t; - - -// _fm_canload() -static int _fm_canload( PM_PARAMS_CANLOAD ){ - fm_t fm; - unsigned char *bb; - int fm_file_pos; - - bb = (unsigned char *) buffer; - - // Header - fm.fm_header_hdr = (fm_chunk_header_t *) bb; - fm_file_pos = sizeof( fm_chunk_header_t ) + fm.fm_header_hdr->size; -#ifdef FM_VERBOSE_DBG - _pico_printf( PICO_VERBOSE, "IDENT: %s\n", (unsigned char *) fm.fm_header_hdr->ident ); -#endif - if ( ( strcmp( fm.fm_header_hdr->ident, FM_HEADERCHUNKNAME ) ) ) { -#ifdef FM_DBG - _pico_printf( PICO_WARNING, "FM Header Ident incorrect\n" ); -#endif - return PICO_PMV_ERROR_IDENT; - } - - // check fm - if ( _pico_little_long( fm.fm_header_hdr->version ) != FM_HEADERCHUNKVER ) { -#ifdef FM_DBG - _pico_printf( PICO_WARNING, "FM Header Version incorrect\n" ); -#endif - return PICO_PMV_ERROR_VERSION; - } - - // Skin - fm.fm_skin_hdr = (fm_chunk_header_t *) ( bb + fm_file_pos ); - fm_file_pos += sizeof( fm_chunk_header_t ) + fm.fm_skin_hdr->size; -#ifdef FM_VERBOSE_DBG - _pico_printf( PICO_VERBOSE, "SKIN: %s\n", (unsigned char *) fm.fm_skin_hdr->ident ); -#endif - if ( ( strcmp( fm.fm_skin_hdr->ident, FM_SKINCHUNKNAME ) ) ) { -#ifdef FM_DBG - _pico_printf( PICO_WARNING, "FM Skin Ident incorrect\n" ); -#endif - return PICO_PMV_ERROR_IDENT; - } - - // check fm - if ( _pico_little_long( fm.fm_skin_hdr->version ) != FM_SKINCHUNKVER ) { -#ifdef FM_DBG - _pico_printf( PICO_WARNING, "FM Skin Version incorrect\n" ); -#endif - return PICO_PMV_ERROR_VERSION; - } - - // st - fm.fm_st_hdr = (fm_chunk_header_t *) ( bb + fm_file_pos ); - fm_file_pos += sizeof( fm_chunk_header_t ) + fm.fm_st_hdr->size; -#ifdef FM_VERBOSE_DBG - _pico_printf( PICO_VERBOSE, "ST: %s\n", (unsigned char *) fm.fm_st_hdr->ident ); -#endif - if ( ( strcmp( fm.fm_st_hdr->ident, FM_STCOORDCHUNKNAME ) ) ) { -#ifdef FM_DBG - _pico_printf( PICO_WARNING, "FM ST Ident incorrect\n" ); -#endif - return PICO_PMV_ERROR_IDENT; - } - - // check fm - if ( _pico_little_long( fm.fm_st_hdr->version ) != FM_STCOORDCHUNKVER ) { -#ifdef FM_DBG - _pico_printf( PICO_WARNING, "FM ST Version incorrect\n" ); -#endif - return PICO_PMV_ERROR_VERSION; - } - - // tri - fm.fm_tri_hdr = (fm_chunk_header_t *) ( bb + fm_file_pos ); - fm_file_pos += sizeof( fm_chunk_header_t ) + fm.fm_tri_hdr->size; -#ifdef FM_VERBOSE_DBG - _pico_printf( PICO_VERBOSE, "TRI: %s\n", (unsigned char *) fm.fm_tri_hdr->ident ); -#endif - if ( ( strcmp( fm.fm_tri_hdr->ident, FM_TRISCHUNKNAME ) ) ) { -#ifdef FM_DBG - _pico_printf( PICO_WARNING, "FM Tri Ident incorrect\n" ); -#endif - return PICO_PMV_ERROR_IDENT; - } - - // check fm - if ( _pico_little_long( fm.fm_tri_hdr->version ) != FM_TRISCHUNKVER ) { -#ifdef FM_DBG - _pico_printf( PICO_WARNING, "FM Tri Version incorrect\n" ); -#endif - return PICO_PMV_ERROR_VERSION; - } - - // frame - fm.fm_frame_hdr = (fm_chunk_header_t *) ( bb + fm_file_pos ); - fm_file_pos += sizeof( fm_chunk_header_t ); -#ifdef FM_VERBOSE_DBG - _pico_printf( PICO_VERBOSE, "FRAME: %s\n", (unsigned char *) fm.fm_frame_hdr->ident ); -#endif - if ( ( strcmp( fm.fm_frame_hdr->ident, FM_FRAMESCHUNKNAME ) ) ) { -#ifdef FM_DBG - _pico_printf( PICO_WARNING, "FM Frame Ident incorrect\n" ); -#endif - return PICO_PMV_ERROR_IDENT; - } - - // check fm - if ( _pico_little_long( fm.fm_frame_hdr->version ) != FM_FRAMESCHUNKVER ) { -#ifdef FM_DBG - _pico_printf( PICO_WARNING, "FM Frame Version incorrect\n" ); -#endif - return PICO_PMV_ERROR_VERSION; - } - - // file seems to be a valid fm - return PICO_PMV_OK; -} - - - -// _fm_load() loads a Heretic 2 model file. -static picoModel_t *_fm_load( PM_PARAMS_LOAD ){ - int i, j, dups, dup_index; - int fm_file_pos; - short tot_numVerts; - index_LUT_t *p_index_LUT, *p_index_LUT2, *p_index_LUT3; - index_DUP_LUT_t *p_index_LUT_DUPS; - - fm_vert_normal_t *vert; - - char skinname[FM_SKINPATHSIZE]; - fm_t fm; - fm_header_t *fm_head; - fm_st_t *texCoord; - fm_xyz_st_t *tri_verts; - fm_xyz_st_t *triangle; - fm_frame_t *frame; - - picoByte_t *bb; - picoModel_t *picoModel; - picoSurface_t *picoSurface; - picoShader_t *picoShader; - picoVec3_t xyz, normal; - picoVec2_t st; - picoColor_t color; - - - bb = (picoByte_t*) buffer; - - // Header Header - fm.fm_header_hdr = (fm_chunk_header_t *) bb; - fm_file_pos = sizeof( fm_chunk_header_t ) + fm.fm_header_hdr->size; - if ( ( strcmp( fm.fm_header_hdr->ident, FM_HEADERCHUNKNAME ) ) ) { - _pico_printf( PICO_WARNING, "FM Header Ident incorrect\n" ); - return NULL; - } - - if ( _pico_little_long( fm.fm_header_hdr->version ) != FM_HEADERCHUNKVER ) { - _pico_printf( PICO_WARNING, "FM Header Version incorrect\n" ); - return NULL; - } - - // Skin Header - fm.fm_skin_hdr = (fm_chunk_header_t *) ( bb + fm_file_pos ); - fm_file_pos += sizeof( fm_chunk_header_t ) + fm.fm_skin_hdr->size; - if ( ( strcmp( fm.fm_skin_hdr->ident, FM_SKINCHUNKNAME ) ) ) { - _pico_printf( PICO_WARNING, "FM Skin Ident incorrect\n" ); - return NULL; - } - - if ( _pico_little_long( fm.fm_skin_hdr->version ) != FM_SKINCHUNKVER ) { - _pico_printf( PICO_WARNING, "FM Skin Version incorrect\n" ); - return NULL; - } - - // ST Header - fm.fm_st_hdr = (fm_chunk_header_t *) ( bb + fm_file_pos ); - fm_file_pos += sizeof( fm_chunk_header_t ) + fm.fm_st_hdr->size; - if ( ( strcmp( fm.fm_st_hdr->ident, FM_STCOORDCHUNKNAME ) ) ) { - _pico_printf( PICO_WARNING, "FM ST Ident incorrect\n" ); - return NULL; - } - - if ( _pico_little_long( fm.fm_st_hdr->version ) != FM_STCOORDCHUNKVER ) { - _pico_printf( PICO_WARNING, "FM ST Version incorrect\n" ); - return NULL; - } - - // Tris Header - fm.fm_tri_hdr = (fm_chunk_header_t *) ( bb + fm_file_pos ); - fm_file_pos += sizeof( fm_chunk_header_t ) + fm.fm_tri_hdr->size; - if ( ( strcmp( fm.fm_tri_hdr->ident, FM_TRISCHUNKNAME ) ) ) { - _pico_printf( PICO_WARNING, "FM Tri Ident incorrect\n" ); - return NULL; - } - - if ( _pico_little_long( fm.fm_tri_hdr->version ) != FM_TRISCHUNKVER ) { - _pico_printf( PICO_WARNING, "FM Tri Version incorrect\n" ); - return NULL; - } - - // Frame Header - fm.fm_frame_hdr = (fm_chunk_header_t *) ( bb + fm_file_pos ); - fm_file_pos += sizeof( fm_chunk_header_t ); - if ( ( strcmp( fm.fm_frame_hdr->ident, FM_FRAMESCHUNKNAME ) ) ) { - _pico_printf( PICO_WARNING, "FM Frame Ident incorrect\n" ); - return NULL; - } - - if ( _pico_little_long( fm.fm_frame_hdr->version ) != FM_FRAMESCHUNKVER ) { - _pico_printf( PICO_WARNING, "FM Frame Version incorrect\n" ); - return NULL; - } - - // Header - fm_file_pos = sizeof( fm_chunk_header_t ); - fm_head = fm.fm_header = (fm_header_t *) ( bb + fm_file_pos ); - fm_file_pos += fm.fm_header_hdr->size; - - // Skin - fm_file_pos += sizeof( fm_chunk_header_t ); - fm.fm_skin = (fm_skinpath_t *) ( bb + fm_file_pos ); - fm_file_pos += fm.fm_skin_hdr->size; - - // ST - fm_file_pos += sizeof( fm_chunk_header_t ); - texCoord = fm.fm_st = (fm_st_t *) ( bb + fm_file_pos ); - fm_file_pos += fm.fm_st_hdr->size; - - // Tri - fm_file_pos += sizeof( fm_chunk_header_t ); - tri_verts = fm.fm_tri = (fm_xyz_st_t *) ( bb + fm_file_pos ); - fm_file_pos += fm.fm_tri_hdr->size; - - // Frame - fm_file_pos += sizeof( fm_chunk_header_t ); - frame = fm.fm_frame = (fm_frame_t *) ( bb + fm_file_pos ); - - // do frame check - if ( fm_head->numFrames < 1 ) { - _pico_printf( PICO_ERROR, "%s has 0 frames!", fileName ); - return NULL; - } - - if ( frameNum < 0 || frameNum >= fm_head->numFrames ) { - _pico_printf( PICO_ERROR, "Invalid or out-of-range FM frame specified" ); - return NULL; - } - - // swap fm - fm_head->skinWidth = _pico_little_long( fm_head->skinWidth ); - fm_head->skinHeight = _pico_little_long( fm_head->skinHeight ); - fm_head->frameSize = _pico_little_long( fm_head->frameSize ); - - fm_head->numSkins = _pico_little_long( fm_head->numSkins ); - fm_head->numXYZ = _pico_little_long( fm_head->numXYZ ); - fm_head->numST = _pico_little_long( fm_head->numST ); - fm_head->numTris = _pico_little_long( fm_head->numTris ); - fm_head->numGLCmds = _pico_little_long( fm_head->numGLCmds ); - fm_head->numFrames = _pico_little_long( fm_head->numFrames ); - - // swap frame scale and translation - for ( i = 0; i < 3; i++ ) - { - frame->header.scale[ i ] = _pico_little_float( frame->header.scale[ i ] ); - frame->header.translate[ i ] = _pico_little_float( frame->header.translate[ i ] ); - } - - // swap triangles - triangle = tri_verts; - for ( i = 0; i < fm_head->numTris; i++, triangle++ ) - { - for ( j = 0; j < 3; j++ ) - { - triangle->index_xyz[ j ] = _pico_little_short( triangle->index_xyz[ j ] ); - triangle->index_st[ j ] = _pico_little_short( triangle->index_st[ j ] ); - } - } - - // swap st coords - for ( i = 0; i < fm_head->numST; i++ ) - { - texCoord->s = _pico_little_short( texCoord[i].s ); - texCoord->t = _pico_little_short( texCoord[i].t ); - } - // set Skin Name - strncpy( skinname, (unsigned char *) fm.fm_skin, FM_SKINPATHSIZE ); - -#ifdef FM_VERBOSE_DBG - // Print out md2 values - _pico_printf( PICO_VERBOSE,"numSkins->%d numXYZ->%d numST->%d numTris->%d numFrames->%d\nSkin Name \"%s\"\n", fm_head->numSkins, fm_head->numXYZ, fm_head->numST, fm_head->numTris, fm_head->numFrames, &skinname ); -#endif - - // detox Skin name - _pico_setfext( skinname, "" ); - _pico_unixify( skinname ); - - /* create new pico model */ - picoModel = PicoNewModel(); - if ( picoModel == NULL ) { - _pico_printf( PICO_ERROR, "Unable to allocate a new model" ); - return NULL; - } - - /* do model setup */ - PicoSetModelFrameNum( picoModel, frameNum ); - PicoSetModelNumFrames( picoModel, fm_head->numFrames ); /* sea */ - PicoSetModelName( picoModel, fileName ); - PicoSetModelFileName( picoModel, fileName ); - - // allocate new pico surface - picoSurface = PicoNewSurface( picoModel ); - if ( picoSurface == NULL ) { - _pico_printf( PICO_ERROR, "Unable to allocate a new model surface" ); - PicoFreeModel( picoModel ); - return NULL; - } - - - PicoSetSurfaceType( picoSurface, PICO_TRIANGLES ); - PicoSetSurfaceName( picoSurface, frame->header.name ); - picoShader = PicoNewShader( picoModel ); - if ( picoShader == NULL ) { - _pico_printf( PICO_ERROR, "Unable to allocate a new model shader" ); - PicoFreeModel( picoModel ); - return NULL; - } - - PicoSetShaderName( picoShader, skinname ); - - // associate current surface with newly created shader - PicoSetSurfaceShader( picoSurface, picoShader ); - - // Init LUT for Verts - p_index_LUT = (index_LUT_t *)_pico_alloc( sizeof( index_LUT_t ) * fm_head->numXYZ ); - for ( i = 0; i < fm_head->numXYZ; i++ ) - { - p_index_LUT[i].Vert = -1; - p_index_LUT[i].ST = -1; - p_index_LUT[i].next = NULL; - } - - // Fill in Look Up Table, and allocate/fill Linked List from vert array as needed for dup STs per Vert. - tot_numVerts = fm_head->numXYZ; - dups = 0; - triangle = tri_verts; - - for ( i = 0; i < fm_head->numTris; i++ ) - { - for ( j = 0; j < 3; j++ ) - { - if ( p_index_LUT[triangle->index_xyz[j]].ST == -1 ) { // No Main Entry - p_index_LUT[triangle->index_xyz[j]].ST = triangle->index_st[j]; - } - - else if ( triangle->index_st[j] == p_index_LUT[triangle->index_xyz[j]].ST ) { // Equal to Main Entry -#ifdef FM_VERBOSE_DBG - _pico_printf( PICO_NORMAL, "-> Tri #%d, Vert %d:\t XYZ:%d ST:%d\n", i, j, triangle->index_xyz[j], triangle->index_st[j] ); -#endif - continue; - } - else if ( ( p_index_LUT[triangle->index_xyz[j]].next == NULL ) ) { // Not equal to Main entry, and no LL entry - // Add first entry of LL from Main - p_index_LUT2 = (index_LUT_t *)_pico_alloc( sizeof( index_LUT_t ) ); - if ( p_index_LUT2 == NULL ) { - _pico_printf( PICO_NORMAL, " Couldn't allocate memory!\n" ); - } - p_index_LUT[triangle->index_xyz[j]].next = (index_LUT_t *)p_index_LUT2; - p_index_LUT2->Vert = dups; - p_index_LUT2->ST = triangle->index_st[j]; - p_index_LUT2->next = NULL; -#ifdef FM_VERBOSE_DBG - _pico_printf( PICO_NORMAL, " ADDING first LL XYZ:%d DUP:%d ST:%d\n", triangle->index_xyz[j], dups, triangle->index_st[j] ); -#endif - triangle->index_xyz[j] = dups + fm_head->numXYZ; // Make change in Tri hunk - dups++; - } - else // Try to find in LL from Main Entry - { - p_index_LUT3 = p_index_LUT2 = p_index_LUT[triangle->index_xyz[j]].next; - while ( ( p_index_LUT2 != NULL ) && ( triangle->index_xyz[j] != p_index_LUT2->Vert ) ) // Walk down LL - { - p_index_LUT3 = p_index_LUT2; - p_index_LUT2 = p_index_LUT2->next; - } - p_index_LUT2 = p_index_LUT3; - - if ( triangle->index_st[j] == p_index_LUT2->ST ) { // Found it - triangle->index_xyz[j] = p_index_LUT2->Vert + fm_head->numXYZ; // Make change in Tri hunk -#ifdef FM_VERBOSE_DBG - _pico_printf( PICO_NORMAL, "--> Tri #%d, Vert %d:\t XYZ:%d ST:%d\n", i, j, triangle->index_xyz[j], triangle->index_st[j] ); -#endif - continue; - } - - if ( p_index_LUT2->next == NULL ) { // Didn't find it. Add entry to LL. - // Add the Entry - p_index_LUT3 = (index_LUT_t *)_pico_alloc( sizeof( index_LUT_t ) ); - if ( p_index_LUT3 == NULL ) { - _pico_printf( PICO_NORMAL, " Couldn't allocate memory!\n" ); - } - p_index_LUT2->next = (index_LUT_t *)p_index_LUT3; - p_index_LUT3->Vert = dups; - p_index_LUT3->ST = triangle->index_st[j]; - p_index_LUT3->next = NULL; -#ifdef FM_VERBOSE_DBG - _pico_printf( PICO_NORMAL, " ADDING additional LL XYZ:%d DUP:%d NewXYZ:%d ST:%d\n", triangle->index_xyz[j], dups, dups + ( fm_head->numXYZ ), triangle->index_st[j] ); -#endif - triangle->index_xyz[j] = dups + fm_head->numXYZ; // Make change in Tri hunk - dups++; - } - } -#ifdef FM_VERBOSE_DBG - _pico_printf( PICO_NORMAL, "---> Tri #%d, Vert %d:\t XYZ:%d ST:%d\n", i, j, triangle->index_xyz[j], triangle->index_st[j] ); -#endif - } - triangle++; - } - - // malloc and build array for Dup STs - p_index_LUT_DUPS = (index_DUP_LUT_t *)_pico_alloc( sizeof( index_DUP_LUT_t ) * dups ); - if ( p_index_LUT_DUPS == NULL ) { - _pico_printf( PICO_NORMAL, " Couldn't allocate memory!\n" ); - } - - dup_index = 0; - for ( i = 0; i < fm_head->numXYZ; i++ ) - { - p_index_LUT2 = p_index_LUT[i].next; - while ( p_index_LUT2 != NULL ) - { - p_index_LUT_DUPS[p_index_LUT2->Vert].OldVert = i; - p_index_LUT_DUPS[p_index_LUT2->Vert].ST = p_index_LUT2->ST; - dup_index++; - p_index_LUT2 = p_index_LUT2->next; - } - } -#ifdef FM_VERBOSE_DBG - _pico_printf( PICO_NORMAL, " Dups = %d\n", dups ); - _pico_printf( PICO_NORMAL, " Dup Index = %d\n", dup_index ); -#endif - for ( i = 0; i < fm_head->numXYZ; i++ ) - { -#ifdef FM_VERBOSE_DBG - _pico_printf( PICO_NORMAL, "Vert: %4d\t%4d",i, p_index_LUT[i].ST ); -#endif - if ( p_index_LUT[i].next != NULL ) { - - p_index_LUT2 = p_index_LUT[i].next; - do { -#ifdef FM_VERBOSE_DBG - _pico_printf( PICO_NORMAL, " %4d %4d", p_index_LUT2->Vert, p_index_LUT2->ST ); -#endif - p_index_LUT2 = p_index_LUT2->next; - } while ( p_index_LUT2 != NULL ); - - } -#ifdef FM_VERBOSE_DBG - _pico_printf( PICO_NORMAL, "\n" ); -#endif - } - - -#ifdef FM_VERBOSE_DBG - for ( i = 0; i < dup_index; i++ ) - _pico_printf( PICO_NORMAL, " Dup Index #%d OldVert: %d ST: %d\n", i, p_index_LUT_DUPS[i].OldVert, p_index_LUT_DUPS[i].ST ); - - triangle = tri_verts; - for ( i = 0; i < fm_head->numTris; i++ ) - { - for ( j = 0; j < 3; j++ ) - _pico_printf( PICO_NORMAL, "Tri #%d, Vert %d:\t XYZ:%d ST:%d\n", i, j, triangle->index_xyz[j], triangle->index_st[j] ); - _pico_printf( PICO_NORMAL, "\n" ); - triangle++; - } -#endif - // Build Picomodel - triangle = tri_verts; - for ( j = 0; j < fm_head->numTris; j++, triangle++ ) - { - PicoSetSurfaceIndex( picoSurface, j * 3, triangle->index_xyz[0] ); - PicoSetSurfaceIndex( picoSurface, j * 3 + 1, triangle->index_xyz[1] ); - PicoSetSurfaceIndex( picoSurface, j * 3 + 2, triangle->index_xyz[2] ); - } - - vert = (fm_vert_normal_t*) ( (picoByte_t*) ( frame->verts ) ); - for ( i = 0; i < fm_head->numXYZ; i++, vert++ ) - { - /* set vertex origin */ - xyz[ 0 ] = vert->v[0] * frame->header.scale[0] + frame->header.translate[0]; - xyz[ 1 ] = vert->v[1] * frame->header.scale[1] + frame->header.translate[1]; - xyz[ 2 ] = vert->v[2] * frame->header.scale[2] + frame->header.translate[2]; - PicoSetSurfaceXYZ( picoSurface, i, xyz ); - - /* set normal */ - normal[ 0 ] = fm_normals[vert->lightnormalindex][0]; - normal[ 1 ] = fm_normals[vert->lightnormalindex][1]; - normal[ 2 ] = fm_normals[vert->lightnormalindex][2]; - PicoSetSurfaceNormal( picoSurface, i, normal ); - - /* set st coords */ - st[ 0 ] = ( ( texCoord[p_index_LUT[i].ST].s ) / ( (float)fm_head->skinWidth ) ); - st[ 1 ] = ( texCoord[p_index_LUT[i].ST].t / ( (float)fm_head->skinHeight ) ); - PicoSetSurfaceST( picoSurface, 0, i, st ); - } - - if ( dups ) { - for ( i = 0; i < dups; i++ ) - { - j = p_index_LUT_DUPS[i].OldVert; - /* set vertex origin */ - xyz[ 0 ] = frame->verts[j].v[0] * frame->header.scale[0] + frame->header.translate[0]; - xyz[ 1 ] = frame->verts[j].v[1] * frame->header.scale[1] + frame->header.translate[1]; - xyz[ 2 ] = frame->verts[j].v[2] * frame->header.scale[2] + frame->header.translate[2]; - PicoSetSurfaceXYZ( picoSurface, i + fm_head->numXYZ, xyz ); - - /* set normal */ - normal[ 0 ] = fm_normals[frame->verts[j].lightnormalindex][0]; - normal[ 1 ] = fm_normals[frame->verts[j].lightnormalindex][1]; - normal[ 2 ] = fm_normals[frame->verts[j].lightnormalindex][2]; - PicoSetSurfaceNormal( picoSurface, i + fm_head->numXYZ, normal ); - - /* set st coords */ - st[ 0 ] = ( ( texCoord[p_index_LUT_DUPS[i].ST].s ) / ( (float)fm_head->skinWidth ) ); - st[ 1 ] = ( texCoord[p_index_LUT_DUPS[i].ST].t / ( (float)fm_head->skinHeight ) ); - PicoSetSurfaceST( picoSurface, 0, i + fm_head->numXYZ, st ); - } - } - - /* set color */ - PicoSetSurfaceColor( picoSurface, 0, 0, color ); - - // Free up malloc'ed LL entries - for ( i = 0; i < fm_head->numXYZ; i++ ) - { - if ( p_index_LUT[i].next != NULL ) { - p_index_LUT2 = p_index_LUT[i].next; - do { - p_index_LUT3 = p_index_LUT2->next; - _pico_free( p_index_LUT2 ); - p_index_LUT2 = p_index_LUT3; - dups--; - } while ( p_index_LUT2 != NULL ); - } - } - - if ( dups ) { - _pico_printf( PICO_WARNING, " Not all LL mallocs freed\n" ); - } - - // Free malloc'ed LUTs - _pico_free( p_index_LUT ); - _pico_free( p_index_LUT_DUPS ); - - /* return the new pico model */ - return picoModel; - -} - - - -/* pico file format module definition */ -const picoModule_t picoModuleFM = -{ - "0.85", /* module version string */ - "Heretic 2 FM", /* module display name */ - "Nurail", /* author's name */ - "2003 Nurail", /* module copyright */ - { - "fm", NULL, NULL, NULL /* default extensions to use */ - }, - _fm_canload, /* validation routine */ - _fm_load, /* load routine */ - NULL, /* save validation routine */ - NULL /* save routine */ -}; diff --git a/tools/urt/libs/picomodel/pm_fm.h b/tools/urt/libs/picomodel/pm_fm.h deleted file mode 100644 index 6fa317c..0000000 --- a/tools/urt/libs/picomodel/pm_fm.h +++ /dev/null @@ -1,367 +0,0 @@ -/* ----------------------------------------------------------------------------- - - PicoModel Library - - Copyright (c) 2002, Randy Reddig & seaw0lf - All rights reserved. - - Redistribution and use in source and binary forms, with or without modification, - are permitted provided that the following conditions are met: - - Redistributions of source code must retain the above copyright notice, this list - of conditions and the following disclaimer. - - Redistributions in binary form must reproduce the above copyright notice, this - list of conditions and the following disclaimer in the documentation and/or - other materials provided with the distribution. - - Neither the names of the copyright holders nor the names of its contributors may - be used to endorse or promote products derived from this software without - specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR - ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - ----------------------------------------------------------------------------- */ - -// This header file is based from the following: - -/* - FlexModel.H - Header file for FlexModel file structure - - By Chris Burke - serotonin@earthlink.net - */ - -#ifndef __PM_FM_H__ -#define __PM_FM_H__ - -#include "picointernal.h" - - -// -// Absolute limits (from QData / QMView source) -// -#define MAX_FM_TRIANGLES 2048 -#define MAX_FM_VERTS 2048 -#define MAX_FM_FRAMES 2048 -#define MAX_FM_SKINS 64 -#define MAX_FM_SKINNAME 64 -#define MAX_FM_MESH_NODES 16 - -#define DTRIVERTX_V0 0 -#define DTRIVERTX_V1 1 -#define DTRIVERTX_V2 2 -#define DTRIVERTX_LNI 3 -#define DTRIVERTX_SIZE 4 - -#define SKINPAGE_WIDTH 640 -#define SKINPAGE_HEIGHT 480 - -#define ENCODED_WIDTH_X 92 -#define ENCODED_WIDTH_Y 475 -#define ENCODED_HEIGHT_X 128 -#define ENCODED_HEIGHT_Y 475 - -#define SCALE_ADJUST_FACTOR 0.96 - -#define INFO_HEIGHT 5 -#define INFO_Y ( SKINPAGE_HEIGHT - INFO_HEIGHT ) - -#ifndef byte - #define byte unsigned char -#endif - - -// -// Generic header on every chunk -// -#define FM_MAXCHUNKIDENT 32L -typedef struct -{ - char ident[FM_MAXCHUNKIDENT]; - unsigned int version; - unsigned int size; -} fm_chunk_header_t; - -// -// The format of the "header" chunk -// -#define FM_HEADERCHUNKNAME "header" -#define FM_HEADERCHUNKVER 2 -#define FM_HEADERCHUNKSIZE 40 -typedef struct -{ - int skinWidth; // in pixels - int skinHeight; // in pixels - int frameSize; // size of each frame (in bytes) - int numSkins; // number of skins - int numXYZ; // number of unique vertices in 3D space - int numST; // number of unique vertices in texture space - int numTris; // number of unique triangles - int numGLCmds; // # 32-bit elements in strip/fan command list - int numFrames; // number of animation frames - int numMeshNodes; // number of mesh nodes -} fm_header_t; - -// -// The format of an entry in the "skin" chunk. -// The number of entries is given in the fmheader chunk -// -#define FM_SKINCHUNKNAME "skin" -#define FM_SKINCHUNKVER 1 -#define FM_MAXPATHLENGTH 64L -#define FM_SKINPATHSIZE ( FM_MAXPATHLENGTH ) -typedef struct -{ - char path[FM_SKINPATHSIZE]; // path, relative to 'base' -} fm_skinpath_t; - -// -// The format of the "st coord" chunk. This is a list -// of unique skin texture (u, v) coordinates to be mapped -// to verteces of the model -// -#define FM_STCOORDCHUNKNAME "st coord" -#define FM_STCOORDCHUNKVER 1 -#define FM_STCOORDUVSIZE ( 2L + 2L ) - -typedef struct -{ - short s; - short t; -} fm_st_t; - -// -// The format of the "tris" chunk. This is a list of vertex indeces -// in 3D space, and the corresponding vertex indeces in texture space. -// -#define FM_TRISCHUNKNAME "tris" -#define FM_TRISCHUNKVER 1 -#define FM_TRISINFOSIZE ( 2L * 3 + 2L * 3 ) - -typedef struct -{ - short index_xyz[3]; - short index_st[3]; -} fm_xyz_st_t; - - -// -// The format of the "frames" chunk. This is a list of animation -// frames, each specifying the coordinates and "light normal" index -// of every vertex of the model in 3D space. -// -#define FM_FRAMESCHUNKNAME "frames" -#define FM_FRAMESCHUNKVER 1 - -#define FM_NUMVERTEXNORMALS 162 - -// Frame info -typedef struct -{ - byte v[3]; // scaled by header info - byte lightnormalindex; // index in canned table of closest vertex normal -} fm_vert_normal_t; - -typedef struct -{ - float scale[3]; // multiply byte verts by this - float translate[3]; // then add this - char name[16]; // frame name -} fm_framehdr_t; - -typedef struct -{ - fm_framehdr_t header; // One header per frame - fm_vert_normal_t verts[1]; // variable number of these -} fm_frame_t; - -typedef struct -{ - fm_chunk_header_t *fm_header_hdr; - fm_header_t *fm_header; - fm_chunk_header_t *fm_skin_hdr; - fm_skinpath_t *fm_skin; - fm_chunk_header_t *fm_st_hdr; - fm_st_t *fm_st; - fm_chunk_header_t *fm_tri_hdr; - fm_xyz_st_t *fm_tri; - fm_chunk_header_t *fm_frame_hdr; - fm_frame_t *fm_frame; -} fm_t; - -float fm_normals[FM_NUMVERTEXNORMALS][3] = { - {-0.525731f, 0.000000f, 0.850651f}, - {-0.442863f, 0.238856f, 0.864188f}, - {-0.295242f, 0.000000f, 0.955423f}, - {-0.309017f, 0.500000f, 0.809017f}, - {-0.162460f, 0.262866f, 0.951056f}, - {0.000000f, 0.000000f, 1.000000f}, - {0.000000f, 0.850651f, 0.525731f}, - {-0.147621f, 0.716567f, 0.681718f}, - {0.147621f, 0.716567f, 0.681718f}, - {0.000000f, 0.525731f, 0.850651f}, - {0.309017f, 0.500000f, 0.809017f}, - {0.525731f, 0.000000f, 0.850651f}, - {0.295242f, 0.000000f, 0.955423f}, - {0.442863f, 0.238856f, 0.864188f}, - {0.162460f, 0.262866f, 0.951056f}, - {-0.681718f, 0.147621f, 0.716567f}, - {-0.809017f, 0.309017f, 0.500000f}, - {-0.587785f, 0.425325f, 0.688191f}, - {-0.850651f, 0.525731f, 0.000000f}, - {-0.864188f, 0.442863f, 0.238856f}, - {-0.716567f, 0.681718f, 0.147621f}, - {-0.688191f, 0.587785f, 0.425325f}, - {-0.500000f, 0.809017f, 0.309017f}, - {-0.238856f, 0.864188f, 0.442863f}, - {-0.425325f, 0.688191f, 0.587785f}, - {-0.716567f, 0.681718f, -0.147621f}, - {-0.500000f, 0.809017f, -0.309017f}, - {-0.525731f, 0.850651f, 0.000000f}, - {0.000000f, 0.850651f, -0.525731f}, - {-0.238856f, 0.864188f, -0.442863f}, - {0.000000f, 0.955423f, -0.295242f}, - {-0.262866f, 0.951056f, -0.162460f}, - {0.000000f, 1.000000f, 0.000000f}, - {0.000000f, 0.955423f, 0.295242f}, - {-0.262866f, 0.951056f, 0.162460f}, - {0.238856f, 0.864188f, 0.442863f}, - {0.262866f, 0.951056f, 0.162460f}, - {0.500000f, 0.809017f, 0.309017f}, - {0.238856f, 0.864188f, -0.442863f}, - {0.262866f, 0.951056f, -0.162460f}, - {0.500000f, 0.809017f, -0.309017f}, - {0.850651f, 0.525731f, 0.000000f}, - {0.716567f, 0.681718f, 0.147621f}, - {0.716567f, 0.681718f, -0.147621f}, - {0.525731f, 0.850651f, 0.000000f}, - {0.425325f, 0.688191f, 0.587785f}, - {0.864188f, 0.442863f, 0.238856f}, - {0.688191f, 0.587785f, 0.425325f}, - {0.809017f, 0.309017f, 0.500000f}, - {0.681718f, 0.147621f, 0.716567f}, - {0.587785f, 0.425325f, 0.688191f}, - {0.955423f, 0.295242f, 0.000000f}, - {1.000000f, 0.000000f, 0.000000f}, - {0.951056f, 0.162460f, 0.262866f}, - {0.850651f, -0.525731f, 0.000000f}, - {0.955423f, -0.295242f, 0.000000f}, - {0.864188f, -0.442863f, 0.238856f}, - {0.951056f, -0.162460f, 0.262866f}, - {0.809017f, -0.309017f, 0.500000f}, - {0.681718f, -0.147621f, 0.716567f}, - {0.850651f, 0.000000f, 0.525731f}, - {0.864188f, 0.442863f, -0.238856f}, - {0.809017f, 0.309017f, -0.500000f}, - {0.951056f, 0.162460f, -0.262866f}, - {0.525731f, 0.000000f, -0.850651f}, - {0.681718f, 0.147621f, -0.716567f}, - {0.681718f, -0.147621f, -0.716567f}, - {0.850651f, 0.000000f, -0.525731f}, - {0.809017f, -0.309017f, -0.500000f}, - {0.864188f, -0.442863f, -0.238856f}, - {0.951056f, -0.162460f, -0.262866f}, - {0.147621f, 0.716567f, -0.681718f}, - {0.309017f, 0.500000f, -0.809017f}, - {0.425325f, 0.688191f, -0.587785f}, - {0.442863f, 0.238856f, -0.864188f}, - {0.587785f, 0.425325f, -0.688191f}, - {0.688191f, 0.587785f, -0.425325f}, - {-0.147621f, 0.716567f, -0.681718f}, - {-0.309017f, 0.500000f, -0.809017f}, - {0.000000f, 0.525731f, -0.850651f}, - {-0.525731f, 0.000000f, -0.850651f}, - {-0.442863f, 0.238856f, -0.864188f}, - {-0.295242f, 0.000000f, -0.955423f}, - {-0.162460f, 0.262866f, -0.951056f}, - {0.000000f, 0.000000f, -1.000000f}, - {0.295242f, 0.000000f, -0.955423f}, - {0.162460f, 0.262866f, -0.951056f}, - {-0.442863f, -0.238856f, -0.864188f}, - {-0.309017f, -0.500000f, -0.809017f}, - {-0.162460f, -0.262866f, -0.951056f}, - {0.000000f, -0.850651f, -0.525731f}, - {-0.147621f, -0.716567f, -0.681718f}, - {0.147621f, -0.716567f, -0.681718f}, - {0.000000f, -0.525731f, -0.850651f}, - {0.309017f, -0.500000f, -0.809017f}, - {0.442863f, -0.238856f, -0.864188f}, - {0.162460f, -0.262866f, -0.951056f}, - {0.238856f, -0.864188f, -0.442863f}, - {0.500000f, -0.809017f, -0.309017f}, - {0.425325f, -0.688191f, -0.587785f}, - {0.716567f, -0.681718f, -0.147621f}, - {0.688191f, -0.587785f, -0.425325f}, - {0.587785f, -0.425325f, -0.688191f}, - {0.000000f, -0.955423f, -0.295242f}, - {0.000000f, -1.000000f, 0.000000f}, - {0.262866f, -0.951056f, -0.162460f}, - {0.000000f, -0.850651f, 0.525731f}, - {0.000000f, -0.955423f, 0.295242f}, - {0.238856f, -0.864188f, 0.442863f}, - {0.262866f, -0.951056f, 0.162460f}, - {0.500000f, -0.809017f, 0.309017f}, - {0.716567f, -0.681718f, 0.147621f}, - {0.525731f, -0.850651f, 0.000000f}, - {-0.238856f, -0.864188f, -0.442863f}, - {-0.500000f, -0.809017f, -0.309017f}, - {-0.262866f, -0.951056f, -0.162460f}, - {-0.850651f, -0.525731f, 0.000000f}, - {-0.716567f, -0.681718f, -0.147621f}, - {-0.716567f, -0.681718f, 0.147621f}, - {-0.525731f, -0.850651f, 0.000000f}, - {-0.500000f, -0.809017f, 0.309017f}, - {-0.238856f, -0.864188f, 0.442863f}, - {-0.262866f, -0.951056f, 0.162460f}, - {-0.864188f, -0.442863f, 0.238856f}, - {-0.809017f, -0.309017f, 0.500000f}, - {-0.688191f, -0.587785f, 0.425325f}, - {-0.681718f, -0.147621f, 0.716567f}, - {-0.442863f, -0.238856f, 0.864188f}, - {-0.587785f, -0.425325f, 0.688191f}, - {-0.309017f, -0.500000f, 0.809017f}, - {-0.147621f, -0.716567f, 0.681718f}, - {-0.425325f, -0.688191f, 0.587785f}, - {-0.162460f, -0.262866f, 0.951056f}, - {0.442863f, -0.238856f, 0.864188f}, - {0.162460f, -0.262866f, 0.951056f}, - {0.309017f, -0.500000f, 0.809017f}, - {0.147621f, -0.716567f, 0.681718f}, - {0.000000f, -0.525731f, 0.850651f}, - {0.425325f, -0.688191f, 0.587785f}, - {0.587785f, -0.425325f, 0.688191f}, - {0.688191f, -0.587785f, 0.425325f}, - {-0.955423f, 0.295242f, 0.000000f}, - {-0.951056f, 0.162460f, 0.262866f}, - {-1.000000f, 0.000000f, 0.000000f}, - {-0.850651f, 0.000000f, 0.525731f}, - {-0.955423f, -0.295242f, 0.000000f}, - {-0.951056f, -0.162460f, 0.262866f}, - {-0.864188f, 0.442863f, -0.238856f}, - {-0.951056f, 0.162460f, -0.262866f}, - {-0.809017f, 0.309017f, -0.500000f}, - {-0.864188f, -0.442863f, -0.238856f}, - {-0.951056f, -0.162460f, -0.262866f}, - {-0.809017f, -0.309017f, -0.500000f}, - {-0.681718f, 0.147621f, -0.716567f}, - {-0.681718f, -0.147621f, -0.716567f}, - {-0.850651f, 0.000000f, -0.525731f}, - {-0.688191f, 0.587785f, -0.425325f}, - {-0.587785f, 0.425325f, -0.688191f}, - {-0.425325f, 0.688191f, -0.587785f}, - {-0.425325f, -0.688191f, -0.587785f}, - {-0.587785f, -0.425325f, -0.688191f}, - {-0.688191f, -0.587785f, -0.425325f}, -}; - -#endif diff --git a/tools/urt/libs/picomodel/pm_lwo.c b/tools/urt/libs/picomodel/pm_lwo.c deleted file mode 100644 index 177f3cd..0000000 --- a/tools/urt/libs/picomodel/pm_lwo.c +++ /dev/null @@ -1,423 +0,0 @@ -/* ----------------------------------------------------------------------------- - - PicoModel Library - - Copyright (c) 2002, Randy Reddig & seaw0lf - All rights reserved. - - Redistribution and use in source and binary forms, with or without modification, - are permitted provided that the following conditions are met: - - Redistributions of source code must retain the above copyright notice, this list - of conditions and the following disclaimer. - - Redistributions in binary form must reproduce the above copyright notice, this - list of conditions and the following disclaimer in the documentation and/or - other materials provided with the distribution. - - Neither the names of the copyright holders nor the names of its contributors may - be used to endorse or promote products derived from this software without - specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR - ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - ----------------------------------------------------------------------------- */ - -/* marker */ -#define PM_LWO_C - -/* dependencies */ -#include "picointernal.h" -#include "lwo/lwo2.h" - -/* uncomment when debugging this module */ -/*#define DEBUG_PM_LWO*/ - -#ifdef DEBUG_PM_LWO -#include "time.h" -#endif - -/* helper functions */ -static const char *lwo_lwIDToStr( unsigned int lwID ){ - static char lwIDStr[5]; - - if ( !lwID ) { - return "n/a"; - } - - lwIDStr[ 0 ] = (char)( ( lwID ) >> 24 ); - lwIDStr[ 1 ] = (char)( ( lwID ) >> 16 ); - lwIDStr[ 2 ] = (char)( ( lwID ) >> 8 ); - lwIDStr[ 3 ] = (char)( ( lwID ) ); - lwIDStr[ 4 ] = '\0'; - - return lwIDStr; -} - -/* - _lwo_canload() - validates a LightWave Object model file. btw, i use the - preceding underscore cause it's a static func referenced - by one structure only. - */ -static int _lwo_canload( PM_PARAMS_CANLOAD ){ - picoMemStream_t *s; - unsigned int failID = 0; - int failpos = -1; - int ret; - - /* create a new pico memorystream */ - s = _pico_new_memstream( (picoByte_t *)buffer, bufSize ); - if ( s == NULL ) { - return PICO_PMV_ERROR_MEMORY; - } - - ret = lwValidateObject( fileName, s, &failID, &failpos ); - - _pico_free_memstream( s ); - - return ret; -} - -/* - _lwo_load() - loads a LightWave Object model file. - */ -static picoModel_t *_lwo_load( PM_PARAMS_LOAD ){ - picoMemStream_t *s; - unsigned int failID = 0; - int failpos = -1; - lwObject *obj; - lwSurface *surface; - lwLayer *layer; - lwPoint *pt; - lwPolygon *pol; - lwPolVert *v; - lwVMapPt *vm; - char name[ 64 ]; - int i, j, k, numverts; - - picoModel_t *picoModel; - picoSurface_t *picoSurface; - picoShader_t *picoShader; - picoVec3_t xyz, normal; - picoVec2_t st; - picoColor_t color; - - int defaultSTAxis[ 2 ]; - picoVec2_t defaultXYZtoSTScale; - - picoVertexCombinationHash_t **hashTable; - picoVertexCombinationHash_t *vertexCombinationHash; - -#ifdef DEBUG_PM_LWO - clock_t load_start, load_finish, convert_start, convert_finish; - double load_elapsed, convert_elapsed; - - load_start = clock(); -#endif - - /* do frame check */ - if ( frameNum < 0 || frameNum >= 1 ) { - _pico_printf( PICO_ERROR, "Invalid or out-of-range LWO frame specified" ); - return NULL; - } - - /* create a new pico memorystream */ - s = _pico_new_memstream( (picoByte_t *)buffer, bufSize ); - if ( s == NULL ) { - return NULL; - } - - obj = lwGetObject( fileName, s, &failID, &failpos ); - - _pico_free_memstream( s ); - - if ( !obj ) { - _pico_printf( PICO_ERROR, "Couldn't load LWO file, failed on ID '%s', position %d", lwo_lwIDToStr( failID ), failpos ); - return NULL; - } - -#ifdef DEBUG_PM_LWO - convert_start = load_finish = clock(); - load_elapsed = (double)( load_finish - load_start ) / CLOCKS_PER_SEC; -#endif - - /* ------------------------------------------------- - pico model creation - ------------------------------------------------- */ - - /* create a new pico model */ - picoModel = PicoNewModel(); - if ( picoModel == NULL ) { - _pico_printf( PICO_ERROR, "Unable to allocate a new model" ); - return NULL; - } - - /* do model setup */ - PicoSetModelFrameNum( picoModel, frameNum ); - PicoSetModelNumFrames( picoModel, 1 ); - PicoSetModelName( picoModel, fileName ); - PicoSetModelFileName( picoModel, fileName ); - - /* create all polygons from layer[ 0 ] that belong to this surface */ - layer = &obj->layer[0]; - - /* warn the user that other layers are discarded */ - if ( obj->nlayers > 1 ) { - _pico_printf( PICO_WARNING, "LWO loader discards any geometry data not in Layer 1 (%d layers found)", obj->nlayers ); - } - - /* initialize dummy normal */ - normal[ 0 ] = normal[ 1 ] = normal[ 2 ] = 0.f; - - /* setup default st map */ - st[ 0 ] = st[ 1 ] = 0.f; /* st[0] holds max, st[1] holds max par one */ - defaultSTAxis[ 0 ] = 0; - defaultSTAxis[ 1 ] = 1; - for ( i = 0; i < 3; i++ ) - { - float min = layer->bbox[ i ]; - float max = layer->bbox[ i + 3 ]; - float size = max - min; - - if ( size > st[ 0 ] ) { - defaultSTAxis[ 1 ] = defaultSTAxis[ 0 ]; - defaultSTAxis[ 0 ] = i; - - st[ 1 ] = st[ 0 ]; - st[ 0 ] = size; - } - else if ( size > st[ 1 ] ) { - defaultSTAxis[ 1 ] = i; - st[ 1 ] = size; - } - } - defaultXYZtoSTScale[ 0 ] = 4.f / st[ 0 ]; - defaultXYZtoSTScale[ 1 ] = 4.f / st[ 1 ]; - - /* LWO surfaces become pico surfaces */ - surface = obj->surf; - while ( surface ) - { - /* allocate new pico surface */ - picoSurface = PicoNewSurface( picoModel ); - if ( picoSurface == NULL ) { - _pico_printf( PICO_ERROR, "Unable to allocate a new model surface" ); - PicoFreeModel( picoModel ); - lwFreeObject( obj ); - return NULL; - } - - /* LWO model surfaces are all triangle meshes */ - PicoSetSurfaceType( picoSurface, PICO_TRIANGLES ); - - /* set surface name */ - PicoSetSurfaceName( picoSurface, surface->name ); - - /* create new pico shader */ - picoShader = PicoNewShader( picoModel ); - if ( picoShader == NULL ) { - _pico_printf( PICO_ERROR, "Unable to allocate a new model shader" ); - PicoFreeModel( picoModel ); - lwFreeObject( obj ); - return NULL; - } - - /* detox and set shader name */ - strncpy( name, surface->name, sizeof( name ) ); - _pico_first_token( name ); - _pico_setfext( name, "" ); - _pico_unixify( name ); - PicoSetShaderName( picoShader, name ); - - /* associate current surface with newly created shader */ - PicoSetSurfaceShader( picoSurface, picoShader ); - - /* copy indices and vertex data */ - numverts = 0; - - hashTable = PicoNewVertexCombinationHashTable(); - - if ( hashTable == NULL ) { - _pico_printf( PICO_ERROR, "Unable to allocate hash table" ); - PicoFreeModel( picoModel ); - lwFreeObject( obj ); - return NULL; - } - - for ( i = 0, pol = layer->polygon.pol; i < layer->polygon.count; i++, pol++ ) - { - /* does this polygon belong to this surface? */ - if ( pol->surf != surface ) { - continue; - } - - /* we only support polygons of the FACE type */ - if ( pol->type != ID_FACE ) { - _pico_printf( PICO_WARNING, "LWO loader discarded a polygon because it's type != FACE (%s)", lwo_lwIDToStr( pol->type ) ); - continue; - } - - /* NOTE: LWO has support for non-convex polygons, do we want to store them as well? */ - if ( pol->nverts != 3 ) { - _pico_printf( PICO_WARNING, "LWO loader discarded a polygon because it has != 3 verts (%d)", pol->nverts ); - continue; - } - - for ( j = 0, v = pol->v; j < 3; j++, v++ ) - { - pt = &layer->point.pt[ v->index ]; - - /* setup data */ - xyz[ 0 ] = pt->pos[ 0 ]; - xyz[ 1 ] = pt->pos[ 2 ]; - xyz[ 2 ] = pt->pos[ 1 ]; - -/* doom3 lwo data doesn't seem to have smoothing-angle information */ -#if 0 - if ( surface->smooth <= 0 ) { - /* use face normals */ - normal[ 0 ] = v->norm[ 0 ]; - normal[ 1 ] = v->norm[ 2 ]; - normal[ 2 ] = v->norm[ 1 ]; - } - else -#endif - { - /* smooth normals later */ - normal[ 0 ] = 0; - normal[ 1 ] = 0; - normal[ 2 ] = 0; - } - - st[ 0 ] = xyz[ defaultSTAxis[ 0 ] ] * defaultXYZtoSTScale[ 0 ]; - st[ 1 ] = xyz[ defaultSTAxis[ 1 ] ] * defaultXYZtoSTScale[ 1 ]; - - color[ 0 ] = (picoByte_t)( surface->color.rgb[ 0 ] * surface->diffuse.val * 0xFF ); - color[ 1 ] = (picoByte_t)( surface->color.rgb[ 1 ] * surface->diffuse.val * 0xFF ); - color[ 2 ] = (picoByte_t)( surface->color.rgb[ 2 ] * surface->diffuse.val * 0xFF ); - color[ 3 ] = 0xFF; - - /* set from points */ - for ( k = 0, vm = pt->vm; k < pt->nvmaps; k++, vm++ ) - { - if ( vm->vmap->type == LWID_( 'T','X','U','V' ) ) { - /* set st coords */ - st[ 0 ] = vm->vmap->val[ vm->index ][ 0 ]; - st[ 1 ] = 1.f - vm->vmap->val[ vm->index ][ 1 ]; - } - else if ( vm->vmap->type == LWID_( 'R','G','B','A' ) ) { - /* set rgba */ - color[ 0 ] = (picoByte_t)( vm->vmap->val[ vm->index ][ 0 ] * surface->color.rgb[ 0 ] * surface->diffuse.val * 0xFF ); - color[ 1 ] = (picoByte_t)( vm->vmap->val[ vm->index ][ 1 ] * surface->color.rgb[ 1 ] * surface->diffuse.val * 0xFF ); - color[ 2 ] = (picoByte_t)( vm->vmap->val[ vm->index ][ 2 ] * surface->color.rgb[ 2 ] * surface->diffuse.val * 0xFF ); - color[ 3 ] = (picoByte_t)( vm->vmap->val[ vm->index ][ 3 ] * 0xFF ); - } - } - - /* override with polygon data */ - for ( k = 0, vm = v->vm; k < v->nvmaps; k++, vm++ ) - { - if ( vm->vmap->type == LWID_( 'T','X','U','V' ) ) { - /* set st coords */ - st[ 0 ] = vm->vmap->val[ vm->index ][ 0 ]; - st[ 1 ] = 1.f - vm->vmap->val[ vm->index ][ 1 ]; - } - else if ( vm->vmap->type == LWID_( 'R','G','B','A' ) ) { - /* set rgba */ - color[ 0 ] = (picoByte_t)( vm->vmap->val[ vm->index ][ 0 ] * surface->color.rgb[ 0 ] * surface->diffuse.val * 0xFF ); - color[ 1 ] = (picoByte_t)( vm->vmap->val[ vm->index ][ 1 ] * surface->color.rgb[ 1 ] * surface->diffuse.val * 0xFF ); - color[ 2 ] = (picoByte_t)( vm->vmap->val[ vm->index ][ 2 ] * surface->color.rgb[ 2 ] * surface->diffuse.val * 0xFF ); - color[ 3 ] = (picoByte_t)( vm->vmap->val[ vm->index ][ 3 ] * 0xFF ); - } - } - - /* find vertex in this surface and if we can't find it there create it */ - vertexCombinationHash = PicoFindVertexCombinationInHashTable( hashTable, xyz, normal, st, color ); - - if ( vertexCombinationHash ) { - /* found an existing one */ - PicoSetSurfaceIndex( picoSurface, ( i * 3 + j ), vertexCombinationHash->index ); - } - else - { - /* it is a new one */ - vertexCombinationHash = PicoAddVertexCombinationToHashTable( hashTable, xyz, normal, st, color, (picoIndex_t) numverts ); - - if ( vertexCombinationHash == NULL ) { - _pico_printf( PICO_ERROR, "Unable to allocate hash bucket entry table" ); - PicoFreeVertexCombinationHashTable( hashTable ); - PicoFreeModel( picoModel ); - lwFreeObject( obj ); - return NULL; - } - - /* add the vertex to this surface */ - PicoSetSurfaceXYZ( picoSurface, numverts, xyz ); - - /* set dummy normal */ - PicoSetSurfaceNormal( picoSurface, numverts, normal ); - - /* set color */ - PicoSetSurfaceColor( picoSurface, 0, numverts, color ); - - /* set st coords */ - PicoSetSurfaceST( picoSurface, 0, numverts, st ); - - /* set index */ - PicoSetSurfaceIndex( picoSurface, ( i * 3 + j ), (picoIndex_t) numverts ); - - numverts++; - } - } - } - - /* free the hashtable */ - PicoFreeVertexCombinationHashTable( hashTable ); - - /* get next surface */ - surface = surface->next; - } - -#ifdef DEBUG_PM_LWO - load_start = convert_finish = clock(); -#endif - - lwFreeObject( obj ); - -#ifdef DEBUG_PM_LWO - load_finish = clock(); - load_elapsed += (double)( load_finish - load_start ) / CLOCKS_PER_SEC; - convert_elapsed = (double)( convert_finish - convert_start ) / CLOCKS_PER_SEC; - _pico_printf( PICO_NORMAL, "Loaded model in in %-.2f second(s) (loading: %-.2fs converting: %-.2fs)\n", load_elapsed + convert_elapsed, load_elapsed, convert_elapsed ); -#endif - - /* return the new pico model */ - return picoModel; -} - -/* pico file format module definition */ -const picoModule_t picoModuleLWO = -{ - "1.0", /* module version string */ - "LightWave Object", /* module display name */ - "Arnout van Meer", /* author's name */ - "2003 Arnout van Meer, 2000 Ernie Wright", /* module copyright */ - { - "lwo", NULL, NULL, NULL /* default extensions to use */ - }, - _lwo_canload, /* validation routine */ - _lwo_load, /* load routine */ - NULL, /* save validation routine */ - NULL /* save routine */ -}; diff --git a/tools/urt/libs/picomodel/pm_md2.c b/tools/urt/libs/picomodel/pm_md2.c deleted file mode 100644 index 1aa5160..0000000 --- a/tools/urt/libs/picomodel/pm_md2.c +++ /dev/null @@ -1,664 +0,0 @@ -/* ----------------------------------------------------------------------------- - - PicoModel Library - - Copyright (c) 2002, Randy Reddig & seaw0lf - All rights reserved. - - Redistribution and use in source and binary forms, with or without modification, - are permitted provided that the following conditions are met: - - Redistributions of source code must retain the above copyright notice, this list - of conditions and the following disclaimer. - - Redistributions in binary form must reproduce the above copyright notice, this - list of conditions and the following disclaimer in the documentation and/or - other materials provided with the distribution. - - Neither the names of the copyright holders nor the names of its contributors may - be used to endorse or promote products derived from this software without - specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR - ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - ----------------------------------------------------------------------------- */ - -/* - Nurail: Used pm_md3.c (Randy Reddig) as a template. - */ - - -/* marker */ -#define PM_MD2_C - -/* dependencies */ -#include "picointernal.h" - - -/* md2 model format */ -#define MD2_MAGIC "IDP2" -#define MD2_VERSION 8 - -#define MD2_NUMVERTEXNORMALS 162 -#define MD2_MAX_SKINNAME 64 -#define MD2_MAX_TRIANGLES 4096 -#define MD2_MAX_VERTS 2048 -#define MD2_MAX_FRAMES 512 -#define MD2_MAX_MD2SKINS 32 -#define MD2_MAX_SKINNAME 64 - -#ifndef byte - #define byte unsigned char -#endif - -typedef struct index_LUT_s -{ - short Vert; - short ST; - struct index_LUT_s *next; - -} index_LUT_t; - -typedef struct index_DUP_LUT_s -{ - short ST; - short OldVert; - -} index_DUP_LUT_t; - -typedef struct -{ - short s; - short t; -} md2St_t; - -typedef struct -{ - short index_xyz[3]; - short index_st[3]; -} md2Triangle_t; - -typedef struct -{ - byte v[3]; // scaled byte to fit in frame mins/maxs - byte lightnormalindex; -} md2XyzNormal_t; - -typedef struct md2Frame_s -{ - float scale[3]; // multiply byte verts by this - float translate[3]; // then add this - char name[16]; // frame name from grabbing - md2XyzNormal_t verts[1]; // variable sized -} -md2Frame_t; - - -/* md2 model file md2 structure */ -typedef struct md2_s -{ - char magic[ 4 ]; - int version; - - int skinWidth; - int skinHeight; - int frameSize; - - int numSkins; - int numXYZ; - int numST; - int numTris; - int numGLCmds; - int numFrames; - - int ofsSkins; - int ofsST; - int ofsTris; - int ofsFrames; - int ofsGLCmds; - int ofsEnd; -} -md2_t; - -float md2_normals[ MD2_NUMVERTEXNORMALS ][ 3 ] = -{ - { -0.525731f, 0.000000f, 0.850651f }, - { -0.442863f, 0.238856f, 0.864188f }, - { -0.295242f, 0.000000f, 0.955423f }, - { -0.309017f, 0.500000f, 0.809017f }, - { -0.162460f, 0.262866f, 0.951056f }, - { 0.000000f, 0.000000f, 1.000000f }, - { 0.000000f, 0.850651f, 0.525731f }, - { -0.147621f, 0.716567f, 0.681718f }, - { 0.147621f, 0.716567f, 0.681718f }, - { 0.000000f, 0.525731f, 0.850651f }, - { 0.309017f, 0.500000f, 0.809017f }, - { 0.525731f, 0.000000f, 0.850651f }, - { 0.295242f, 0.000000f, 0.955423f }, - { 0.442863f, 0.238856f, 0.864188f }, - { 0.162460f, 0.262866f, 0.951056f }, - { -0.681718f, 0.147621f, 0.716567f }, - { -0.809017f, 0.309017f, 0.500000f }, - { -0.587785f, 0.425325f, 0.688191f }, - { -0.850651f, 0.525731f, 0.000000f }, - { -0.864188f, 0.442863f, 0.238856f }, - { -0.716567f, 0.681718f, 0.147621f }, - { -0.688191f, 0.587785f, 0.425325f }, - { -0.500000f, 0.809017f, 0.309017f }, - { -0.238856f, 0.864188f, 0.442863f }, - { -0.425325f, 0.688191f, 0.587785f }, - { -0.716567f, 0.681718f, -0.147621f }, - { -0.500000f, 0.809017f, -0.309017f }, - { -0.525731f, 0.850651f, 0.000000f }, - { 0.000000f, 0.850651f, -0.525731f }, - { -0.238856f, 0.864188f, -0.442863f }, - { 0.000000f, 0.955423f, -0.295242f }, - { -0.262866f, 0.951056f, -0.162460f }, - { 0.000000f, 1.000000f, 0.000000f }, - { 0.000000f, 0.955423f, 0.295242f }, - { -0.262866f, 0.951056f, 0.162460f }, - { 0.238856f, 0.864188f, 0.442863f }, - { 0.262866f, 0.951056f, 0.162460f }, - { 0.500000f, 0.809017f, 0.309017f }, - { 0.238856f, 0.864188f, -0.442863f }, - { 0.262866f, 0.951056f, -0.162460f }, - { 0.500000f, 0.809017f, -0.309017f }, - { 0.850651f, 0.525731f, 0.000000f }, - { 0.716567f, 0.681718f, 0.147621f }, - { 0.716567f, 0.681718f, -0.147621f }, - { 0.525731f, 0.850651f, 0.000000f }, - { 0.425325f, 0.688191f, 0.587785f }, - { 0.864188f, 0.442863f, 0.238856f }, - { 0.688191f, 0.587785f, 0.425325f }, - { 0.809017f, 0.309017f, 0.500000f }, - { 0.681718f, 0.147621f, 0.716567f }, - { 0.587785f, 0.425325f, 0.688191f }, - { 0.955423f, 0.295242f, 0.000000f }, - { 1.000000f, 0.000000f, 0.000000f }, - { 0.951056f, 0.162460f, 0.262866f }, - { 0.850651f, -0.525731f, 0.000000f }, - { 0.955423f, -0.295242f, 0.000000f }, - { 0.864188f, -0.442863f, 0.238856f }, - { 0.951056f, -0.162460f, 0.262866f }, - { 0.809017f, -0.309017f, 0.500000f }, - { 0.681718f, -0.147621f, 0.716567f }, - { 0.850651f, 0.000000f, 0.525731f }, - { 0.864188f, 0.442863f, -0.238856f }, - { 0.809017f, 0.309017f, -0.500000f }, - { 0.951056f, 0.162460f, -0.262866f }, - { 0.525731f, 0.000000f, -0.850651f }, - { 0.681718f, 0.147621f, -0.716567f }, - { 0.681718f, -0.147621f, -0.716567f }, - { 0.850651f, 0.000000f, -0.525731f }, - { 0.809017f, -0.309017f, -0.500000f }, - { 0.864188f, -0.442863f, -0.238856f }, - { 0.951056f, -0.162460f, -0.262866f }, - { 0.147621f, 0.716567f, -0.681718f }, - { 0.309017f, 0.500000f, -0.809017f }, - { 0.425325f, 0.688191f, -0.587785f }, - { 0.442863f, 0.238856f, -0.864188f }, - { 0.587785f, 0.425325f, -0.688191f }, - { 0.688191f, 0.587785f, -0.425325f }, - { -0.147621f, 0.716567f, -0.681718f }, - { -0.309017f, 0.500000f, -0.809017f }, - { 0.000000f, 0.525731f, -0.850651f }, - { -0.525731f, 0.000000f, -0.850651f }, - { -0.442863f, 0.238856f, -0.864188f }, - { -0.295242f, 0.000000f, -0.955423f }, - { -0.162460f, 0.262866f, -0.951056f }, - { 0.000000f, 0.000000f, -1.000000f }, - { 0.295242f, 0.000000f, -0.955423f }, - { 0.162460f, 0.262866f, -0.951056f }, - { -0.442863f, -0.238856f, -0.864188f }, - { -0.309017f, -0.500000f, -0.809017f }, - { -0.162460f, -0.262866f, -0.951056f }, - { 0.000000f, -0.850651f, -0.525731f }, - { -0.147621f, -0.716567f, -0.681718f }, - { 0.147621f, -0.716567f, -0.681718f }, - { 0.000000f, -0.525731f, -0.850651f }, - { 0.309017f, -0.500000f, -0.809017f }, - { 0.442863f, -0.238856f, -0.864188f }, - { 0.162460f, -0.262866f, -0.951056f }, - { 0.238856f, -0.864188f, -0.442863f }, - { 0.500000f, -0.809017f, -0.309017f }, - { 0.425325f, -0.688191f, -0.587785f }, - { 0.716567f, -0.681718f, -0.147621f }, - { 0.688191f, -0.587785f, -0.425325f }, - { 0.587785f, -0.425325f, -0.688191f }, - { 0.000000f, -0.955423f, -0.295242f }, - { 0.000000f, -1.000000f, 0.000000f }, - { 0.262866f, -0.951056f, -0.162460f }, - { 0.000000f, -0.850651f, 0.525731f }, - { 0.000000f, -0.955423f, 0.295242f }, - { 0.238856f, -0.864188f, 0.442863f }, - { 0.262866f, -0.951056f, 0.162460f }, - { 0.500000f, -0.809017f, 0.309017f }, - { 0.716567f, -0.681718f, 0.147621f }, - { 0.525731f, -0.850651f, 0.000000f }, - { -0.238856f, -0.864188f, -0.442863f }, - { -0.500000f, -0.809017f, -0.309017f }, - { -0.262866f, -0.951056f, -0.162460f }, - { -0.850651f, -0.525731f, 0.000000f }, - { -0.716567f, -0.681718f, -0.147621f }, - { -0.716567f, -0.681718f, 0.147621f }, - { -0.525731f, -0.850651f, 0.000000f }, - { -0.500000f, -0.809017f, 0.309017f }, - { -0.238856f, -0.864188f, 0.442863f }, - { -0.262866f, -0.951056f, 0.162460f }, - { -0.864188f, -0.442863f, 0.238856f }, - { -0.809017f, -0.309017f, 0.500000f }, - { -0.688191f, -0.587785f, 0.425325f }, - { -0.681718f, -0.147621f, 0.716567f }, - { -0.442863f, -0.238856f, 0.864188f }, - { -0.587785f, -0.425325f, 0.688191f }, - { -0.309017f, -0.500000f, 0.809017f }, - { -0.147621f, -0.716567f, 0.681718f }, - { -0.425325f, -0.688191f, 0.587785f }, - { -0.162460f, -0.262866f, 0.951056f }, - { 0.442863f, -0.238856f, 0.864188f }, - { 0.162460f, -0.262866f, 0.951056f }, - { 0.309017f, -0.500000f, 0.809017f }, - { 0.147621f, -0.716567f, 0.681718f }, - { 0.000000f, -0.525731f, 0.850651f }, - { 0.425325f, -0.688191f, 0.587785f }, - { 0.587785f, -0.425325f, 0.688191f }, - { 0.688191f, -0.587785f, 0.425325f }, - { -0.955423f, 0.295242f, 0.000000f }, - { -0.951056f, 0.162460f, 0.262866f }, - { -1.000000f, 0.000000f, 0.000000f }, - { -0.850651f, 0.000000f, 0.525731f }, - { -0.955423f, -0.295242f, 0.000000f }, - { -0.951056f, -0.162460f, 0.262866f }, - { -0.864188f, 0.442863f, -0.238856f }, - { -0.951056f, 0.162460f, -0.262866f }, - { -0.809017f, 0.309017f, -0.500000f }, - { -0.864188f, -0.442863f, -0.238856f }, - { -0.951056f, -0.162460f, -0.262866f }, - { -0.809017f, -0.309017f, -0.500000f }, - { -0.681718f, 0.147621f, -0.716567f }, - { -0.681718f, -0.147621f, -0.716567f }, - { -0.850651f, 0.000000f, -0.525731f }, - { -0.688191f, 0.587785f, -0.425325f }, - { -0.587785f, 0.425325f, -0.688191f }, - { -0.425325f, 0.688191f, -0.587785f }, - { -0.425325f, -0.688191f, -0.587785f }, - { -0.587785f, -0.425325f, -0.688191f }, - { -0.688191f, -0.587785f, -0.425325f }, -}; - - -// _md2_canload() - -static int _md2_canload( PM_PARAMS_CANLOAD ){ - md2_t *md2; - - /* to keep the compiler happy */ - *fileName = *fileName; - - /* sanity check */ - if ( bufSize < ( sizeof( *md2 ) * 2 ) ) { - return PICO_PMV_ERROR_SIZE; - } - - /* set as md2 */ - md2 = (md2_t*) buffer; - - /* check md2 magic */ - if ( *( (int*) md2->magic ) != *( (int*) MD2_MAGIC ) ) { - return PICO_PMV_ERROR_IDENT; - } - - /* check md2 version */ - if ( _pico_little_long( md2->version ) != MD2_VERSION ) { - return PICO_PMV_ERROR_VERSION; - } - - /* file seems to be a valid md2 */ - return PICO_PMV_OK; -} - - - -// _md2_load() loads a quake2 md2 model file. - - -static picoModel_t *_md2_load( PM_PARAMS_LOAD ){ - int i, j, dups, dup_index; - short tot_numVerts; - index_LUT_t *p_index_LUT, *p_index_LUT2, *p_index_LUT3; - index_DUP_LUT_t *p_index_LUT_DUPS; - md2Triangle_t *p_md2Triangle; - - char skinname[ MD2_MAX_SKINNAME ]; - md2_t *md2; - md2St_t *texCoord; - md2Frame_t *frame; - md2Triangle_t *triangle; - md2XyzNormal_t *vertex; - - picoByte_t *bb; - picoModel_t *picoModel; - picoSurface_t *picoSurface; - picoShader_t *picoShader; - picoVec3_t xyz, normal; - picoVec2_t st; - picoColor_t color; - - - /* set as md2 */ - bb = (picoByte_t*) buffer; - md2 = (md2_t*) buffer; - - /* check ident and version */ - if ( *( (int*) md2->magic ) != *( (int*) MD2_MAGIC ) || _pico_little_long( md2->version ) != MD2_VERSION ) { - /* not an md2 file (todo: set error) */ - _pico_printf( PICO_ERROR, "%s is not an MD2 File!", fileName ); - return NULL; - } - - // swap md2 - md2->version = _pico_little_long( md2->version ); - - md2->skinWidth = _pico_little_long( md2->skinWidth ); - md2->skinHeight = _pico_little_long( md2->skinHeight ); - md2->frameSize = _pico_little_long( md2->frameSize ); - - md2->numSkins = _pico_little_long( md2->numSkins ); - md2->numXYZ = _pico_little_long( md2->numXYZ ); - md2->numST = _pico_little_long( md2->numST ); - md2->numTris = _pico_little_long( md2->numTris ); - md2->numGLCmds = _pico_little_long( md2->numGLCmds ); - md2->numFrames = _pico_little_long( md2->numFrames ); - - md2->ofsSkins = _pico_little_long( md2->ofsSkins ); - md2->ofsST = _pico_little_long( md2->ofsST ); - md2->ofsTris = _pico_little_long( md2->ofsTris ); - md2->ofsFrames = _pico_little_long( md2->ofsFrames ); - md2->ofsGLCmds = _pico_little_long( md2->ofsGLCmds ); - md2->ofsEnd = _pico_little_long( md2->ofsEnd ); - - // do frame check - if ( md2->numFrames < 1 ) { - _pico_printf( PICO_ERROR, "%s has 0 frames!", fileName ); - return NULL; - } - - if ( frameNum < 0 || frameNum >= md2->numFrames ) { - _pico_printf( PICO_ERROR, "Invalid or out-of-range MD2 frame specified" ); - return NULL; - } - - // Setup Frame - frame = (md2Frame_t *) ( bb + md2->ofsFrames + ( sizeof( md2Frame_t ) * frameNum ) ); - - // swap frame scale and translation - for ( i = 0; i < 3; i++ ) - { - frame->scale[ i ] = _pico_little_float( frame->scale[ i ] ); - frame->translate[ i ] = _pico_little_float( frame->translate[ i ] ); - } - - // swap triangles - triangle = (md2Triangle_t *) ( (picoByte_t *) ( bb + md2->ofsTris ) ); - for ( i = 0; i < md2->numTris; i++, triangle++ ) - { - for ( j = 0; j < 3; j++ ) - { - triangle->index_xyz[ j ] = _pico_little_short( triangle->index_xyz[ j ] ); - triangle->index_st[ j ] = _pico_little_short( triangle->index_st[ j ] ); - } - } - - // swap st coords - texCoord = (md2St_t*) ( (picoByte_t *) ( bb + md2->ofsST ) ); - for ( i = 0; i < md2->numST; i++, texCoord++ ) - { - texCoord->s = _pico_little_short( texCoord->s ); - texCoord->t = _pico_little_short( texCoord->t ); - } - - // set Skin Name - strncpy( skinname, ( bb + md2->ofsSkins ), MD2_MAX_SKINNAME ); - - // Print out md2 values - _pico_printf( PICO_VERBOSE,"Skins: %d Verts: %d STs: %d Triangles: %d Frames: %d\nSkin Name \"%s\"\n", md2->numSkins, md2->numXYZ, md2->numST, md2->numTris, md2->numFrames, &skinname ); - - // detox Skin name - _pico_setfext( skinname, "" ); - _pico_unixify( skinname ); - - /* create new pico model */ - picoModel = PicoNewModel(); - if ( picoModel == NULL ) { - _pico_printf( PICO_ERROR, "Unable to allocate a new model" ); - return NULL; - } - - /* do model setup */ - PicoSetModelFrameNum( picoModel, frameNum ); - PicoSetModelNumFrames( picoModel, md2->numFrames ); /* sea */ - PicoSetModelName( picoModel, fileName ); - PicoSetModelFileName( picoModel, fileName ); - - // allocate new pico surface - picoSurface = PicoNewSurface( picoModel ); - if ( picoSurface == NULL ) { - _pico_printf( PICO_ERROR, "Unable to allocate a new model surface" ); - PicoFreeModel( picoModel ); - return NULL; - } - - - PicoSetSurfaceType( picoSurface, PICO_TRIANGLES ); - PicoSetSurfaceName( picoSurface, frame->name ); - picoShader = PicoNewShader( picoModel ); - if ( picoShader == NULL ) { - _pico_printf( PICO_ERROR, "Unable to allocate a new model shader" ); - PicoFreeModel( picoModel ); - return NULL; - } - - PicoSetShaderName( picoShader, skinname ); - - // associate current surface with newly created shader - PicoSetSurfaceShader( picoSurface, picoShader ); - - // Init LUT for Verts - p_index_LUT = (index_LUT_t *)_pico_alloc( sizeof( index_LUT_t ) * md2->numXYZ ); - for ( i = 0; i < md2->numXYZ; i++ ) - { - p_index_LUT[i].Vert = -1; - p_index_LUT[i].ST = -1; - p_index_LUT[i].next = NULL; - } - - // Fill in Look Up Table, and allocate/fill Linked List from vert array as needed for dup STs per Vert. - tot_numVerts = md2->numXYZ; - dups = 0; - for ( i = 0; i < md2->numTris; i++ ) - { - p_md2Triangle = (md2Triangle_t *) ( bb + md2->ofsTris + ( sizeof( md2Triangle_t ) * i ) ); - for ( j = 0; j < 3; j++ ) - { - if ( p_index_LUT[p_md2Triangle->index_xyz[j]].ST == -1 ) { // No Main Entry - p_index_LUT[p_md2Triangle->index_xyz[j]].ST = p_md2Triangle->index_st[j]; - } - - else if ( p_md2Triangle->index_st[j] == p_index_LUT[p_md2Triangle->index_xyz[j]].ST ) { // Equal to Main Entry - continue; - } - - else if ( ( p_index_LUT[p_md2Triangle->index_xyz[j]].next == NULL ) ) { // Not equal to Main entry, and no LL entry - // Add first entry of LL from Main - p_index_LUT2 = (index_LUT_t *)_pico_alloc( sizeof( index_LUT_t ) ); - if ( p_index_LUT2 == NULL ) { - _pico_printf( PICO_ERROR," Couldn't allocate memory!\n" ); - } - p_index_LUT[p_md2Triangle->index_xyz[j]].next = (index_LUT_t *)p_index_LUT2; - p_index_LUT2->Vert = dups; - p_index_LUT2->ST = p_md2Triangle->index_st[j]; - p_index_LUT2->next = NULL; - p_md2Triangle->index_xyz[j] = dups + md2->numXYZ; // Make change in Tri hunk - dups++; - } - else // Try to find in LL from Main Entry - { - p_index_LUT3 = p_index_LUT2 = p_index_LUT[p_md2Triangle->index_xyz[j]].next; - while ( ( p_index_LUT2 != NULL ) && ( p_md2Triangle->index_xyz[j] != p_index_LUT2->Vert ) ) // Walk down LL - { - p_index_LUT3 = p_index_LUT2; - p_index_LUT2 = p_index_LUT2->next; - } - p_index_LUT2 = p_index_LUT3; - - if ( p_md2Triangle->index_st[j] == p_index_LUT2->ST ) { // Found it - p_md2Triangle->index_xyz[j] = p_index_LUT2->Vert + md2->numXYZ; // Make change in Tri hunk - continue; - } - - if ( p_index_LUT2->next == NULL ) { // Didn't find it. Add entry to LL. - // Add the Entry - p_index_LUT3 = (index_LUT_t *)_pico_alloc( sizeof( index_LUT_t ) ); - if ( p_index_LUT3 == NULL ) { - _pico_printf( PICO_ERROR," Couldn't allocate memory!\n" ); - } - p_index_LUT2->next = (index_LUT_t *)p_index_LUT3; - p_index_LUT3->Vert = p_md2Triangle->index_xyz[j]; - p_index_LUT3->ST = p_md2Triangle->index_st[j]; - p_index_LUT3->next = NULL; - p_md2Triangle->index_xyz[j] = dups + md2->numXYZ; // Make change in Tri hunk - dups++; - } - } - } - } - - // malloc and build array for Dup STs - p_index_LUT_DUPS = (index_DUP_LUT_t *)_pico_alloc( sizeof( index_DUP_LUT_t ) * dups ); - if ( p_index_LUT_DUPS == NULL ) { - _pico_printf( PICO_ERROR," Couldn't allocate memory!\n" ); - } - - dup_index = 0; - for ( i = 0; i < md2->numXYZ; i++ ) - { - p_index_LUT2 = p_index_LUT[i].next; - while ( p_index_LUT2 != NULL ) - { - p_index_LUT_DUPS[p_index_LUT2->Vert].OldVert = i; - p_index_LUT_DUPS[p_index_LUT2->Vert].ST = p_index_LUT2->ST; - dup_index++; - p_index_LUT2 = p_index_LUT2->next; - } - } - - // Build Picomodel - triangle = (md2Triangle_t *) ( (picoByte_t *) ( bb + md2->ofsTris ) ); - texCoord = (md2St_t*) ( (picoByte_t *) ( bb + md2->ofsST ) ); - vertex = (md2XyzNormal_t*) ( (picoByte_t*) ( frame->verts ) ); - for ( j = 0; j < md2->numTris; j++, triangle++ ) - { - PicoSetSurfaceIndex( picoSurface, j * 3, triangle->index_xyz[0] ); - PicoSetSurfaceIndex( picoSurface, j * 3 + 1, triangle->index_xyz[1] ); - PicoSetSurfaceIndex( picoSurface, j * 3 + 2, triangle->index_xyz[2] ); - } - - for ( i = 0; i < md2->numXYZ; i++, vertex++ ) - { - /* set vertex origin */ - xyz[ 0 ] = vertex->v[0] * frame->scale[0] + frame->translate[0]; - xyz[ 1 ] = vertex->v[1] * frame->scale[1] + frame->translate[1]; - xyz[ 2 ] = vertex->v[2] * frame->scale[2] + frame->translate[2]; - PicoSetSurfaceXYZ( picoSurface, i, xyz ); - - /* set normal */ - normal[ 0 ] = md2_normals[vertex->lightnormalindex][0]; - normal[ 1 ] = md2_normals[vertex->lightnormalindex][1]; - normal[ 2 ] = md2_normals[vertex->lightnormalindex][2]; - PicoSetSurfaceNormal( picoSurface, i, normal ); - - /* set st coords */ - st[ 0 ] = ( ( texCoord[p_index_LUT[i].ST].s ) / ( (float)md2->skinWidth ) ); - st[ 1 ] = ( texCoord[p_index_LUT[i].ST].t / ( (float)md2->skinHeight ) ); - PicoSetSurfaceST( picoSurface, 0, i, st ); - } - - if ( dups ) { - for ( i = 0; i < dups; i++ ) - { - j = p_index_LUT_DUPS[i].OldVert; - /* set vertex origin */ - xyz[ 0 ] = frame->verts[j].v[0] * frame->scale[0] + frame->translate[0]; - xyz[ 1 ] = frame->verts[j].v[1] * frame->scale[1] + frame->translate[1]; - xyz[ 2 ] = frame->verts[j].v[2] * frame->scale[2] + frame->translate[2]; - PicoSetSurfaceXYZ( picoSurface, i + md2->numXYZ, xyz ); - - /* set normal */ - normal[ 0 ] = md2_normals[frame->verts[j].lightnormalindex][0]; - normal[ 1 ] = md2_normals[frame->verts[j].lightnormalindex][1]; - normal[ 2 ] = md2_normals[frame->verts[j].lightnormalindex][2]; - PicoSetSurfaceNormal( picoSurface, i + md2->numXYZ, normal ); - - /* set st coords */ - st[ 0 ] = ( ( texCoord[p_index_LUT_DUPS[i].ST].s ) / ( (float)md2->skinWidth ) ); - st[ 1 ] = ( texCoord[p_index_LUT_DUPS[i].ST].t / ( (float)md2->skinHeight ) ); - PicoSetSurfaceST( picoSurface, 0, i + md2->numXYZ, st ); - } - } - - /* set color */ - PicoSetSurfaceColor( picoSurface, 0, 0, color ); - - // Free up malloc'ed LL entries - for ( i = 0; i < md2->numXYZ; i++ ) - { - if ( p_index_LUT[i].next != NULL ) { - p_index_LUT2 = p_index_LUT[i].next; - do { - p_index_LUT3 = p_index_LUT2->next; - _pico_free( p_index_LUT2 ); - p_index_LUT2 = p_index_LUT3; - dups--; - } while ( p_index_LUT2 != NULL ); - } - } - - if ( dups ) { - _pico_printf( PICO_WARNING, " Not all LL mallocs freed\n" ); - } - - // Free malloc'ed LUTs - _pico_free( p_index_LUT ); - _pico_free( p_index_LUT_DUPS ); - - /* return the new pico model */ - return picoModel; - -} - - - -/* pico file format module definition */ -const picoModule_t picoModuleMD2 = -{ - "0.875", /* module version string */ - "Quake 2 MD2", /* module display name */ - "Nurail", /* author's name */ - "2003 Nurail", /* module copyright */ - { - "md2", NULL, NULL, NULL /* default extensions to use */ - }, - _md2_canload, /* validation routine */ - _md2_load, /* load routine */ - NULL, /* save validation routine */ - NULL /* save routine */ -}; diff --git a/tools/urt/libs/picomodel/pm_md3.c b/tools/urt/libs/picomodel/pm_md3.c deleted file mode 100644 index 94f7a8f..0000000 --- a/tools/urt/libs/picomodel/pm_md3.c +++ /dev/null @@ -1,420 +0,0 @@ -/* ----------------------------------------------------------------------------- - - PicoModel Library - - Copyright (c) 2002, Randy Reddig & seaw0lf - All rights reserved. - - Redistribution and use in source and binary forms, with or without modification, - are permitted provided that the following conditions are met: - - Redistributions of source code must retain the above copyright notice, this list - of conditions and the following disclaimer. - - Redistributions in binary form must reproduce the above copyright notice, this - list of conditions and the following disclaimer in the documentation and/or - other materials provided with the distribution. - - Neither the names of the copyright holders nor the names of its contributors may - be used to endorse or promote products derived from this software without - specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR - ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - ----------------------------------------------------------------------------- */ - - - -/* marker */ -#define PM_MD3_C - - - -/* dependencies */ -#include "picointernal.h" - - - -/* md3 model format */ -#define MD3_MAGIC "IDP3" -#define MD3_VERSION 15 - -/* md3 vertex scale */ -#define MD3_SCALE ( 1.0f / 64.0f ) - -/* md3 model frame information */ -typedef struct md3Frame_s -{ - float bounds[ 2 ][ 3 ]; - float localOrigin[ 3 ]; - float radius; - char creator[ 16 ]; -} -md3Frame_t; - -/* md3 model tag information */ -typedef struct md3Tag_s -{ - char name[ 64 ]; - float origin[ 3 ]; - float axis[ 3 ][ 3 ]; -} -md3Tag_t; - -/* md3 surface md3 (one object mesh) */ -typedef struct md3Surface_s -{ - char magic[ 4 ]; - char name[ 64 ]; /* polyset name */ - int flags; - int numFrames; /* all model surfaces should have the same */ - int numShaders; /* all model surfaces should have the same */ - int numVerts; - int numTriangles; - int ofsTriangles; - int ofsShaders; /* offset from start of md3Surface_t */ - int ofsSt; /* texture coords are common for all frames */ - int ofsVertexes; /* numVerts * numFrames */ - int ofsEnd; /* next surface follows */ -} -md3Surface_t; - -typedef struct md3Shader_s -{ - char name[ 64 ]; - int shaderIndex; /* for ingame use */ -} -md3Shader_t; - -typedef struct md3Triangle_s -{ - int indexes[ 3 ]; -} -md3Triangle_t; - -typedef struct md3TexCoord_s -{ - float st[ 2 ]; -} -md3TexCoord_t; - -typedef struct md3Vertex_s -{ - short xyz[ 3 ]; - short normal; -} -md3Vertex_t; - - -/* md3 model file md3 structure */ -typedef struct md3_s -{ - char magic[ 4 ]; /* MD3_MAGIC */ - int version; - char name[ 64 ]; /* model name */ - int flags; - int numFrames; - int numTags; - int numSurfaces; - int numSkins; /* number of skins for the mesh */ - int ofsFrames; /* offset for first frame */ - int ofsTags; /* numFrames * numTags */ - int ofsSurfaces; /* first surface, others follow */ - int ofsEnd; /* end of file */ -} -md3_t; - - - - -/* - _md3_canload() - validates a quake3 arena md3 model file. btw, i use the - preceding underscore cause it's a static func referenced - by one structure only. - */ - -static int _md3_canload( PM_PARAMS_CANLOAD ){ - md3_t *md3; - - - /* to keep the compiler happy */ - *fileName = *fileName; - - /* sanity check */ - if ( bufSize < ( sizeof( *md3 ) * 2 ) ) { - return PICO_PMV_ERROR_SIZE; - } - - /* set as md3 */ - md3 = (md3_t*) buffer; - - /* check md3 magic */ - if ( *( (int*) md3->magic ) != *( (int*) MD3_MAGIC ) ) { - return PICO_PMV_ERROR_IDENT; - } - - /* check md3 version */ - if ( _pico_little_long( md3->version ) != MD3_VERSION ) { - return PICO_PMV_ERROR_VERSION; - } - - /* file seems to be a valid md3 */ - return PICO_PMV_OK; -} - - - -/* - _md3_load() - loads a quake3 arena md3 model file. - */ - -static picoModel_t *_md3_load( PM_PARAMS_LOAD ){ - int i, j; - picoByte_t *bb; - md3_t *md3; - md3Surface_t *surface; - md3Shader_t *shader; - md3TexCoord_t *texCoord; - md3Frame_t *frame; - md3Triangle_t *triangle; - md3Vertex_t *vertex; - double lat, lng; - - picoModel_t *picoModel; - picoSurface_t *picoSurface; - picoShader_t *picoShader; - picoVec3_t xyz, normal; - picoVec2_t st; - picoColor_t color; - - - /* ------------------------------------------------- - md3 loading - ------------------------------------------------- */ - - - /* set as md3 */ - bb = (picoByte_t*) buffer; - md3 = (md3_t*) buffer; - - /* check ident and version */ - if ( *( (int*) md3->magic ) != *( (int*) MD3_MAGIC ) || _pico_little_long( md3->version ) != MD3_VERSION ) { - /* not an md3 file (todo: set error) */ - return NULL; - } - - /* swap md3; sea: swaps fixed */ - md3->version = _pico_little_long( md3->version ); - md3->numFrames = _pico_little_long( md3->numFrames ); - md3->numTags = _pico_little_long( md3->numTags ); - md3->numSurfaces = _pico_little_long( md3->numSurfaces ); - md3->numSkins = _pico_little_long( md3->numSkins ); - md3->ofsFrames = _pico_little_long( md3->ofsFrames ); - md3->ofsTags = _pico_little_long( md3->ofsTags ); - md3->ofsSurfaces = _pico_little_long( md3->ofsSurfaces ); - md3->ofsEnd = _pico_little_long( md3->ofsEnd ); - - /* do frame check */ - if ( md3->numFrames < 1 ) { - _pico_printf( PICO_ERROR, "MD3 with 0 frames" ); - return NULL; - } - - if ( frameNum < 0 || frameNum >= md3->numFrames ) { - _pico_printf( PICO_ERROR, "Invalid or out-of-range MD3 frame specified" ); - return NULL; - } - - /* swap frames */ - frame = (md3Frame_t*) ( bb + md3->ofsFrames ); - for ( i = 0; i < md3->numFrames; i++, frame++ ) - { - frame->radius = _pico_little_float( frame->radius ); - for ( j = 0; j < 3; j++ ) - { - frame->bounds[ 0 ][ j ] = _pico_little_float( frame->bounds[ 0 ][ j ] ); - frame->bounds[ 1 ][ j ] = _pico_little_float( frame->bounds[ 1 ][ j ] ); - frame->localOrigin[ j ] = _pico_little_float( frame->localOrigin[ j ] ); - } - } - - /* swap surfaces */ - surface = (md3Surface_t*) ( bb + md3->ofsSurfaces ); - for ( i = 0; i < md3->numSurfaces; i++ ) - { - /* swap surface md3; sea: swaps fixed */ - surface->flags = _pico_little_long( surface->flags ); - surface->numFrames = _pico_little_long( surface->numFrames ); - surface->numShaders = _pico_little_long( surface->numShaders ); - surface->numTriangles = _pico_little_long( surface->numTriangles ); - surface->ofsTriangles = _pico_little_long( surface->ofsTriangles ); - surface->numVerts = _pico_little_long( surface->numVerts ); - surface->ofsShaders = _pico_little_long( surface->ofsShaders ); - surface->ofsSt = _pico_little_long( surface->ofsSt ); - surface->ofsVertexes = _pico_little_long( surface->ofsVertexes ); - surface->ofsEnd = _pico_little_long( surface->ofsEnd ); - - /* swap triangles */ - triangle = (md3Triangle_t*) ( (picoByte_t*) surface + surface->ofsTriangles ); - for ( j = 0; j < surface->numTriangles; j++, triangle++ ) - { - /* sea: swaps fixed */ - triangle->indexes[ 0 ] = _pico_little_long( triangle->indexes[ 0 ] ); - triangle->indexes[ 1 ] = _pico_little_long( triangle->indexes[ 1 ] ); - triangle->indexes[ 2 ] = _pico_little_long( triangle->indexes[ 2 ] ); - } - - /* swap st coords */ - texCoord = (md3TexCoord_t*) ( (picoByte_t*) surface + surface->ofsSt ); - for ( j = 0; j < surface->numVerts; j++, texCoord++ ) - { - texCoord->st[ 0 ] = _pico_little_float( texCoord->st[ 0 ] ); - texCoord->st[ 1 ] = _pico_little_float( texCoord->st[ 1 ] ); - } - - /* swap xyz/normals */ - vertex = (md3Vertex_t*) ( (picoByte_t*) surface + surface->ofsVertexes ); - for ( j = 0; j < ( surface->numVerts * surface->numFrames ); j++, vertex++ ) - { - vertex->xyz[ 0 ] = _pico_little_short( vertex->xyz[ 0 ] ); - vertex->xyz[ 1 ] = _pico_little_short( vertex->xyz[ 1 ] ); - vertex->xyz[ 2 ] = _pico_little_short( vertex->xyz[ 2 ] ); - vertex->normal = _pico_little_short( vertex->normal ); - } - - /* get next surface */ - surface = (md3Surface_t*) ( (picoByte_t*) surface + surface->ofsEnd ); - } - - /* ------------------------------------------------- - pico model creation - ------------------------------------------------- */ - - /* create new pico model */ - picoModel = PicoNewModel(); - if ( picoModel == NULL ) { - _pico_printf( PICO_ERROR, "Unable to allocate a new model" ); - return NULL; - } - - /* do model setup */ - PicoSetModelFrameNum( picoModel, frameNum ); - PicoSetModelNumFrames( picoModel, md3->numFrames ); /* sea */ - PicoSetModelName( picoModel, fileName ); - PicoSetModelFileName( picoModel, fileName ); - - /* md3 surfaces become picomodel surfaces */ - surface = (md3Surface_t*) ( bb + md3->ofsSurfaces ); - - /* run through md3 surfaces */ - for ( i = 0; i < md3->numSurfaces; i++ ) - { - /* allocate new pico surface */ - picoSurface = PicoNewSurface( picoModel ); - if ( picoSurface == NULL ) { - _pico_printf( PICO_ERROR, "Unable to allocate a new model surface" ); - PicoFreeModel( picoModel ); /* sea */ - return NULL; - } - - /* md3 model surfaces are all triangle meshes */ - PicoSetSurfaceType( picoSurface, PICO_TRIANGLES ); - - /* set surface name */ - PicoSetSurfaceName( picoSurface, surface->name ); - - /* create new pico shader -sea */ - picoShader = PicoNewShader( picoModel ); - if ( picoShader == NULL ) { - _pico_printf( PICO_ERROR, "Unable to allocate a new model shader" ); - PicoFreeModel( picoModel ); - return NULL; - } - - /* detox and set shader name */ - shader = (md3Shader_t*) ( (picoByte_t*) surface + surface->ofsShaders ); - _pico_setfext( shader->name, "" ); - _pico_unixify( shader->name ); - PicoSetShaderName( picoShader, shader->name ); - - /* associate current surface with newly created shader */ - PicoSetSurfaceShader( picoSurface, picoShader ); - - /* copy indexes */ - triangle = (md3Triangle_t *) ( (picoByte_t*) surface + surface->ofsTriangles ); - - for ( j = 0; j < surface->numTriangles; j++, triangle++ ) - { - PicoSetSurfaceIndex( picoSurface, ( j * 3 + 0 ), (picoIndex_t) triangle->indexes[ 0 ] ); - PicoSetSurfaceIndex( picoSurface, ( j * 3 + 1 ), (picoIndex_t) triangle->indexes[ 1 ] ); - PicoSetSurfaceIndex( picoSurface, ( j * 3 + 2 ), (picoIndex_t) triangle->indexes[ 2 ] ); - } - - /* copy vertexes */ - texCoord = (md3TexCoord_t*) ( (picoByte_t *) surface + surface->ofsSt ); - vertex = (md3Vertex_t*) ( (picoByte_t*) surface + surface->ofsVertexes + surface->numVerts * frameNum * sizeof( md3Vertex_t ) ); - _pico_set_color( color, 255, 255, 255, 255 ); - - for ( j = 0; j < surface->numVerts; j++, texCoord++, vertex++ ) - { - /* set vertex origin */ - xyz[ 0 ] = MD3_SCALE * vertex->xyz[ 0 ]; - xyz[ 1 ] = MD3_SCALE * vertex->xyz[ 1 ]; - xyz[ 2 ] = MD3_SCALE * vertex->xyz[ 2 ]; - PicoSetSurfaceXYZ( picoSurface, j, xyz ); - - /* decode lat/lng normal to 3 float normal */ - lat = (float) ( ( vertex->normal >> 8 ) & 0xff ); - lng = (float) ( vertex->normal & 0xff ); - lat *= PICO_PI / 128; - lng *= PICO_PI / 128; - normal[ 0 ] = (picoVec_t) cos( lat ) * (picoVec_t) sin( lng ); - normal[ 1 ] = (picoVec_t) sin( lat ) * (picoVec_t) sin( lng ); - normal[ 2 ] = (picoVec_t) cos( lng ); - PicoSetSurfaceNormal( picoSurface, j, normal ); - - /* set st coords */ - st[ 0 ] = texCoord->st[ 0 ]; - st[ 1 ] = texCoord->st[ 1 ]; - PicoSetSurfaceST( picoSurface, 0, j, st ); - - /* set color */ - PicoSetSurfaceColor( picoSurface, 0, j, color ); - } - - /* get next surface */ - surface = (md3Surface_t*) ( (picoByte_t*) surface + surface->ofsEnd ); - } - - /* return the new pico model */ - return picoModel; -} - - - -/* pico file format module definition */ -const picoModule_t picoModuleMD3 = -{ - "1.3", /* module version string */ - "Quake 3 Arena", /* module display name */ - "Randy Reddig", /* author's name */ - "2002 Randy Reddig", /* module copyright */ - { - "md3", NULL, NULL, NULL /* default extensions to use */ - }, - _md3_canload, /* validation routine */ - _md3_load, /* load routine */ - NULL, /* save validation routine */ - NULL /* save routine */ -}; diff --git a/tools/urt/libs/picomodel/pm_mdc.c b/tools/urt/libs/picomodel/pm_mdc.c deleted file mode 100644 index 2e4849f..0000000 --- a/tools/urt/libs/picomodel/pm_mdc.c +++ /dev/null @@ -1,744 +0,0 @@ -/* ----------------------------------------------------------------------------- - - PicoModel Library - - Copyright (c) 2002, Randy Reddig & seaw0lf - All rights reserved. - - Redistribution and use in source and binary forms, with or without modification, - are permitted provided that the following conditions are met: - - Redistributions of source code must retain the above copyright notice, this list - of conditions and the following disclaimer. - - Redistributions in binary form must reproduce the above copyright notice, this - list of conditions and the following disclaimer in the documentation and/or - other materials provided with the distribution. - - Neither the names of the copyright holders nor the names of its contributors may - be used to endorse or promote products derived from this software without - specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR - ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - ----------------------------------------------------------------------------- */ - - - -/* marker */ -#define PM_MDC_C - - - -/* dependencies */ -#include "picointernal.h" - -/* mdc model format */ -#define MDC_MAGIC "IDPC" -#define MDC_VERSION 2 - -/* mdc vertex scale */ -#define MDC_SCALE ( 1.0f / 64.0f ) -#define MDC_MAX_OFS 127.0f -#define MDC_DIST_SCALE 0.05f - -/* mdc decoding normal table */ -double mdcNormals[ 256 ][ 3 ] = -{ - { 1.000000, 0.000000, 0.000000 }, - { 0.980785, 0.195090, 0.000000 }, - { 0.923880, 0.382683, 0.000000 }, - { 0.831470, 0.555570, 0.000000 }, - { 0.707107, 0.707107, 0.000000 }, - { 0.555570, 0.831470, 0.000000 }, - { 0.382683, 0.923880, 0.000000 }, - { 0.195090, 0.980785, 0.000000 }, - { -0.000000, 1.000000, 0.000000 }, - { -0.195090, 0.980785, 0.000000 }, - { -0.382683, 0.923880, 0.000000 }, - { -0.555570, 0.831470, 0.000000 }, - { -0.707107, 0.707107, 0.000000 }, - { -0.831470, 0.555570, 0.000000 }, - { -0.923880, 0.382683, 0.000000 }, - { -0.980785, 0.195090, 0.000000 }, - { -1.000000, -0.000000, 0.000000 }, - { -0.980785, -0.195090, 0.000000 }, - { -0.923880, -0.382683, 0.000000 }, - { -0.831470, -0.555570, 0.000000 }, - { -0.707107, -0.707107, 0.000000 }, - { -0.555570, -0.831469, 0.000000 }, - { -0.382684, -0.923880, 0.000000 }, - { -0.195090, -0.980785, 0.000000 }, - { 0.000000, -1.000000, 0.000000 }, - { 0.195090, -0.980785, 0.000000 }, - { 0.382684, -0.923879, 0.000000 }, - { 0.555570, -0.831470, 0.000000 }, - { 0.707107, -0.707107, 0.000000 }, - { 0.831470, -0.555570, 0.000000 }, - { 0.923880, -0.382683, 0.000000 }, - { 0.980785, -0.195090, 0.000000 }, - { 0.980785, 0.000000, -0.195090 }, - { 0.956195, 0.218245, -0.195090 }, - { 0.883657, 0.425547, -0.195090 }, - { 0.766809, 0.611510, -0.195090 }, - { 0.611510, 0.766809, -0.195090 }, - { 0.425547, 0.883657, -0.195090 }, - { 0.218245, 0.956195, -0.195090 }, - { -0.000000, 0.980785, -0.195090 }, - { -0.218245, 0.956195, -0.195090 }, - { -0.425547, 0.883657, -0.195090 }, - { -0.611510, 0.766809, -0.195090 }, - { -0.766809, 0.611510, -0.195090 }, - { -0.883657, 0.425547, -0.195090 }, - { -0.956195, 0.218245, -0.195090 }, - { -0.980785, -0.000000, -0.195090 }, - { -0.956195, -0.218245, -0.195090 }, - { -0.883657, -0.425547, -0.195090 }, - { -0.766809, -0.611510, -0.195090 }, - { -0.611510, -0.766809, -0.195090 }, - { -0.425547, -0.883657, -0.195090 }, - { -0.218245, -0.956195, -0.195090 }, - { 0.000000, -0.980785, -0.195090 }, - { 0.218245, -0.956195, -0.195090 }, - { 0.425547, -0.883657, -0.195090 }, - { 0.611510, -0.766809, -0.195090 }, - { 0.766809, -0.611510, -0.195090 }, - { 0.883657, -0.425547, -0.195090 }, - { 0.956195, -0.218245, -0.195090 }, - { 0.923880, 0.000000, -0.382683 }, - { 0.892399, 0.239118, -0.382683 }, - { 0.800103, 0.461940, -0.382683 }, - { 0.653281, 0.653281, -0.382683 }, - { 0.461940, 0.800103, -0.382683 }, - { 0.239118, 0.892399, -0.382683 }, - { -0.000000, 0.923880, -0.382683 }, - { -0.239118, 0.892399, -0.382683 }, - { -0.461940, 0.800103, -0.382683 }, - { -0.653281, 0.653281, -0.382683 }, - { -0.800103, 0.461940, -0.382683 }, - { -0.892399, 0.239118, -0.382683 }, - { -0.923880, -0.000000, -0.382683 }, - { -0.892399, -0.239118, -0.382683 }, - { -0.800103, -0.461940, -0.382683 }, - { -0.653282, -0.653281, -0.382683 }, - { -0.461940, -0.800103, -0.382683 }, - { -0.239118, -0.892399, -0.382683 }, - { 0.000000, -0.923880, -0.382683 }, - { 0.239118, -0.892399, -0.382683 }, - { 0.461940, -0.800103, -0.382683 }, - { 0.653281, -0.653282, -0.382683 }, - { 0.800103, -0.461940, -0.382683 }, - { 0.892399, -0.239117, -0.382683 }, - { 0.831470, 0.000000, -0.555570 }, - { 0.790775, 0.256938, -0.555570 }, - { 0.672673, 0.488726, -0.555570 }, - { 0.488726, 0.672673, -0.555570 }, - { 0.256938, 0.790775, -0.555570 }, - { -0.000000, 0.831470, -0.555570 }, - { -0.256938, 0.790775, -0.555570 }, - { -0.488726, 0.672673, -0.555570 }, - { -0.672673, 0.488726, -0.555570 }, - { -0.790775, 0.256938, -0.555570 }, - { -0.831470, -0.000000, -0.555570 }, - { -0.790775, -0.256938, -0.555570 }, - { -0.672673, -0.488726, -0.555570 }, - { -0.488725, -0.672673, -0.555570 }, - { -0.256938, -0.790775, -0.555570 }, - { 0.000000, -0.831470, -0.555570 }, - { 0.256938, -0.790775, -0.555570 }, - { 0.488725, -0.672673, -0.555570 }, - { 0.672673, -0.488726, -0.555570 }, - { 0.790775, -0.256938, -0.555570 }, - { 0.707107, 0.000000, -0.707107 }, - { 0.653281, 0.270598, -0.707107 }, - { 0.500000, 0.500000, -0.707107 }, - { 0.270598, 0.653281, -0.707107 }, - { -0.000000, 0.707107, -0.707107 }, - { -0.270598, 0.653282, -0.707107 }, - { -0.500000, 0.500000, -0.707107 }, - { -0.653281, 0.270598, -0.707107 }, - { -0.707107, -0.000000, -0.707107 }, - { -0.653281, -0.270598, -0.707107 }, - { -0.500000, -0.500000, -0.707107 }, - { -0.270598, -0.653281, -0.707107 }, - { 0.000000, -0.707107, -0.707107 }, - { 0.270598, -0.653281, -0.707107 }, - { 0.500000, -0.500000, -0.707107 }, - { 0.653282, -0.270598, -0.707107 }, - { 0.555570, 0.000000, -0.831470 }, - { 0.481138, 0.277785, -0.831470 }, - { 0.277785, 0.481138, -0.831470 }, - { -0.000000, 0.555570, -0.831470 }, - { -0.277785, 0.481138, -0.831470 }, - { -0.481138, 0.277785, -0.831470 }, - { -0.555570, -0.000000, -0.831470 }, - { -0.481138, -0.277785, -0.831470 }, - { -0.277785, -0.481138, -0.831470 }, - { 0.000000, -0.555570, -0.831470 }, - { 0.277785, -0.481138, -0.831470 }, - { 0.481138, -0.277785, -0.831470 }, - { 0.382683, 0.000000, -0.923880 }, - { 0.270598, 0.270598, -0.923880 }, - { -0.000000, 0.382683, -0.923880 }, - { -0.270598, 0.270598, -0.923880 }, - { -0.382683, -0.000000, -0.923880 }, - { -0.270598, -0.270598, -0.923880 }, - { 0.000000, -0.382683, -0.923880 }, - { 0.270598, -0.270598, -0.923880 }, - { 0.195090, 0.000000, -0.980785 }, - { -0.000000, 0.195090, -0.980785 }, - { -0.195090, -0.000000, -0.980785 }, - { 0.000000, -0.195090, -0.980785 }, - { 0.980785, 0.000000, 0.195090 }, - { 0.956195, 0.218245, 0.195090 }, - { 0.883657, 0.425547, 0.195090 }, - { 0.766809, 0.611510, 0.195090 }, - { 0.611510, 0.766809, 0.195090 }, - { 0.425547, 0.883657, 0.195090 }, - { 0.218245, 0.956195, 0.195090 }, - { -0.000000, 0.980785, 0.195090 }, - { -0.218245, 0.956195, 0.195090 }, - { -0.425547, 0.883657, 0.195090 }, - { -0.611510, 0.766809, 0.195090 }, - { -0.766809, 0.611510, 0.195090 }, - { -0.883657, 0.425547, 0.195090 }, - { -0.956195, 0.218245, 0.195090 }, - { -0.980785, -0.000000, 0.195090 }, - { -0.956195, -0.218245, 0.195090 }, - { -0.883657, -0.425547, 0.195090 }, - { -0.766809, -0.611510, 0.195090 }, - { -0.611510, -0.766809, 0.195090 }, - { -0.425547, -0.883657, 0.195090 }, - { -0.218245, -0.956195, 0.195090 }, - { 0.000000, -0.980785, 0.195090 }, - { 0.218245, -0.956195, 0.195090 }, - { 0.425547, -0.883657, 0.195090 }, - { 0.611510, -0.766809, 0.195090 }, - { 0.766809, -0.611510, 0.195090 }, - { 0.883657, -0.425547, 0.195090 }, - { 0.956195, -0.218245, 0.195090 }, - { 0.923880, 0.000000, 0.382683 }, - { 0.892399, 0.239118, 0.382683 }, - { 0.800103, 0.461940, 0.382683 }, - { 0.653281, 0.653281, 0.382683 }, - { 0.461940, 0.800103, 0.382683 }, - { 0.239118, 0.892399, 0.382683 }, - { -0.000000, 0.923880, 0.382683 }, - { -0.239118, 0.892399, 0.382683 }, - { -0.461940, 0.800103, 0.382683 }, - { -0.653281, 0.653281, 0.382683 }, - { -0.800103, 0.461940, 0.382683 }, - { -0.892399, 0.239118, 0.382683 }, - { -0.923880, -0.000000, 0.382683 }, - { -0.892399, -0.239118, 0.382683 }, - { -0.800103, -0.461940, 0.382683 }, - { -0.653282, -0.653281, 0.382683 }, - { -0.461940, -0.800103, 0.382683 }, - { -0.239118, -0.892399, 0.382683 }, - { 0.000000, -0.923880, 0.382683 }, - { 0.239118, -0.892399, 0.382683 }, - { 0.461940, -0.800103, 0.382683 }, - { 0.653281, -0.653282, 0.382683 }, - { 0.800103, -0.461940, 0.382683 }, - { 0.892399, -0.239117, 0.382683 }, - { 0.831470, 0.000000, 0.555570 }, - { 0.790775, 0.256938, 0.555570 }, - { 0.672673, 0.488726, 0.555570 }, - { 0.488726, 0.672673, 0.555570 }, - { 0.256938, 0.790775, 0.555570 }, - { -0.000000, 0.831470, 0.555570 }, - { -0.256938, 0.790775, 0.555570 }, - { -0.488726, 0.672673, 0.555570 }, - { -0.672673, 0.488726, 0.555570 }, - { -0.790775, 0.256938, 0.555570 }, - { -0.831470, -0.000000, 0.555570 }, - { -0.790775, -0.256938, 0.555570 }, - { -0.672673, -0.488726, 0.555570 }, - { -0.488725, -0.672673, 0.555570 }, - { -0.256938, -0.790775, 0.555570 }, - { 0.000000, -0.831470, 0.555570 }, - { 0.256938, -0.790775, 0.555570 }, - { 0.488725, -0.672673, 0.555570 }, - { 0.672673, -0.488726, 0.555570 }, - { 0.790775, -0.256938, 0.555570 }, - { 0.707107, 0.000000, 0.707107 }, - { 0.653281, 0.270598, 0.707107 }, - { 0.500000, 0.500000, 0.707107 }, - { 0.270598, 0.653281, 0.707107 }, - { -0.000000, 0.707107, 0.707107 }, - { -0.270598, 0.653282, 0.707107 }, - { -0.500000, 0.500000, 0.707107 }, - { -0.653281, 0.270598, 0.707107 }, - { -0.707107, -0.000000, 0.707107 }, - { -0.653281, -0.270598, 0.707107 }, - { -0.500000, -0.500000, 0.707107 }, - { -0.270598, -0.653281, 0.707107 }, - { 0.000000, -0.707107, 0.707107 }, - { 0.270598, -0.653281, 0.707107 }, - { 0.500000, -0.500000, 0.707107 }, - { 0.653282, -0.270598, 0.707107 }, - { 0.555570, 0.000000, 0.831470 }, - { 0.481138, 0.277785, 0.831470 }, - { 0.277785, 0.481138, 0.831470 }, - { -0.000000, 0.555570, 0.831470 }, - { -0.277785, 0.481138, 0.831470 }, - { -0.481138, 0.277785, 0.831470 }, - { -0.555570, -0.000000, 0.831470 }, - { -0.481138, -0.277785, 0.831470 }, - { -0.277785, -0.481138, 0.831470 }, - { 0.000000, -0.555570, 0.831470 }, - { 0.277785, -0.481138, 0.831470 }, - { 0.481138, -0.277785, 0.831470 }, - { 0.382683, 0.000000, 0.923880 }, - { 0.270598, 0.270598, 0.923880 }, - { -0.000000, 0.382683, 0.923880 }, - { -0.270598, 0.270598, 0.923880 }, - { -0.382683, -0.000000, 0.923880 }, - { -0.270598, -0.270598, 0.923880 }, - { 0.000000, -0.382683, 0.923880 }, - { 0.270598, -0.270598, 0.923880 }, - { 0.195090, 0.000000, 0.980785 }, - { -0.000000, 0.195090, 0.980785 }, - { -0.195090, -0.000000, 0.980785 }, - { 0.000000, -0.195090, 0.980785 } -}; - -/* mdc model frame information */ -typedef struct mdcFrame_s -{ - float bounds[ 2 ][ 3 ]; - float localOrigin[ 3 ]; - float radius; - char creator[ 16 ]; -} -mdcFrame_t; - -/* mdc model tag information */ -typedef struct mdcTag_s -{ - short xyz[3]; - short angles[3]; -} -mdcTag_t; - -/* mdc surface mdc (one object mesh) */ -typedef struct mdcSurface_s -{ - char magic[ 4 ]; - char name[ 64 ]; /* polyset name */ - int flags; - int numCompFrames; /* all surfaces in a model should have the same */ - int numBaseFrames; /* ditto */ - int numShaders; /* all model surfaces should have the same */ - int numVerts; - int numTriangles; - int ofsTriangles; - int ofsShaders; /* offset from start of mdcSurface_t */ - int ofsSt; /* texture coords are common for all frames */ - int ofsXyzNormals; /* numVerts * numBaseFrames */ - int ofsXyzCompressed; /* numVerts * numCompFrames */ - - int ofsFrameBaseFrames; /* numFrames */ - int ofsFrameCompFrames; /* numFrames */ - int ofsEnd; /* next surface follows */ -} -mdcSurface_t; - -typedef struct mdcShader_s -{ - char name[ 64 ]; - int shaderIndex; /* for ingame use */ -} -mdcShader_t; - -typedef struct mdcTriangle_s -{ - int indexes[ 3 ]; -} -mdcTriangle_t; - -typedef struct mdcTexCoord_s -{ - float st[ 2 ]; -} -mdcTexCoord_t; - -typedef struct mdcVertex_s -{ - short xyz[ 3 ]; - short normal; -} -mdcVertex_t; - -typedef struct mdcXyzCompressed_s -{ - unsigned int ofsVec; /* offset direction from the last base frame */ -} -mdcXyzCompressed_t; - - -/* mdc model file mdc structure */ -typedef struct mdc_s -{ - char magic[ 4 ]; /* MDC_MAGIC */ - int version; - char name[ 64 ]; /* model name */ - int flags; - int numFrames; - int numTags; - int numSurfaces; - int numSkins; /* number of skins for the mesh */ - int ofsFrames; /* offset for first frame */ - int ofsTagNames; /* numTags */ - int ofsTags; /* numFrames * numTags */ - int ofsSurfaces; /* first surface, others follow */ - int ofsEnd; /* end of file */ -} -mdc_t; - - - - -/* - _mdc_canload() - validates a Return to Castle Wolfenstein model file. btw, i use the - preceding underscore cause it's a static func referenced - by one structure only. - */ - -static int _mdc_canload( PM_PARAMS_CANLOAD ){ - mdc_t *mdc; - - - /* to keep the compiler happy */ - *fileName = *fileName; - - /* sanity check */ - if ( bufSize < ( sizeof( *mdc ) * 2 ) ) { - return PICO_PMV_ERROR_SIZE; - } - - /* set as mdc */ - mdc = (mdc_t*) buffer; - - /* check mdc magic */ - if ( *( (int*) mdc->magic ) != *( (int*) MDC_MAGIC ) ) { - return PICO_PMV_ERROR_IDENT; - } - - /* check mdc version */ - if ( _pico_little_long( mdc->version ) != MDC_VERSION ) { - return PICO_PMV_ERROR_VERSION; - } - - /* file seems to be a valid mdc */ - return PICO_PMV_OK; -} - - - -/* - _mdc_load() - loads a Return to Castle Wolfenstein mdc model file. - */ - -static picoModel_t *_mdc_load( PM_PARAMS_LOAD ){ - int i, j; - picoByte_t *bb; - mdc_t *mdc; - mdcSurface_t *surface; - mdcShader_t *shader; - mdcTexCoord_t *texCoord; - mdcFrame_t *frame; - mdcTriangle_t *triangle; - mdcVertex_t *vertex; - mdcXyzCompressed_t *vertexComp; - short *mdcShort, *mdcCompVert; - double lat, lng; - - picoModel_t *picoModel; - picoSurface_t *picoSurface; - picoShader_t *picoShader; - picoVec3_t xyz, normal; - picoVec2_t st; - picoColor_t color; - - - /* ------------------------------------------------- - mdc loading - ------------------------------------------------- */ - - - /* set as mdc */ - bb = (picoByte_t*) buffer; - mdc = (mdc_t*) buffer; - - /* check ident and version */ - if ( *( (int*) mdc->magic ) != *( (int*) MDC_MAGIC ) || _pico_little_long( mdc->version ) != MDC_VERSION ) { - /* not an mdc file (todo: set error) */ - return NULL; - } - - /* swap mdc */ - mdc->version = _pico_little_long( mdc->version ); - mdc->numFrames = _pico_little_long( mdc->numFrames ); - mdc->numTags = _pico_little_long( mdc->numTags ); - mdc->numSurfaces = _pico_little_long( mdc->numSurfaces ); - mdc->numSkins = _pico_little_long( mdc->numSkins ); - mdc->ofsFrames = _pico_little_long( mdc->ofsFrames ); - mdc->ofsTags = _pico_little_long( mdc->ofsTags ); - mdc->ofsTagNames = _pico_little_long( mdc->ofsTagNames ); - mdc->ofsSurfaces = _pico_little_long( mdc->ofsSurfaces ); - mdc->ofsEnd = _pico_little_long( mdc->ofsEnd ); - - /* do frame check */ - if ( mdc->numFrames < 1 ) { - _pico_printf( PICO_ERROR, "MDC with 0 frames" ); - return NULL; - } - - if ( frameNum < 0 || frameNum >= mdc->numFrames ) { - _pico_printf( PICO_ERROR, "Invalid or out-of-range MDC frame specified" ); - return NULL; - } - - /* swap frames */ - frame = (mdcFrame_t*) ( bb + mdc->ofsFrames ); - for ( i = 0; i < mdc->numFrames; i++, frame++ ) - { - frame->radius = _pico_little_float( frame->radius ); - for ( j = 0; j < 3; j++ ) - { - frame->bounds[ 0 ][ j ] = _pico_little_float( frame->bounds[ 0 ][ j ] ); - frame->bounds[ 1 ][ j ] = _pico_little_float( frame->bounds[ 1 ][ j ] ); - frame->localOrigin[ j ] = _pico_little_float( frame->localOrigin[ j ] ); - } - } - - /* swap surfaces */ - surface = (mdcSurface_t*) ( bb + mdc->ofsSurfaces ); - for ( i = 0; i < mdc->numSurfaces; i++ ) - { - /* swap surface mdc */ - surface->flags = _pico_little_long( surface->flags ); - surface->numBaseFrames = _pico_little_long( surface->numBaseFrames ); - surface->numCompFrames = _pico_little_long( surface->numCompFrames ); - surface->numShaders = _pico_little_long( surface->numShaders ); - surface->numTriangles = _pico_little_long( surface->numTriangles ); - surface->ofsTriangles = _pico_little_long( surface->ofsTriangles ); - surface->numVerts = _pico_little_long( surface->numVerts ); - surface->ofsShaders = _pico_little_long( surface->ofsShaders ); - surface->ofsSt = _pico_little_long( surface->ofsSt ); - surface->ofsXyzNormals = _pico_little_long( surface->ofsXyzNormals ); - surface->ofsXyzCompressed = _pico_little_long( surface->ofsXyzCompressed ); - surface->ofsFrameBaseFrames = _pico_little_long( surface->ofsFrameBaseFrames ); - surface->ofsFrameCompFrames = _pico_little_long( surface->ofsFrameCompFrames ); - surface->ofsEnd = _pico_little_long( surface->ofsEnd ); - - /* swap triangles */ - triangle = (mdcTriangle_t*) ( (picoByte_t*) surface + surface->ofsTriangles ); - for ( j = 0; j < surface->numTriangles; j++, triangle++ ) - { - /* sea: swaps fixed */ - triangle->indexes[ 0 ] = _pico_little_long( triangle->indexes[ 0 ] ); - triangle->indexes[ 1 ] = _pico_little_long( triangle->indexes[ 1 ] ); - triangle->indexes[ 2 ] = _pico_little_long( triangle->indexes[ 2 ] ); - } - - /* swap st coords */ - texCoord = (mdcTexCoord_t*) ( (picoByte_t*) surface + surface->ofsSt ); - for ( j = 0; j < surface->numVerts; j++, texCoord++ ) - { - texCoord->st[ 0 ] = _pico_little_float( texCoord->st[ 0 ] ); - texCoord->st[ 1 ] = _pico_little_float( texCoord->st[ 1 ] ); - } - - /* swap xyz/normals */ - vertex = (mdcVertex_t*) ( (picoByte_t*) surface + surface->ofsXyzNormals ); - for ( j = 0; j < ( surface->numVerts * surface->numBaseFrames ); j++, vertex++ ) - { - vertex->xyz[ 0 ] = _pico_little_short( vertex->xyz[ 0 ] ); - vertex->xyz[ 1 ] = _pico_little_short( vertex->xyz[ 1 ] ); - vertex->xyz[ 2 ] = _pico_little_short( vertex->xyz[ 2 ] ); - vertex->normal = _pico_little_short( vertex->normal ); - } - - /* swap xyz/compressed */ - vertexComp = (mdcXyzCompressed_t*) ( (picoByte_t*) surface + surface->ofsXyzCompressed ); - for ( j = 0; j < ( surface->numVerts * surface->numCompFrames ); j++, vertexComp++ ) - { - vertexComp->ofsVec = _pico_little_long( vertexComp->ofsVec ); - } - - /* swap base frames */ - mdcShort = (short *) ( (picoByte_t*) surface + surface->ofsFrameBaseFrames ); - for ( j = 0; j < mdc->numFrames; j++, mdcShort++ ) - { - *mdcShort = _pico_little_short( *mdcShort ); - } - - /* swap compressed frames */ - mdcShort = (short *) ( (picoByte_t*) surface + surface->ofsFrameCompFrames ); - for ( j = 0; j < mdc->numFrames; j++, mdcShort++ ) - { - *mdcShort = _pico_little_short( *mdcShort ); - } - - /* get next surface */ - surface = (mdcSurface_t*) ( (picoByte_t*) surface + surface->ofsEnd ); - } - - /* ------------------------------------------------- - pico model creation - ------------------------------------------------- */ - - /* create new pico model */ - picoModel = PicoNewModel(); - if ( picoModel == NULL ) { - _pico_printf( PICO_ERROR, "Unable to allocate a new model" ); - return NULL; - } - - /* do model setup */ - PicoSetModelFrameNum( picoModel, frameNum ); - PicoSetModelNumFrames( picoModel, mdc->numFrames ); /* sea */ - PicoSetModelName( picoModel, fileName ); - PicoSetModelFileName( picoModel, fileName ); - - /* mdc surfaces become picomodel surfaces */ - surface = (mdcSurface_t*) ( bb + mdc->ofsSurfaces ); - - /* run through mdc surfaces */ - for ( i = 0; i < mdc->numSurfaces; i++ ) - { - /* allocate new pico surface */ - picoSurface = PicoNewSurface( picoModel ); - if ( picoSurface == NULL ) { - _pico_printf( PICO_ERROR, "Unable to allocate a new model surface" ); - PicoFreeModel( picoModel ); /* sea */ - return NULL; - } - - /* mdc model surfaces are all triangle meshes */ - PicoSetSurfaceType( picoSurface, PICO_TRIANGLES ); - - /* set surface name */ - PicoSetSurfaceName( picoSurface, surface->name ); - - /* create new pico shader -sea */ - picoShader = PicoNewShader( picoModel ); - if ( picoShader == NULL ) { - _pico_printf( PICO_ERROR, "Unable to allocate a new model shader" ); - PicoFreeModel( picoModel ); - return NULL; - } - - /* detox and set shader name */ - shader = (mdcShader_t*) ( (picoByte_t*) surface + surface->ofsShaders ); - _pico_setfext( shader->name, "" ); - _pico_unixify( shader->name ); - PicoSetShaderName( picoShader, shader->name ); - - /* associate current surface with newly created shader */ - PicoSetSurfaceShader( picoSurface, picoShader ); - - /* copy indexes */ - triangle = (mdcTriangle_t *) ( (picoByte_t*) surface + surface->ofsTriangles ); - - for ( j = 0; j < surface->numTriangles; j++, triangle++ ) - { - PicoSetSurfaceIndex( picoSurface, ( j * 3 + 0 ), (picoIndex_t) triangle->indexes[ 0 ] ); - PicoSetSurfaceIndex( picoSurface, ( j * 3 + 1 ), (picoIndex_t) triangle->indexes[ 1 ] ); - PicoSetSurfaceIndex( picoSurface, ( j * 3 + 2 ), (picoIndex_t) triangle->indexes[ 2 ] ); - } - - /* copy vertexes */ - texCoord = (mdcTexCoord_t*) ( (picoByte_t *) surface + surface->ofsSt ); - mdcShort = (short *) ( (picoByte_t *) surface + surface->ofsXyzNormals ) + ( (int)*( (short *) ( (picoByte_t *) surface + surface->ofsFrameBaseFrames ) + frameNum ) * surface->numVerts * 4 ); - if ( surface->numCompFrames > 0 ) { - mdcCompVert = (short *) ( (picoByte_t *) surface + surface->ofsFrameCompFrames ) + frameNum; - if ( *mdcCompVert >= 0 ) { - vertexComp = (mdcXyzCompressed_t *) ( (picoByte_t *) surface + surface->ofsXyzCompressed ) + ( *mdcCompVert * surface->numVerts ); - } - } - _pico_set_color( color, 255, 255, 255, 255 ); - - for ( j = 0; j < surface->numVerts; j++, texCoord++, mdcShort += 4 ) - { - /* set vertex origin */ - xyz[ 0 ] = MDC_SCALE * mdcShort[ 0 ]; - xyz[ 1 ] = MDC_SCALE * mdcShort[ 1 ]; - xyz[ 2 ] = MDC_SCALE * mdcShort[ 2 ]; - - /* add compressed ofsVec */ - if ( surface->numCompFrames > 0 && *mdcCompVert >= 0 ) { - xyz[ 0 ] += ( (float) ( ( vertexComp->ofsVec ) & 255 ) - MDC_MAX_OFS ) * MDC_DIST_SCALE; - xyz[ 1 ] += ( (float) ( ( vertexComp->ofsVec >> 8 ) & 255 ) - MDC_MAX_OFS ) * MDC_DIST_SCALE; - xyz[ 2 ] += ( (float) ( ( vertexComp->ofsVec >> 16 ) & 255 ) - MDC_MAX_OFS ) * MDC_DIST_SCALE; - PicoSetSurfaceXYZ( picoSurface, j, xyz ); - - normal[ 0 ] = (float) mdcNormals[ ( vertexComp->ofsVec >> 24 ) ][ 0 ]; - normal[ 1 ] = (float) mdcNormals[ ( vertexComp->ofsVec >> 24 ) ][ 1 ]; - normal[ 2 ] = (float) mdcNormals[ ( vertexComp->ofsVec >> 24 ) ][ 2 ]; - PicoSetSurfaceNormal( picoSurface, j, normal ); - - vertexComp++; - } - else - { - PicoSetSurfaceXYZ( picoSurface, j, xyz ); - - /* decode lat/lng normal to 3 float normal */ - lat = (float) ( ( *( mdcShort + 3 ) >> 8 ) & 0xff ); - lng = (float) ( *( mdcShort + 3 ) & 0xff ); - lat *= PICO_PI / 128; - lng *= PICO_PI / 128; - normal[ 0 ] = (picoVec_t) cos( lat ) * (picoVec_t) sin( lng ); - normal[ 1 ] = (picoVec_t) sin( lat ) * (picoVec_t) sin( lng ); - normal[ 2 ] = (picoVec_t) cos( lng ); - PicoSetSurfaceNormal( picoSurface, j, normal ); - } - - /* set st coords */ - st[ 0 ] = texCoord->st[ 0 ]; - st[ 1 ] = texCoord->st[ 1 ]; - PicoSetSurfaceST( picoSurface, 0, j, st ); - - /* set color */ - PicoSetSurfaceColor( picoSurface, 0, j, color ); - } - - /* get next surface */ - surface = (mdcSurface_t*) ( (picoByte_t*) surface + surface->ofsEnd ); - } - - /* return the new pico model */ - return picoModel; -} - - - -/* pico file format module definition */ -const picoModule_t picoModuleMDC = -{ - "1.3", /* module version string */ - "RtCW MDC", /* module display name */ - "Arnout van Meer", /* author's name */ - "2002 Arnout van Meer", /* module copyright */ - { - "mdc", NULL, NULL, NULL /* default extensions to use */ - }, - _mdc_canload, /* validation routine */ - _mdc_load, /* load routine */ - NULL, /* save validation routine */ - NULL /* save routine */ -}; diff --git a/tools/urt/libs/picomodel/pm_ms3d.c b/tools/urt/libs/picomodel/pm_ms3d.c deleted file mode 100644 index 0c4fc06..0000000 --- a/tools/urt/libs/picomodel/pm_ms3d.c +++ /dev/null @@ -1,497 +0,0 @@ -/* ----------------------------------------------------------------------------- - - PicoModel Library - - Copyright (c) 2002, Randy Reddig & seaw0lf - All rights reserved. - - Redistribution and use in source and binary forms, with or without modification, - are permitted provided that the following conditions are met: - - Redistributions of source code must retain the above copyright notice, this list - of conditions and the following disclaimer. - - Redistributions in binary form must reproduce the above copyright notice, this - list of conditions and the following disclaimer in the documentation and/or - other materials provided with the distribution. - - Neither the names of the copyright holders nor the names of its contributors may - be used to endorse or promote products derived from this software without - specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR - ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - ----------------------------------------------------------------------------- */ - - - -/* marker */ -#define PM_MS3D_C - -/* dependencies */ -#include "picointernal.h" - -/* disable warnings */ -#ifdef WIN32 -#pragma warning( disable:4100 ) /* unref param */ -#endif - -/* remarks: - * - loader seems stable - * todo: - * - fix uv coordinate problem - * - check for buffer overflows ('bufptr' accesses) - */ -/* uncomment when debugging this module */ - #define DEBUG_PM_MS3D - #define DEBUG_PM_MS3D_EX - -/* plain white */ -static picoColor_t white = { 255,255,255,255 }; - -/* ms3d limits */ -#define MS3D_MAX_VERTS 8192 -#define MS3D_MAX_TRIS 16384 -#define MS3D_MAX_GROUPS 128 -#define MS3D_MAX_MATERIALS 128 -#define MS3D_MAX_JOINTS 128 -#define MS3D_MAX_KEYFRAMES 216 - -/* ms3d flags */ -#define MS3D_SELECTED 1 -#define MS3D_HIDDEN 2 -#define MS3D_SELECTED2 4 -#define MS3D_DIRTY 8 - -/* this freaky loader needs byte alignment */ -#pragma pack(push, 1) - -/* ms3d header */ -typedef struct SMsHeader -{ - char magic[10]; - int version; -} -TMsHeader; - -/* ms3d vertex */ -typedef struct SMsVertex -{ - unsigned char flags; /* sel, sel2, or hidden */ - float xyz[3]; - char boneID; /* -1 means 'no bone' */ - unsigned char refCount; -} -TMsVertex; - -/* ms3d triangle */ -typedef struct SMsTriangle -{ - unsigned short flags; /* sel, sel2, or hidden */ - unsigned short vertexIndices[3]; - float vertexNormals[3][3]; - float s[3]; - float t[3]; - unsigned char smoothingGroup; /* 1 - 32 */ - unsigned char groupIndex; -} -TMsTriangle; - -/* ms3d material */ -typedef struct SMsMaterial -{ - char name[32]; - float ambient[4]; - float diffuse[4]; - float specular[4]; - float emissive[4]; - float shininess; /* range 0..128 */ - float transparency; /* range 0..1 */ - unsigned char mode; - char texture [128]; /* texture.bmp */ - char alphamap[128]; /* alpha.bmp */ -} -TMsMaterial; - -// ms3d group (static part) -// followed by a variable size block (see below) -typedef struct SMsGroup -{ - unsigned char flags; // sel, hidden - char name[32]; - unsigned short numTriangles; -/* - unsigned short triangleIndices[ numTriangles ]; - char materialIndex; // -1 means 'no material' - */ -} -TMsGroup; - -// ms3d joint -typedef struct SMsJoint -{ - unsigned char flags; - char name[32]; - char parentName[32]; - float rotation[3]; - float translation[3]; - unsigned short numRotationKeyframes; - unsigned short numTranslationKeyframes; -} -TMsJoint; - -// ms3d keyframe -typedef struct SMsKeyframe -{ - float time; - float parameter[3]; -} -TMsKeyframe; - -/* restore previous data alignment */ -#pragma pack(pop) - -/* _ms3d_canload: - * validates a milkshape3d model file. - */ -static int _ms3d_canload( PM_PARAMS_CANLOAD ){ - TMsHeader *hdr; - - - /* to keep the compiler happy */ - *fileName = *fileName; - - /* sanity check */ - if ( bufSize < sizeof( TMsHeader ) ) { - return PICO_PMV_ERROR_SIZE; - } - - /* get ms3d header */ - hdr = (TMsHeader *)buffer; - - /* check ms3d magic */ - if ( strncmp( hdr->magic,"MS3D000000",10 ) != 0 ) { - return PICO_PMV_ERROR_IDENT; - } - - /* check ms3d version */ - if ( _pico_little_long( hdr->version ) < 3 || - _pico_little_long( hdr->version ) > 4 ) { - _pico_printf( PICO_ERROR,"MS3D file ignored. Only MS3D 1.3 and 1.4 is supported." ); - return PICO_PMV_ERROR_VERSION; - } - /* file seems to be a valid ms3d */ - return PICO_PMV_OK; -} - -static unsigned char *GetWord( unsigned char *bufptr, int *out ){ - if ( bufptr == NULL ) { - return NULL; - } - *out = _pico_little_short( *(unsigned short *)bufptr ); - return( bufptr + 2 ); -} - -/* _ms3d_load: - * loads a milkshape3d model file. - */ -static picoModel_t *_ms3d_load( PM_PARAMS_LOAD ){ - picoModel_t *model; - unsigned char *bufptr; - int shaderRefs[ MS3D_MAX_GROUPS ]; - int numGroups; - int numMaterials; -// unsigned char *ptrToGroups; - int numVerts; - unsigned char *ptrToVerts; - int numTris; - unsigned char *ptrToTris; - int i,k,m; - - /* create new pico model */ - model = PicoNewModel(); - if ( model == NULL ) { - return NULL; - } - - /* do model setup */ - PicoSetModelFrameNum( model, frameNum ); - PicoSetModelName( model, fileName ); - PicoSetModelFileName( model, fileName ); - - /* skip header */ - bufptr = (unsigned char *)buffer + sizeof( TMsHeader ); - - /* get number of vertices */ - bufptr = GetWord( bufptr,&numVerts ); - ptrToVerts = bufptr; - -#ifdef DEBUG_PM_MS3D - printf( "NumVertices: %d\n",numVerts ); -#endif - /* swap verts */ - for ( i = 0; i < numVerts; i++ ) - { - TMsVertex *vertex; - vertex = (TMsVertex *)bufptr; - bufptr += sizeof( TMsVertex ); - - vertex->xyz[ 0 ] = _pico_little_float( vertex->xyz[ 0 ] ); - vertex->xyz[ 1 ] = _pico_little_float( vertex->xyz[ 1 ] ); - vertex->xyz[ 2 ] = _pico_little_float( vertex->xyz[ 2 ] ); - -#ifdef DEBUG_PM_MS3D_EX_ - printf( "Vertex: x: %f y: %f z: %f\n", - msvd[i]->vertex[0], - msvd[i]->vertex[1], - msvd[i]->vertex[2] ); -#endif - } - /* get number of triangles */ - bufptr = GetWord( bufptr,&numTris ); - ptrToTris = bufptr; - -#ifdef DEBUG_PM_MS3D - printf( "NumTriangles: %d\n",numTris ); -#endif - /* swap tris */ - for ( i = 0; i < numTris; i++ ) - { - TMsTriangle *triangle; - triangle = (TMsTriangle *)bufptr; - bufptr += sizeof( TMsTriangle ); - - triangle->flags = _pico_little_short( triangle->flags ); - - /* run through all tri verts */ - for ( k = 0; k < 3; k++ ) - { - /* swap tex coords */ - triangle->s[ k ] = _pico_little_float( triangle->s[ k ] ); - triangle->t[ k ] = _pico_little_float( triangle->t[ k ] ); - - /* swap fields */ - triangle->vertexIndices[ k ] = _pico_little_short( triangle->vertexIndices[ k ] ); - triangle->vertexNormals[ 0 ][ k ] = _pico_little_float( triangle->vertexNormals[ 0 ][ k ] ); - triangle->vertexNormals[ 1 ][ k ] = _pico_little_float( triangle->vertexNormals[ 1 ][ k ] ); - triangle->vertexNormals[ 2 ][ k ] = _pico_little_float( triangle->vertexNormals[ 2 ][ k ] ); - - /* check for out of range indices */ - if ( triangle->vertexIndices[ k ] >= numVerts ) { - _pico_printf( PICO_ERROR,"Vertex %d index %d out of range (%d, max %d)",i,k,triangle->vertexIndices[k],numVerts - 1 ); - PicoFreeModel( model ); - return NULL; /* yuck */ - } - } - } - /* get number of groups */ - bufptr = GetWord( bufptr,&numGroups ); -// ptrToGroups = bufptr; - -#ifdef DEBUG_PM_MS3D - printf( "NumGroups: %d\n",numGroups ); -#endif - /* run through all groups in model */ - for ( i = 0; i < numGroups && i < MS3D_MAX_GROUPS; i++ ) - { - picoSurface_t *surface; - TMsGroup *group; - - group = (TMsGroup *)bufptr; - bufptr += sizeof( TMsGroup ); - - /* we ignore hidden groups */ - if ( group->flags & MS3D_HIDDEN ) { - bufptr += ( group->numTriangles * 2 ) + 1; - continue; - } - /* forced null term of group name */ - group->name[ 31 ] = '\0'; - - /* create new pico surface */ - surface = PicoNewSurface( model ); - if ( surface == NULL ) { - PicoFreeModel( model ); - return NULL; - } - /* do surface setup */ - PicoSetSurfaceType( surface,PICO_TRIANGLES ); - PicoSetSurfaceName( surface,group->name ); - - /* process triangle indices */ - for ( k = 0; k < group->numTriangles; k++ ) - { - TMsTriangle *triangle; - unsigned int triangleIndex; - - /* get triangle index */ - bufptr = GetWord( bufptr,(int *)&triangleIndex ); - - /* get ptr to triangle data */ - triangle = (TMsTriangle *)( ptrToTris + ( sizeof( TMsTriangle ) * triangleIndex ) ); - - /* run through triangle vertices */ - for ( m = 0; m < 3; m++ ) - { - TMsVertex *vertex; - unsigned int vertexIndex; - picoVec2_t texCoord; - - /* get ptr to vertex data */ - vertexIndex = triangle->vertexIndices[ m ]; - vertex = (TMsVertex *)( ptrToVerts + ( sizeof( TMsVertex ) * vertexIndex ) ); - - /* store vertex origin */ - PicoSetSurfaceXYZ( surface,vertexIndex,vertex->xyz ); - - /* store vertex color */ - PicoSetSurfaceColor( surface,0,vertexIndex,white ); - - /* store vertex normal */ - PicoSetSurfaceNormal( surface,vertexIndex,triangle->vertexNormals[ m ] ); - - /* store current face vertex index */ - PicoSetSurfaceIndex( surface,( k * 3 + ( 2 - m ) ),(picoIndex_t)vertexIndex ); - - /* get texture vertex coord */ - texCoord[ 0 ] = triangle->s[ m ]; - texCoord[ 1 ] = -triangle->t[ m ]; /* flip t */ - - /* store texture vertex coord */ - PicoSetSurfaceST( surface,0,vertexIndex,texCoord ); - } - } - /* store material */ - shaderRefs[ i ] = *bufptr++; - -#ifdef DEBUG_PM_MS3D - printf( "Group %d: '%s' (%d tris)\n",i,group->name,group->numTriangles ); -#endif - } - /* get number of materials */ - bufptr = GetWord( bufptr,&numMaterials ); - -#ifdef DEBUG_PM_MS3D - printf( "NumMaterials: %d\n",numMaterials ); -#endif - /* run through all materials in model */ - for ( i = 0; i < numMaterials; i++ ) - { - picoShader_t *shader; - picoColor_t ambient,diffuse,specular; - TMsMaterial *material; - int k; - - material = (TMsMaterial *)bufptr; - bufptr += sizeof( TMsMaterial ); - - /* null term strings */ - material->name [ 31 ] = '\0'; - material->texture [ 127 ] = '\0'; - material->alphamap[ 127 ] = '\0'; - - /* ltrim strings */ - _pico_strltrim( material->name ); - _pico_strltrim( material->texture ); - _pico_strltrim( material->alphamap ); - - /* rtrim strings */ - _pico_strrtrim( material->name ); - _pico_strrtrim( material->texture ); - _pico_strrtrim( material->alphamap ); - - /* create new pico shader */ - shader = PicoNewShader( model ); - if ( shader == NULL ) { - PicoFreeModel( model ); - return NULL; - } - /* scale shader colors */ - for ( k = 0; k < 4; k++ ) - { - ambient [ k ] = (picoByte_t) ( material->ambient[ k ] * 255 ); - diffuse [ k ] = (picoByte_t) ( material->diffuse[ k ] * 255 ); - specular[ k ] = (picoByte_t) ( material->specular[ k ] * 255 ); - } - /* set shader colors */ - PicoSetShaderAmbientColor( shader,ambient ); - PicoSetShaderDiffuseColor( shader,diffuse ); - PicoSetShaderSpecularColor( shader,specular ); - - /* set shader transparency */ - PicoSetShaderTransparency( shader,material->transparency ); - - /* set shader shininess (0..127) */ - PicoSetShaderShininess( shader,material->shininess ); - - /* set shader name */ - PicoSetShaderName( shader,material->name ); - - /* set shader texture map name */ - PicoSetShaderMapName( shader,material->texture ); - -#ifdef DEBUG_PM_MS3D - printf( "Material %d: '%s' ('%s','%s')\n",i,material->name,material->texture,material->alphamap ); -#endif - } - /* assign shaders to surfaces */ - for ( i = 0; i < numGroups && i < MS3D_MAX_GROUPS; i++ ) - { - picoSurface_t *surface; - picoShader_t *shader; - - /* sanity check */ - if ( shaderRefs[ i ] >= MS3D_MAX_MATERIALS || - shaderRefs[ i ] < 0 ) { - continue; - } - - /* get surface */ - surface = PicoGetModelSurface( model,i ); - if ( surface == NULL ) { - continue; - } - - /* get shader */ - shader = PicoGetModelShader( model,shaderRefs[ i ] ); - if ( shader == NULL ) { - continue; - } - - /* assign shader */ - PicoSetSurfaceShader( surface,shader ); - -#ifdef DEBUG_PM_MS3D - printf( "Mapped: %d ('%s') to %d (%s)\n", - shaderRefs[i],shader->name,i,surface->name ); -#endif - } - /* return allocated pico model */ - return model; -// return NULL; -} - -/* pico file format module definition */ -const picoModule_t picoModuleMS3D = -{ - "0.4-a", /* module version string */ - "Milkshape 3D", /* module display name */ - "seaw0lf", /* author's name */ - "2002 seaw0lf", /* module copyright */ - { - "ms3d",NULL,NULL,NULL /* default extensions to use */ - }, - _ms3d_canload, /* validation routine */ - _ms3d_load, /* load routine */ - NULL, /* save validation routine */ - NULL /* save routine */ -}; diff --git a/tools/urt/libs/picomodel/pm_obj.c b/tools/urt/libs/picomodel/pm_obj.c deleted file mode 100644 index 81ffe07..0000000 --- a/tools/urt/libs/picomodel/pm_obj.c +++ /dev/null @@ -1,886 +0,0 @@ -/* ----------------------------------------------------------------------------- - - PicoModel Library - - Copyright (c) 2002, Randy Reddig & seaw0lf - All rights reserved. - - Redistribution and use in source and binary forms, with or without modification, - are permitted provided that the following conditions are met: - - Redistributions of source code must retain the above copyright notice, this list - of conditions and the following disclaimer. - - Redistributions in binary form must reproduce the above copyright notice, this - list of conditions and the following disclaimer in the documentation and/or - other materials provided with the distribution. - - Neither the names of the copyright holders nor the names of its contributors may - be used to endorse or promote products derived from this software without - specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR - ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - ----------------------------------------------------------------------------- */ - - - -/* marker */ -#define PM_OBJ_C - -/* dependencies */ -#include "picointernal.h" - -/* disable warnings */ -#ifdef WIN32 -#pragma warning( disable:4100 ) /* unref param */ -#endif - -/* todo: - * - '_obj_load' code crashes in a weird way after - * '_obj_mtl_load' for a few .mtl files - * - process 'mtllib' rather than using .mtl - * - handle 'usemtl' statements - */ -/* uncomment when debugging this module */ -/* #define DEBUG_PM_OBJ */ -/* #define DEBUG_PM_OBJ_EX */ - -/* this holds temporary vertex data read by parser */ -typedef struct SObjVertexData -{ - picoVec3_t v; /* geometric vertices */ - picoVec2_t vt; /* texture vertices */ - picoVec3_t vn; /* vertex normals (optional) */ -} -TObjVertexData; - -/* _obj_canload: - * validates a wavefront obj model file. - */ -static int _obj_canload( PM_PARAMS_CANLOAD ){ - picoParser_t *p; - - /* check data length */ - if ( bufSize < 30 ) { - return PICO_PMV_ERROR_SIZE; - } - - /* first check file extension. we have to do this for objs */ - /* cause there is no good way to identify the contents */ - if ( _pico_stristr( fileName,".obj" ) != NULL || - _pico_stristr( fileName,".wf" ) != NULL ) { - return PICO_PMV_OK; - } - /* if the extension check failed we parse through the first */ - /* few lines in file and look for common keywords often */ - /* appearing at the beginning of wavefront objects */ - - /* alllocate a new pico parser */ - p = _pico_new_parser( (picoByte_t *)buffer,bufSize ); - if ( p == NULL ) { - return PICO_PMV_ERROR_MEMORY; - } - - /* parse obj head line by line for type check */ - while ( 1 ) - { - /* get first token on line */ - if ( _pico_parse_first( p ) == NULL ) { - break; - } - - /* we only parse the first few lines, say 80 */ - if ( p->curLine > 80 ) { - break; - } - - /* skip empty lines */ - if ( p->token == NULL || !strlen( p->token ) ) { - continue; - } - - /* material library keywords are teh good */ - if ( !_pico_stricmp( p->token,"usemtl" ) || - !_pico_stricmp( p->token,"mtllib" ) || - !_pico_stricmp( p->token,"g" ) || - !_pico_stricmp( p->token,"v" ) ) { /* v,g bit fishy, but uh... */ - /* free the pico parser thing */ - _pico_free_parser( p ); - - /* seems to be a valid wavefront obj */ - return PICO_PMV_OK; - } - /* skip rest of line */ - _pico_parse_skip_rest( p ); - } - /* free the pico parser thing */ - _pico_free_parser( p ); - - /* doesn't really look like an obj to us */ - return PICO_PMV_ERROR; -} - -/* SizeObjVertexData: - * This pretty piece of 'alloc ahead' code dynamically - * allocates - and reallocates as soon as required - - * my vertex data array in even steps. - */ -#define SIZE_OBJ_STEP 4096 - -static TObjVertexData *SizeObjVertexData( - TObjVertexData *vertexData, int reqEntries, - int *entries, int *allocated ){ - int newAllocated; - - /* sanity checks */ - if ( reqEntries < 1 ) { - return NULL; - } - if ( entries == NULL || allocated == NULL ) { - return NULL; /* must have */ - - } - /* no need to grow yet */ - if ( vertexData && ( reqEntries < *allocated ) ) { - *entries = reqEntries; - return vertexData; - } - /* given vertex data ptr not allocated yet */ - if ( vertexData == NULL ) { - /* how many entries to allocate */ - newAllocated = ( reqEntries > SIZE_OBJ_STEP ) ? - reqEntries : SIZE_OBJ_STEP; - - /* throw out an extended debug message */ -#ifdef DEBUG_PM_OBJ_EX - printf( "SizeObjVertexData: allocate (%d entries)\n", - newAllocated ); -#endif - /* first time allocation */ - vertexData = (TObjVertexData *) - _pico_alloc( sizeof( TObjVertexData ) * newAllocated ); - - /* allocation failed */ - if ( vertexData == NULL ) { - return NULL; - } - - /* allocation succeeded */ - *allocated = newAllocated; - *entries = reqEntries; - return vertexData; - } - /* given vertex data ptr needs to be resized */ - if ( reqEntries == *allocated ) { - newAllocated = ( *allocated + SIZE_OBJ_STEP ); - - /* throw out an extended debug message */ -#ifdef DEBUG_PM_OBJ_EX - printf( "SizeObjVertexData: reallocate (%d entries)\n", - newAllocated ); -#endif - /* try to reallocate */ - vertexData = (TObjVertexData *) - _pico_realloc( (void *)&vertexData, - sizeof( TObjVertexData ) * ( *allocated ), - sizeof( TObjVertexData ) * ( newAllocated ) ); - - /* reallocation failed */ - if ( vertexData == NULL ) { - return NULL; - } - - /* reallocation succeeded */ - *allocated = newAllocated; - *entries = reqEntries; - return vertexData; - } - /* we're b0rked when we reach this */ - return NULL; -} - -static void FreeObjVertexData( TObjVertexData *vertexData ){ - if ( vertexData != NULL ) { - free( (TObjVertexData *)vertexData ); - } -} - -static int _obj_mtl_load( picoModel_t *model ){ - picoShader_t *curShader = NULL; - picoParser_t *p; - picoByte_t *mtlBuffer; - int mtlBufSize; - char *fileName; - - /* sanity checks */ - if ( model == NULL || model->fileName == NULL ) { - return 0; - } - - /* skip if we have a zero length model file name */ - if ( !strlen( model->fileName ) ) { - return 0; - } - - /* helper */ - #define _obj_mtl_error_return \ - { \ - _pico_free_parser( p ); \ - _pico_free_file( mtlBuffer ); \ - _pico_free( fileName ); \ - return 0; \ - } - /* alloc copy of model file name */ - fileName = _pico_clone_alloc( model->fileName ); - if ( fileName == NULL ) { - return 0; - } - - /* change extension of model file to .mtl */ - _pico_setfext( fileName, "mtl" ); - - /* load .mtl file contents */ - _pico_load_file( fileName,&mtlBuffer,&mtlBufSize ); - - /* check result */ - if ( mtlBufSize == 0 ) { - return 1; /* file is empty: no error */ - } - if ( mtlBufSize < 0 ) { - return 0; /* load failed: error */ - - } - /* create a new pico parser */ - p = _pico_new_parser( mtlBuffer, mtlBufSize ); - if ( p == NULL ) { - _obj_mtl_error_return; - } - - /* doo teh .mtl parse */ - while ( 1 ) - { - /* get next token in material file */ - if ( _pico_parse( p,1 ) == NULL ) { - break; - } -#if 0 - - /* skip empty lines */ - if ( p->token == NULL || !strlen( p->token ) ) { - continue; - } - - /* skip comment lines */ - if ( p->token[0] == '#' ) { - _pico_parse_skip_rest( p ); - continue; - } - /* new material */ - if ( !_pico_stricmp( p->token,"newmtl" ) ) { - picoShader_t *shader; - char *name; - - /* get material name */ - name = _pico_parse( p,0 ); - - /* validate material name */ - if ( name == NULL || !strlen( name ) ) { - _pico_printf( PICO_ERROR,"Missing material name in MTL, line %d.",p->curLine ); - _obj_mtl_error_return; - } - /* create a new pico shader */ - shader = PicoNewShader( model ); - if ( shader == NULL ) { - _obj_mtl_error_return; - } - - /* set shader name */ - PicoSetShaderName( shader,name ); - - /* assign pointer to current shader */ - curShader = shader; - } - /* diffuse map name */ - else if ( !_pico_stricmp( p->token,"map_kd" ) ) { - char *mapName; - - /* pointer to current shader must be valid */ - if ( curShader == NULL ) { - _obj_mtl_error_return; - } - - /* get material's diffuse map name */ - mapName = _pico_parse( p,0 ); - - /* validate map name */ - if ( mapName == NULL || !strlen( mapName ) ) { - _pico_printf( PICO_ERROR,"Missing material map name in MTL, line %d.",p->curLine ); - _obj_mtl_error_return; - } - /* set shader map name */ - PicoSetShaderMapName( shader,mapName ); - } - /* dissolve factor (pseudo transparency 0..1) */ - /* where 0 means 100% transparent and 1 means opaque */ - else if ( !_pico_stricmp( p->token,"d" ) ) { - picoByte_t *diffuse; - float value; - - - /* get dissolve factor */ - if ( !_pico_parse_float( p,&value ) ) { - _obj_mtl_error_return; - } - - /* set shader transparency */ - PicoSetShaderTransparency( curShader,value ); - - /* get shader's diffuse color */ - diffuse = PicoGetShaderDiffuseColor( curShader ); - - /* set diffuse alpha to transparency */ - diffuse[ 3 ] = (picoByte_t)( value * 255.0 ); - - /* set shader's new diffuse color */ - PicoSetShaderDiffuseColor( curShader,diffuse ); - } - /* shininess (phong specular component) */ - else if ( !_pico_stricmp( p->token,"ns" ) ) { - /* remark: - * - well, this is some major obj spec fuckup once again. some - * apps store this in 0..1 range, others use 0..100 range, - * even others use 0..2048 range, and again others use the - * range 0..128, some even use 0..1000, 0..200, 400..700, - * honestly, what's up with the 3d app coders? happens when - * you smoke too much weed i guess. -sea - */ - float value; - - /* pointer to current shader must be valid */ - if ( curShader == NULL ) { - _obj_mtl_error_return; - } - - /* get totally screwed up shininess (a random value in fact ;) */ - if ( !_pico_parse_float( p,&value ) ) { - _obj_mtl_error_return; - } - - /* okay, there is no way to set this correctly, so we simply */ - /* try to guess a few ranges (most common ones i have seen) */ - - /* assume 0..2048 range */ - if ( value > 1000 ) { - value = 128.0 * ( value / 2048.0 ); - } - /* assume 0..1000 range */ - else if ( value > 200 ) { - value = 128.0 * ( value / 1000.0 ); - } - /* assume 0..200 range */ - else if ( value > 100 ) { - value = 128.0 * ( value / 200.0 ); - } - /* assume 0..100 range */ - else if ( value > 1 ) { - value = 128.0 * ( value / 100.0 ); - } - /* assume 0..1 range */ - else { - value *= 128.0; - } - /* negative shininess is bad (yes, i have seen it...) */ - if ( value < 0.0 ) { - value = 0.0; - } - - /* set the pico shininess value in range 0..127 */ - /* geez, .obj is such a mess... */ - PicoSetShaderShininess( curShader,value ); - } - /* kol0r ambient (wut teh fuk does "ka" stand for?) */ - else if ( !_pico_stricmp( p->token,"ka" ) ) { - picoColor_t color; - picoVec3_t v; - - /* pointer to current shader must be valid */ - if ( curShader == NULL ) { - _obj_mtl_error_return; - } - - /* get color vector */ - if ( !_pico_parse_vec( p,v ) ) { - _obj_mtl_error_return; - } - - /* scale to byte range */ - color[ 0 ] = (picoByte_t)( v[ 0 ] * 255 ); - color[ 1 ] = (picoByte_t)( v[ 1 ] * 255 ); - color[ 2 ] = (picoByte_t)( v[ 2 ] * 255 ); - color[ 3 ] = (picoByte_t)( 255 ); - - /* set ambient color */ - PicoSetShaderAmbientColor( curShader,color ); - } - /* kol0r diffuse */ - else if ( !_pico_stricmp( p->token,"kd" ) ) { - picoColor_t color; - picoVec3_t v; - - /* pointer to current shader must be valid */ - if ( curShader == NULL ) { - _obj_mtl_error_return; - } - - /* get color vector */ - if ( !_pico_parse_vec( p,v ) ) { - _obj_mtl_error_return; - } - - /* scale to byte range */ - color[ 0 ] = (picoByte_t)( v[ 0 ] * 255 ); - color[ 1 ] = (picoByte_t)( v[ 1 ] * 255 ); - color[ 2 ] = (picoByte_t)( v[ 2 ] * 255 ); - color[ 3 ] = (picoByte_t)( 255 ); - - /* set diffuse color */ - PicoSetShaderDiffuseColor( curShader,color ); - } - /* kol0r specular */ - else if ( !_pico_stricmp( p->token,"ks" ) ) { - picoColor_t color; - picoVec3_t v; - - /* pointer to current shader must be valid */ - if ( curShader == NULL ) { - _obj_mtl_error_return; - } - - /* get color vector */ - if ( !_pico_parse_vec( p,v ) ) { - _obj_mtl_error_return; - } - - /* scale to byte range */ - color[ 0 ] = (picoByte_t)( v[ 0 ] * 255 ); - color[ 1 ] = (picoByte_t)( v[ 1 ] * 255 ); - color[ 2 ] = (picoByte_t)( v[ 2 ] * 255 ); - color[ 3 ] = (picoByte_t)( 255 ); - - /* set specular color */ - PicoSetShaderSpecularColor( curShader,color ); - } -#endif - /* skip rest of line */ - _pico_parse_skip_rest( p ); - } - - /* free parser, file buffer, and file name */ - _pico_free_parser( p ); - _pico_free_file( mtlBuffer ); - _pico_free( fileName ); - - /* return with success */ - return 1; -} - -/* _obj_load: - * loads a wavefront obj model file. - */ -static picoModel_t *_obj_load( PM_PARAMS_LOAD ){ - TObjVertexData *vertexData = NULL; - picoModel_t *model; - picoSurface_t *curSurface = NULL; - picoParser_t *p; - int allocated; - int entries; - int numVerts = 0; - int numNormals = 0; - int numUVs = 0; - int curVertex = 0; - int curFace = 0; - - /* helper */ - #define _obj_error_return( m ) \ - { \ - _pico_printf( PICO_ERROR,"%s in OBJ, line %d.",m,p->curLine ); \ - _pico_free_parser( p ); \ - FreeObjVertexData( vertexData ); \ - PicoFreeModel( model ); \ - return NULL; \ - } - /* alllocate a new pico parser */ - p = _pico_new_parser( (picoByte_t *)buffer,bufSize ); - if ( p == NULL ) { - return NULL; - } - - /* create a new pico model */ - model = PicoNewModel(); - if ( model == NULL ) { - _pico_free_parser( p ); - return NULL; - } - /* do model setup */ - PicoSetModelFrameNum( model,frameNum ); - PicoSetModelName( model,fileName ); - PicoSetModelFileName( model,fileName ); - - /* try loading the materials; we don't handle the result */ -#if 0 - _obj_mtl_load( model ); -#endif - - /* parse obj line by line */ - while ( 1 ) - { - /* get first token on line */ - if ( _pico_parse_first( p ) == NULL ) { - break; - } - - /* skip empty lines */ - if ( p->token == NULL || !strlen( p->token ) ) { - continue; - } - - /* skip comment lines */ - if ( p->token[0] == '#' ) { - _pico_parse_skip_rest( p ); - continue; - } - /* vertex */ - if ( !_pico_stricmp( p->token,"v" ) ) { - TObjVertexData *data; - picoVec3_t v; - - vertexData = SizeObjVertexData( vertexData,numVerts + 1,&entries,&allocated ); - if ( vertexData == NULL ) { - _obj_error_return( "Realloc of vertex data failed (1)" ); - } - - data = &vertexData[ numVerts++ ]; - - /* get and copy vertex */ - if ( !_pico_parse_vec( p,v ) ) { - _obj_error_return( "Vertex parse error" ); - } - - _pico_copy_vec( v,data->v ); - -#ifdef DEBUG_PM_OBJ_EX - printf( "Vertex: x: %f y: %f z: %f\n",v[0],v[1],v[2] ); -#endif - } - /* uv coord */ - else if ( !_pico_stricmp( p->token,"vt" ) ) { - TObjVertexData *data; - picoVec2_t coord; - - vertexData = SizeObjVertexData( vertexData,numUVs + 1,&entries,&allocated ); - if ( vertexData == NULL ) { - _obj_error_return( "Realloc of vertex data failed (2)" ); - } - - data = &vertexData[ numUVs++ ]; - - /* get and copy tex coord */ - if ( !_pico_parse_vec2( p,coord ) ) { - _obj_error_return( "UV coord parse error" ); - } - - _pico_copy_vec2( coord,data->vt ); - -#ifdef DEBUG_PM_OBJ_EX - printf( "TexCoord: u: %f v: %f\n",coord[0],coord[1] ); -#endif - } - /* vertex normal */ - else if ( !_pico_stricmp( p->token,"vn" ) ) { - TObjVertexData *data; - picoVec3_t n; - - vertexData = SizeObjVertexData( vertexData,numNormals + 1,&entries,&allocated ); - if ( vertexData == NULL ) { - _obj_error_return( "Realloc of vertex data failed (3)" ); - } - - data = &vertexData[ numNormals++ ]; - - /* get and copy vertex normal */ - if ( !_pico_parse_vec( p,n ) ) { - _obj_error_return( "Vertex normal parse error" ); - } - - _pico_copy_vec( n,data->vn ); - -#ifdef DEBUG_PM_OBJ_EX - printf( "Normal: x: %f y: %f z: %f\n",n[0],n[1],n[2] ); -#endif - } - /* new group (for us this means a new surface) */ - else if ( !_pico_stricmp( p->token,"g" ) ) { - picoSurface_t *newSurface; - char *groupName; - - /* get first group name (ignore 2nd,3rd,etc.) */ - groupName = _pico_parse( p,0 ); - if ( groupName == NULL || !strlen( groupName ) ) { - /* some obj exporters feel like they don't need to */ - /* supply a group name. so we gotta handle it here */ -#if 1 - strcpy( p->token,"default" ); - groupName = p->token; -#else - _obj_error_return( "Invalid or missing group name" ); -#endif - } - /* allocate a pico surface */ - newSurface = PicoNewSurface( model ); - if ( newSurface == NULL ) { - _obj_error_return( "Error allocating surface" ); - } - - /* reset face index for surface */ - curFace = 0; - - /* set ptr to current surface */ - curSurface = newSurface; - - /* we use triangle meshes */ - PicoSetSurfaceType( newSurface,PICO_TRIANGLES ); - - /* set surface name */ - PicoSetSurfaceName( newSurface,groupName ); - -#ifdef DEBUG_PM_OBJ_EX - printf( "Group: '%s'\n",groupName ); -#endif - } - /* face (oh jesus, hopefully this will do the job right ;) */ - else if ( !_pico_stricmp( p->token,"f" ) ) { - /* okay, this is a mess. some 3d apps seem to try being unique, */ - /* hello cinema4d & 3d exploration, feel good today?, and save */ - /* this crap in tons of different formats. gah, those screwed */ - /* coders. tho the wavefront obj standard defines exactly two */ - /* ways of storing face information. so, i really won't support */ - /* such stupid extravaganza here! */ - - picoVec3_t verts [ 4 ]; - picoVec3_t normals[ 4 ]; - picoVec2_t coords [ 4 ]; - - int iv [ 4 ], has_v; - int ivt[ 4 ], has_vt = 0; - int ivn[ 4 ], has_vn = 0; - int have_quad = 0; - int slashcount; - int doubleslash; - int i; - - /* group defs *must* come before faces */ - if ( curSurface == NULL ) { - _obj_error_return( "No group defined for faces" ); - } - -#ifdef DEBUG_PM_OBJ_EX - printf( "Face: " ); -#endif - /* read vertex/uv/normal indices for the first three face */ - /* vertices (cause we only support triangles) into 'i*[]' */ - /* store the actual vertex/uv/normal data in three arrays */ - /* called 'verts','coords' and 'normals'. */ - for ( i = 0; i < 4; i++ ) - { - char *str; - - /* get next vertex index string (different */ - /* formats are handled below) */ - str = _pico_parse( p,0 ); - if ( str == NULL ) { - /* just break for quads */ - if ( i == 3 ) { - break; - } - - /* error otherwise */ - _obj_error_return( "Face parse error" ); - } - /* if this is the fourth index string we're */ - /* parsing we assume that we have a quad */ - if ( i == 3 ) { - have_quad = 1; - } - - /* get slash count once */ - if ( i == 0 ) { - slashcount = _pico_strchcount( str,'/' ); - doubleslash = strstr( str,"//" ) != NULL; - } - /* handle format 'v//vn' */ - if ( doubleslash && ( slashcount == 2 ) ) { - has_v = has_vn = 1; - sscanf( str,"%d//%d",&iv[ i ],&ivn[ i ] ); - } - /* handle format 'v/vt/vn' */ - else if ( !doubleslash && ( slashcount == 2 ) ) { - has_v = has_vt = has_vn = 1; - sscanf( str,"%d/%d/%d",&iv[ i ],&ivt[ i ],&ivn[ i ] ); - } - /* handle format 'v/vt' (non-standard fuckage) */ - else if ( !doubleslash && ( slashcount == 1 ) ) { - has_v = has_vt = 1; - sscanf( str,"%d/%d",&iv[ i ],&ivt[ i ] ); - } - /* else assume face format 'v' */ - /* (must have been invented by some bored granny) */ - else { - /* get single vertex index */ - has_v = 1; - iv[ i ] = atoi( str ); - - /* either invalid face format or out of range */ - if ( iv[ i ] == 0 ) { - _obj_error_return( "Invalid face format" ); - } - } - /* fix useless back references */ - /* todo: check if this works as it is supposed to */ - - /* assign new indices */ - if ( iv [ i ] < 0 ) { - iv [ i ] = ( numVerts - iv [ i ] ); - } - if ( ivt[ i ] < 0 ) { - ivt[ i ] = ( numUVs - ivt[ i ] ); - } - if ( ivn[ i ] < 0 ) { - ivn[ i ] = ( numNormals - ivn[ i ] ); - } - - /* validate indices */ - /* - commented out. index range checks will trigger - if (iv [ i ] < 1) iv [ i ] = 1; - if (ivt[ i ] < 1) ivt[ i ] = 1; - if (ivn[ i ] < 1) ivn[ i ] = 1; - */ - /* set vertex origin */ - if ( has_v ) { - /* check vertex index range */ - if ( iv[ i ] < 1 || iv[ i ] > numVerts ) { - _obj_error_return( "Vertex index out of range" ); - } - - /* get vertex data */ - verts[ i ][ 0 ] = vertexData[ iv[ i ] - 1 ].v[ 0 ]; - verts[ i ][ 1 ] = vertexData[ iv[ i ] - 1 ].v[ 1 ]; - verts[ i ][ 2 ] = vertexData[ iv[ i ] - 1 ].v[ 2 ]; - } - /* set vertex normal */ - if ( has_vn ) { - /* check normal index range */ - if ( ivn[ i ] < 1 || ivn[ i ] > numNormals ) { - _obj_error_return( "Normal index out of range" ); - } - - /* get normal data */ - normals[ i ][ 0 ] = vertexData[ ivn[ i ] - 1 ].vn[ 0 ]; - normals[ i ][ 1 ] = vertexData[ ivn[ i ] - 1 ].vn[ 1 ]; - normals[ i ][ 2 ] = vertexData[ ivn[ i ] - 1 ].vn[ 2 ]; - } - /* set texture coordinate */ - if ( has_vt ) { - /* check uv index range */ - if ( ivt[ i ] < 1 || ivt[ i ] > numUVs ) { - _obj_error_return( "UV coord index out of range" ); - } - - /* get uv coord data */ - coords[ i ][ 0 ] = vertexData[ ivt[ i ] - 1 ].vt[ 0 ]; - coords[ i ][ 1 ] = vertexData[ ivt[ i ] - 1 ].vt[ 1 ]; - coords[ i ][ 1 ] = -coords[ i ][ 1 ]; - } -#ifdef DEBUG_PM_OBJ_EX - printf( "(%4d",iv[ i ] ); - if ( has_vt ) { - printf( " %4d",ivt[ i ] ); - } - if ( has_vn ) { - printf( " %4d",ivn[ i ] ); - } - printf( ") " ); -#endif - } -#ifdef DEBUG_PM_OBJ_EX - printf( "\n" ); -#endif - /* now that we have extracted all the indices and have */ - /* read the actual data we need to assign all the crap */ - /* to our current pico surface */ - if ( has_v ) { - int max = 3; - if ( have_quad ) { - max = 4; - } - - /* assign all surface information */ - for ( i = 0; i < max; i++ ) - { - /*if( has_v )*/ PicoSetSurfaceXYZ( curSurface, ( curVertex + i ), verts [ i ] ); - /*if( has_vt )*/ PicoSetSurfaceST( curSurface,0,( curVertex + i ), coords [ i ] ); - /*if( has_vn )*/ PicoSetSurfaceNormal( curSurface, ( curVertex + i ), normals[ i ] ); - } - /* add our triangle (A B C) */ - PicoSetSurfaceIndex( curSurface,( curFace * 3 + 2 ),(picoIndex_t)( curVertex + 0 ) ); - PicoSetSurfaceIndex( curSurface,( curFace * 3 + 1 ),(picoIndex_t)( curVertex + 1 ) ); - PicoSetSurfaceIndex( curSurface,( curFace * 3 + 0 ),(picoIndex_t)( curVertex + 2 ) ); - curFace++; - - /* if we don't have a simple triangle, but a quad... */ - if ( have_quad ) { - /* we have to add another triangle (2nd half of quad which is A C D) */ - PicoSetSurfaceIndex( curSurface,( curFace * 3 + 2 ),(picoIndex_t)( curVertex + 0 ) ); - PicoSetSurfaceIndex( curSurface,( curFace * 3 + 1 ),(picoIndex_t)( curVertex + 2 ) ); - PicoSetSurfaceIndex( curSurface,( curFace * 3 + 0 ),(picoIndex_t)( curVertex + 3 ) ); - curFace++; - } - /* increase vertex count */ - curVertex += max; - } - } - /* skip unparsed rest of line and continue */ - _pico_parse_skip_rest( p ); - } - /* free memory used by temporary vertexdata */ - FreeObjVertexData( vertexData ); - - /* return allocated pico model */ - return model; -// return NULL; -} - -/* pico file format module definition */ -const picoModule_t picoModuleOBJ = -{ - "0.6-b", /* module version string */ - "Wavefront ASCII", /* module display name */ - "seaw0lf", /* author's name */ - "2002 seaw0lf", /* module copyright */ - { - "obj",NULL,NULL,NULL /* default extensions to use */ - }, - _obj_canload, /* validation routine */ - _obj_load, /* load routine */ - NULL, /* save validation routine */ - NULL /* save routine */ -}; diff --git a/tools/urt/libs/picomodel/pm_terrain.c b/tools/urt/libs/picomodel/pm_terrain.c deleted file mode 100644 index 4b8affc..0000000 --- a/tools/urt/libs/picomodel/pm_terrain.c +++ /dev/null @@ -1,607 +0,0 @@ -/* ----------------------------------------------------------------------------- - - PicoModel Library - - Copyright (c) 2003, Randy Reddig & seaw0lf - All rights reserved. - - Redistribution and use in source and binary forms, with or without modification, - are permitted provided that the following conditions are met: - - Redistributions of source code must retain the above copyright notice, this list - of conditions and the following disclaimer. - - Redistributions in binary form must reproduce the above copyright notice, this - list of conditions and the following disclaimer in the documentation and/or - other materials provided with the distribution. - - Neither the names of the copyright holders nor the names of its contributors may - be used to endorse or promote products derived from this software without - specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR - ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - ----------------------------------------------------------------------------- */ - - - -/* marker */ -#define PM_TERRAIN_C - - - -/* dependencies */ -#include "picointernal.h" - - - -typedef struct tga_s -{ - unsigned char id_length, colormap_type, image_type; - unsigned short colormap_index, colormap_length; - unsigned char colormap_size; - unsigned short x_origin, y_origin, width, height; - unsigned char pixel_size, attributes; -} -tga_t; - - - -/* - _terrain_load_tga_buffer() - loads a tga image into a newly allocated image buffer - fixme: replace/clean this function - */ - -void _terrain_load_tga_buffer( unsigned char *buffer, unsigned char **pic, int *width, int *height ){ - int row, column; - int columns, rows, numPixels; - unsigned char *pixbuf; - unsigned char *buf_p; - tga_t targa_header; - unsigned char *targa_rgba; - - - *pic = NULL; - - if ( buffer == NULL ) { - return; - } - - buf_p = buffer; - - targa_header.id_length = *buf_p++; - targa_header.colormap_type = *buf_p++; - targa_header.image_type = *buf_p++; - - targa_header.colormap_index = _pico_little_short( *(short*)buf_p ); - buf_p += 2; - targa_header.colormap_length = _pico_little_short( *(short*) buf_p ); - buf_p += 2; - targa_header.colormap_size = *buf_p++; - targa_header.x_origin = _pico_little_short( *(short*) buf_p ); - buf_p += 2; - targa_header.y_origin = _pico_little_short( *(short*) buf_p ); - buf_p += 2; - targa_header.width = _pico_little_short( *(short*) buf_p ); - buf_p += 2; - targa_header.height = _pico_little_short( *(short*) buf_p ); - buf_p += 2; - targa_header.pixel_size = *buf_p++; - targa_header.attributes = *buf_p++; - - if ( targa_header.image_type != 2 && targa_header.image_type != 10 && targa_header.image_type != 3 ) { - _pico_printf( PICO_ERROR, "Only type 2 (RGB), 3 (gray), and 10 (RGB) TGA images supported\n" ); - pic = NULL; - return; - } - - if ( targa_header.colormap_type != 0 ) { - _pico_printf( PICO_ERROR, "Indexed color TGA images not supported\n" ); - return; - } - - if ( targa_header.pixel_size != 32 && targa_header.pixel_size != 24 && targa_header.image_type != 3 ) { - _pico_printf( PICO_ERROR, "Only 32 or 24 bit TGA images supported (not indexed color)\n" ); - pic = NULL; - return; - } - - columns = targa_header.width; - rows = targa_header.height; - numPixels = columns * rows; - - if ( width ) { - *width = columns; - } - if ( height ) { - *height = rows; - } - - targa_rgba = _pico_alloc( numPixels * 4 ); - *pic = targa_rgba; - - if ( targa_header.id_length != 0 ) { - buf_p += targa_header.id_length; // skip TARGA image comment - - } - if ( targa_header.image_type == 2 || targa_header.image_type == 3 ) { - // Uncompressed RGB or gray scale image - for ( row = rows - 1; row >= 0; row-- ) - { - pixbuf = targa_rgba + row * columns * 4; - for ( column = 0; column < columns; column++ ) - { - unsigned char red,green,blue,alphabyte; - switch ( targa_header.pixel_size ) - { - - case 8: - blue = *buf_p++; - green = blue; - red = blue; - *pixbuf++ = red; - *pixbuf++ = green; - *pixbuf++ = blue; - *pixbuf++ = 255; - break; - - case 24: - blue = *buf_p++; - green = *buf_p++; - red = *buf_p++; - *pixbuf++ = red; - *pixbuf++ = green; - *pixbuf++ = blue; - *pixbuf++ = 255; - break; - case 32: - blue = *buf_p++; - green = *buf_p++; - red = *buf_p++; - alphabyte = *buf_p++; - *pixbuf++ = red; - *pixbuf++ = green; - *pixbuf++ = blue; - *pixbuf++ = alphabyte; - break; - default: - break; - } - } - } - } - - /* rle encoded pixels */ - else if ( targa_header.image_type == 10 ) { - unsigned char red,green,blue,alphabyte,packetHeader,packetSize,j; - - red = 0; - green = 0; - blue = 0; - alphabyte = 0xff; - - for ( row = rows - 1; row >= 0; row-- ) { - pixbuf = targa_rgba + row * columns * 4; - for ( column = 0; column < columns; ) { - packetHeader = *buf_p++; - packetSize = 1 + ( packetHeader & 0x7f ); - if ( packetHeader & 0x80 ) { // run-length packet - switch ( targa_header.pixel_size ) { - case 24: - blue = *buf_p++; - green = *buf_p++; - red = *buf_p++; - alphabyte = 255; - break; - case 32: - blue = *buf_p++; - green = *buf_p++; - red = *buf_p++; - alphabyte = *buf_p++; - break; - default: - //Error("LoadTGA: illegal pixel_size '%d' in file '%s'\n", targa_header.pixel_size, name ); - break; - } - - for ( j = 0; j < packetSize; j++ ) { - *pixbuf++ = red; - *pixbuf++ = green; - *pixbuf++ = blue; - *pixbuf++ = alphabyte; - column++; - if ( column == columns ) { // run spans across rows - column = 0; - if ( row > 0 ) { - row--; - } - else{ - goto breakOut; - } - pixbuf = targa_rgba + row * columns * 4; - } - } - } - else { // non run-length packet - for ( j = 0; j < packetSize; j++ ) { - switch ( targa_header.pixel_size ) { - case 24: - blue = *buf_p++; - green = *buf_p++; - red = *buf_p++; - *pixbuf++ = red; - *pixbuf++ = green; - *pixbuf++ = blue; - *pixbuf++ = 255; - break; - case 32: - blue = *buf_p++; - green = *buf_p++; - red = *buf_p++; - alphabyte = *buf_p++; - *pixbuf++ = red; - *pixbuf++ = green; - *pixbuf++ = blue; - *pixbuf++ = alphabyte; - break; - default: - //Sysprintf("LoadTGA: illegal pixel_size '%d' in file '%s'\n", targa_header.pixel_size, name ); - break; - } - column++; - if ( column == columns ) { // pixel packet run spans across rows - column = 0; - if ( row > 0 ) { - row--; - } - else{ - goto breakOut; - } - pixbuf = targa_rgba + row * columns * 4; - } - } - } - } -breakOut:; - } - } - - /* fix vertically flipped image */ - if ( ( targa_header.attributes & ( 1 << 5 ) ) ) { - int flip; - for ( row = 0; row < .5f * rows; row++ ) - { - for ( column = 0; column < columns; column++ ) - { - flip = *( (int*)targa_rgba + row * columns + column ); - *( (int*)targa_rgba + row * columns + column ) = *( (int*)targa_rgba + ( ( rows - 1 ) - row ) * columns + column ); - *( (int*)targa_rgba + ( ( rows - 1 ) - row ) * columns + column ) = flip; - } - } - } -} - - - -/* - _terrain_canload() - validates a picoterrain file - */ - -static int _terrain_canload( PM_PARAMS_CANLOAD ){ - picoParser_t *p; - - - /* keep the friggin compiler happy */ - *fileName = *fileName; - - /* create pico parser */ - p = _pico_new_parser( (picoByte_t*) buffer, bufSize ); - if ( p == NULL ) { - return PICO_PMV_ERROR_MEMORY; - } - - /* get first token */ - if ( _pico_parse_first( p ) == NULL ) { - return PICO_PMV_ERROR_IDENT; - } - - /* check first token */ - if ( _pico_stricmp( p->token, "picoterrain" ) ) { - _pico_free_parser( p ); - return PICO_PMV_ERROR_IDENT; - } - - /* free the pico parser object */ - _pico_free_parser( p ); - - /* file seems to be a valid picoterrain file */ - return PICO_PMV_OK; -} - - - -/* - _terrain_load() - loads a picoterrain file - */ - -static picoModel_t *_terrain_load( PM_PARAMS_LOAD ){ - int i, j, v, pw[ 5 ], r; - picoParser_t *p; - - char *shader, *heightmapFile, *colormapFile; - picoVec3_t scale, origin; - - unsigned char *imageBuffer; - int imageBufSize, w, h, cw, ch; - unsigned char *heightmap, *colormap, *heightPixel, *colorPixel; - - picoModel_t *picoModel; - picoSurface_t *picoSurface; - picoShader_t *picoShader; - picoVec3_t xyz, normal; - picoVec2_t st; - picoColor_t color; - - - /* keep the friggin compiler happy */ - *fileName = *fileName; - - /* create pico parser */ - p = _pico_new_parser( (picoByte_t*) buffer, bufSize ); - if ( p == NULL ) { - return NULL; - } - - /* get first token */ - if ( _pico_parse_first( p ) == NULL ) { - return NULL; - } - - /* check first token */ - if ( _pico_stricmp( p->token, "picoterrain" ) ) { - _pico_printf( PICO_ERROR, "Invalid PicoTerrain model" ); - _pico_free_parser( p ); - return NULL; - } - - /* setup */ - shader = heightmapFile = colormapFile = NULL; - _pico_set_vec( scale, 512, 512, 32 ); - - /* parse ase model file */ - while ( 1 ) - { - /* get first token on line */ - if ( !_pico_parse_first( p ) ) { - break; - } - - /* skip empty lines */ - if ( !p->token || !p->token[ 0 ] ) { - continue; - } - - /* shader */ - if ( !_pico_stricmp( p->token, "shader" ) ) { - if ( _pico_parse( p, 0 ) && p->token[ 0 ] ) { - if ( shader != NULL ) { - _pico_free( shader ); - } - shader = _pico_clone_alloc( p->token ); - } - } - - /* heightmap */ - else if ( !_pico_stricmp( p->token, "heightmap" ) ) { - if ( _pico_parse( p, 0 ) && p->token[ 0 ] ) { - if ( heightmapFile != NULL ) { - _pico_free( heightmapFile ); - } - heightmapFile = _pico_clone_alloc( p->token ); - } - } - - /* colormap */ - else if ( !_pico_stricmp( p->token, "colormap" ) ) { - if ( _pico_parse( p, 0 ) && p->token[ 0 ] ) { - if ( colormapFile != NULL ) { - _pico_free( colormapFile ); - } - colormapFile = _pico_clone_alloc( p->token ); - } - } - - /* scale */ - else if ( !_pico_stricmp( p->token, "scale" ) ) { - _pico_parse_vec( p, scale ); - } - - /* skip unparsed rest of line and continue */ - _pico_parse_skip_rest( p ); - } - - /* ----------------------------------------------------------------- */ - - /* load heightmap */ - heightmap = imageBuffer = NULL; - _pico_load_file( heightmapFile, &imageBuffer, &imageBufSize ); - _terrain_load_tga_buffer( imageBuffer, &heightmap, &w, &h ); - _pico_free( heightmapFile ); - _pico_free_file( imageBuffer ); - - if ( heightmap == NULL || w < 2 || h < 2 ) { - _pico_printf( PICO_ERROR, "PicoTerrain model with invalid heightmap" ); - if ( shader != NULL ) { - _pico_free( shader ); - } - if ( colormapFile != NULL ) { - _pico_free( colormapFile ); - } - _pico_free_parser( p ); - return NULL; - } - - /* set origin (bottom lowest corner of terrain mesh) */ - _pico_set_vec( origin, ( w / -2 ) * scale[ 0 ], ( h / -2 ) * scale[ 1 ], -128 * scale[ 2 ] ); - - /* load colormap */ - colormap = imageBuffer = NULL; - _pico_load_file( colormapFile, &imageBuffer, &imageBufSize ); - _terrain_load_tga_buffer( imageBuffer, &colormap, &cw, &ch ); - _pico_free( colormapFile ); - _pico_free_file( imageBuffer ); - - if ( cw != w || ch != h ) { - _pico_printf( PICO_WARNING, "PicoTerrain colormap/heightmap size mismatch" ); - _pico_free( colormap ); - colormap = NULL; - } - - /* ----------------------------------------------------------------- */ - - /* create new pico model */ - picoModel = PicoNewModel(); - if ( picoModel == NULL ) { - _pico_printf( PICO_ERROR, "Unable to allocate a new model" ); - return NULL; - } - - /* do model setup */ - PicoSetModelFrameNum( picoModel, frameNum ); - PicoSetModelNumFrames( picoModel, 1 ); /* sea */ - PicoSetModelName( picoModel, fileName ); - PicoSetModelFileName( picoModel, fileName ); - - /* allocate new pico surface */ - picoSurface = PicoNewSurface( picoModel ); - if ( picoSurface == NULL ) { - _pico_printf( PICO_ERROR, "Unable to allocate a new model surface" ); - PicoFreeModel( picoModel ); /* sea */ - return NULL; - } - - /* terrain surfaces are triangle meshes */ - PicoSetSurfaceType( picoSurface, PICO_TRIANGLES ); - - /* set surface name */ - PicoSetSurfaceName( picoSurface, "picoterrain" ); - - /* create new pico shader */ - picoShader = PicoNewShader( picoModel ); - if ( picoShader == NULL ) { - _pico_printf( PICO_ERROR, "Unable to allocate a new model shader" ); - PicoFreeModel( picoModel ); - _pico_free( shader ); - return NULL; - } - - /* detox and set shader name */ - _pico_setfext( shader, "" ); - _pico_unixify( shader ); - PicoSetShaderName( picoShader, shader ); - _pico_free( shader ); - - /* associate current surface with newly created shader */ - PicoSetSurfaceShader( picoSurface, picoShader ); - - /* make bogus normal */ - _pico_set_vec( normal, 0.0f, 0.0f, 0.0f ); - - /* create mesh */ - for ( j = 0; j < h; j++ ) - { - for ( i = 0; i < w; i++ ) - { - /* get pointers */ - v = i + ( j * w ); - heightPixel = heightmap + v * 4; - colorPixel = colormap - ? colormap + v * 4 - : NULL; - - /* set xyz */ - _pico_set_vec( xyz, origin[ 0 ] + scale[ 0 ] * i, - origin[ 1 ] + scale[ 1 ] * j, - origin[ 2 ] + scale[ 2 ] * heightPixel[ 0 ] ); - PicoSetSurfaceXYZ( picoSurface, v, xyz ); - - /* set normal */ - PicoSetSurfaceNormal( picoSurface, v, normal ); - - /* set st */ - st[ 0 ] = (float) i; - st[ 1 ] = (float) j; - PicoSetSurfaceST( picoSurface, 0, v, st ); - - /* set color */ - if ( colorPixel != NULL ) { - _pico_set_color( color, colorPixel[ 0 ], colorPixel[ 1 ], colorPixel[ 2 ], colorPixel[ 3 ] ); - } - else{ - _pico_set_color( color, 255, 255, 255, 255 ); - } - PicoSetSurfaceColor( picoSurface, 0, v, color ); - - /* set triangles (zero alpha in heightmap suppresses this quad) */ - if ( i < ( w - 1 ) && j < ( h - 1 ) && heightPixel[ 3 ] >= 128 ) { - /* set indexes */ - pw[ 0 ] = i + ( j * w ); - pw[ 1 ] = i + ( ( j + 1 ) * w ); - pw[ 2 ] = i + 1 + ( ( j + 1 ) * w ); - pw[ 3 ] = i + 1 + ( j * w ); - pw[ 4 ] = i + ( j * w ); /* same as pw[ 0 ] */ - - /* set radix */ - r = ( i + j ) & 1; - - /* make first triangle */ - PicoSetSurfaceIndex( picoSurface, ( v * 6 + 0 ), (picoIndex_t) pw[ r + 0 ] ); - PicoSetSurfaceIndex( picoSurface, ( v * 6 + 1 ), (picoIndex_t) pw[ r + 1 ] ); - PicoSetSurfaceIndex( picoSurface, ( v * 6 + 2 ), (picoIndex_t) pw[ r + 2 ] ); - - /* make second triangle */ - PicoSetSurfaceIndex( picoSurface, ( v * 6 + 3 ), (picoIndex_t) pw[ r + 0 ] ); - PicoSetSurfaceIndex( picoSurface, ( v * 6 + 4 ), (picoIndex_t) pw[ r + 2 ] ); - PicoSetSurfaceIndex( picoSurface, ( v * 6 + 5 ), (picoIndex_t) pw[ r + 3 ] ); - } - } - } - - /* free stuff */ - _pico_free_parser( p ); - _pico_free( heightmap ); - _pico_free( colormap ); - - /* return the new pico model */ - return picoModel; -} - - - -/* pico file format module definition */ -const picoModule_t picoModuleTerrain = -{ - "1.3", /* module version string */ - "PicoTerrain", /* module display name */ - "Randy Reddig", /* author's name */ - "2003 Randy Reddig", /* module copyright */ - { - "picoterrain", NULL, NULL, NULL /* default extensions to use */ - }, - _terrain_canload, /* validation routine */ - _terrain_load, /* load routine */ - NULL, /* save validation routine */ - NULL /* save routine */ -}; diff --git a/tools/urt/libs/pivot.cpp b/tools/urt/libs/pivot.cpp deleted file mode 100644 index 730d6be..0000000 --- a/tools/urt/libs/pivot.cpp +++ /dev/null @@ -1,2 +0,0 @@ - -#include "pivot.h" diff --git a/tools/urt/libs/pivot.h b/tools/urt/libs/pivot.h deleted file mode 100644 index 3f6d85b..0000000 --- a/tools/urt/libs/pivot.h +++ /dev/null @@ -1,268 +0,0 @@ - -#if !defined( INCLUDED_PIVOT_H ) -#define INCLUDED_PIVOT_H - -#include "math/matrix.h" - - -inline Vector3 vector4_projected( const Vector4& vector4 ){ - return vector3_scaled( vector4_to_vector3( vector4 ), 1.0 / vector4[3] ); -} - -inline void billboard_viewplaneOriented( Matrix4& rotation, const Matrix4& world2screen ){ -#if 1 - rotation = g_matrix4_identity; - Vector3 x( vector3_normalised( vector4_to_vector3( world2screen.x() ) ) ); - Vector3 y( vector3_normalised( vector4_to_vector3( world2screen.y() ) ) ); - Vector3 z( vector3_normalised( vector4_to_vector3( world2screen.z() ) ) ); - vector4_to_vector3( rotation.y() ) = Vector3( x.y(), y.y(), z.y() ); - vector4_to_vector3( rotation.z() ) = vector3_negated( Vector3( x.z(), y.z(), z.z() ) ); - vector4_to_vector3( rotation.x() ) = vector3_normalised( vector3_cross( vector4_to_vector3( rotation.y() ), vector4_to_vector3( rotation.z() ) ) ); - vector4_to_vector3( rotation.y() ) = vector3_cross( vector4_to_vector3( rotation.z() ), vector4_to_vector3( rotation.x() ) ); -#else - Matrix4 screen2world( matrix4_full_inverse( world2screen ) ); - - Vector3 near_( - vector4_projected( - matrix4_transformed_vector4( - screen2world, - Vector4( 0, 0, -1, 1 ) - ) - ) - ); - - Vector3 far_( - vector4_projected( - matrix4_transformed_vector4( - screen2world, - Vector4( 0, 0, 1, 1 ) - ) - ) - ); - - Vector3 up( - vector4_projected( - matrix4_transformed_vector4( - screen2world, - Vector4( 0, 1, -1, 1 ) - ) - ) - ); - - rotation = g_matrix4_identity; - vector4_to_vector3( rotation.y() ) = vector3_normalised( vector3_subtracted( up, near_ ) ); - vector4_to_vector3( rotation.z() ) = vector3_normalised( vector3_subtracted( near_, far_ ) ); - vector4_to_vector3( rotation.x() ) = vector3_normalised( vector3_cross( vector4_to_vector3( rotation.y() ), vector4_to_vector3( rotation.z() ) ) ); - vector4_to_vector3( rotation.y() ) = vector3_cross( vector4_to_vector3( rotation.z() ), vector4_to_vector3( rotation.x() ) ); -#endif -} - -inline void billboard_viewpointOriented( Matrix4& rotation, const Matrix4& world2screen ){ - Matrix4 screen2world( matrix4_full_inverse( world2screen ) ); - -#if 1 - rotation = g_matrix4_identity; - vector4_to_vector3( rotation.y() ) = vector3_normalised( vector4_to_vector3( screen2world.y() ) ); - vector4_to_vector3( rotation.z() ) = vector3_negated( vector3_normalised( vector4_to_vector3( screen2world.z() ) ) ); - vector4_to_vector3( rotation.x() ) = vector3_normalised( vector3_cross( vector4_to_vector3( rotation.y() ), vector4_to_vector3( rotation.z() ) ) ); - vector4_to_vector3( rotation.y() ) = vector3_cross( vector4_to_vector3( rotation.z() ), vector4_to_vector3( rotation.x() ) ); -#else - Vector3 near_( - vector4_projected( - matrix4_transformed_vector4( - screen2world, - Vector4( world2screen[12] / world2screen[15], world2screen[13] / world2screen[15], -1, 1 ) - ) - ) - ); - - Vector3 far_( - vector4_projected( - matrix4_transformed_vector4( - screen2world, - Vector4( world2screen[12] / world2screen[15], world2screen[13] / world2screen[15], 1, 1 ) - ) - ) - ); - - Vector3 up( - vector4_projected( - matrix4_transformed_vector4( - screen2world, - Vector4( world2screen[12] / world2screen[15], world2screen[13] / world2screen[15] + 1, -1, 1 ) - ) - ) - ); - - rotation = g_matrix4_identity; - vector4_to_vector3( rotation.y() ) = vector3_normalised( vector3_subtracted( up, near_ ) ); - vector4_to_vector3( rotation.z() ) = vector3_normalised( vector3_subtracted( near_, far_ ) ); - vector4_to_vector3( rotation.x() ) = vector3_normalised( vector3_cross( vector4_to_vector3( rotation.y() ), vector4_to_vector3( rotation.z() ) ) ); - vector4_to_vector3( rotation.y() ) = vector3_cross( vector4_to_vector3( rotation.z() ), vector4_to_vector3( rotation.x() ) ); -#endif -} - - -inline void ConstructObject2Screen( Matrix4& object2screen, const Matrix4& object2world, const Matrix4& world2view, const Matrix4& view2device, const Matrix4& device2screen ){ - object2screen = device2screen; - matrix4_multiply_by_matrix4( object2screen, view2device ); - matrix4_multiply_by_matrix4( object2screen, world2view ); - matrix4_multiply_by_matrix4( object2screen, object2world ); -} - -inline void ConstructObject2Device( Matrix4& object2screen, const Matrix4& object2world, const Matrix4& world2view, const Matrix4& view2device ){ - object2screen = view2device; - matrix4_multiply_by_matrix4( object2screen, world2view ); - matrix4_multiply_by_matrix4( object2screen, object2world ); -} - -inline void ConstructDevice2Object( Matrix4& device2object, const Matrix4& object2world, const Matrix4& world2view, const Matrix4& view2device ){ - ConstructObject2Device( device2object, object2world, world2view, view2device ); - matrix4_full_invert( device2object ); -} - -//! S = ( Inverse(Object2Screen *post ScaleOf(Object2Screen) ) *post Object2Screen -inline void pivot_scale( Matrix4& scale, const Matrix4& pivot2screen ){ - Matrix4 pre_scale( g_matrix4_identity ); - pre_scale[0] = static_cast( vector3_length( vector4_to_vector3( pivot2screen.x() ) ) ); - pre_scale[5] = static_cast( vector3_length( vector4_to_vector3( pivot2screen.y() ) ) ); - pre_scale[10] = static_cast( vector3_length( vector4_to_vector3( pivot2screen.z() ) ) ); - - scale = pivot2screen; - matrix4_multiply_by_matrix4( scale, pre_scale ); - matrix4_full_invert( scale ); - matrix4_multiply_by_matrix4( scale, pivot2screen ); -} - -// scale by (inverse) W -inline void pivot_perspective( Matrix4& scale, const Matrix4& pivot2screen ){ - scale = g_matrix4_identity; - scale[0] = scale[5] = scale[10] = pivot2screen[15]; -} - -inline void ConstructDevice2Manip( Matrix4& device2manip, const Matrix4& object2world, const Matrix4& world2view, const Matrix4& view2device, const Matrix4& device2screen ){ - Matrix4 pivot2screen; - ConstructObject2Screen( pivot2screen, object2world, world2view, view2device, device2screen ); - - ConstructObject2Device( device2manip, object2world, world2view, view2device ); - - Matrix4 scale; - pivot_scale( scale, pivot2screen ); - matrix4_multiply_by_matrix4( device2manip, scale ); - pivot_perspective( scale, pivot2screen ); - matrix4_multiply_by_matrix4( device2manip, scale ); - - matrix4_full_invert( device2manip ); -} - -inline void Pivot2World_worldSpace( Matrix4& manip2world, const Matrix4& pivot2world, const Matrix4& modelview, const Matrix4& projection, const Matrix4& viewport ){ - manip2world = pivot2world; - - Matrix4 pivot2screen; - ConstructObject2Screen( pivot2screen, pivot2world, modelview, projection, viewport ); - - Matrix4 scale; - pivot_scale( scale, pivot2screen ); - matrix4_multiply_by_matrix4( manip2world, scale ); - pivot_perspective( scale, pivot2screen ); - matrix4_multiply_by_matrix4( manip2world, scale ); -} - -inline void Pivot2World_viewpointSpace( Matrix4& manip2world, Vector3& axis, const Matrix4& pivot2world, const Matrix4& modelview, const Matrix4& projection, const Matrix4& viewport ){ - manip2world = pivot2world; - - Matrix4 pivot2screen; - ConstructObject2Screen( pivot2screen, pivot2world, modelview, projection, viewport ); - - Matrix4 scale; - pivot_scale( scale, pivot2screen ); - matrix4_multiply_by_matrix4( manip2world, scale ); - - billboard_viewpointOriented( scale, pivot2screen ); - axis = vector4_to_vector3( scale.z() ); - matrix4_multiply_by_matrix4( manip2world, scale ); - - pivot_perspective( scale, pivot2screen ); - matrix4_multiply_by_matrix4( manip2world, scale ); -} - -inline void Pivot2World_viewplaneSpace( Matrix4& manip2world, const Matrix4& pivot2world, const Matrix4& modelview, const Matrix4& projection, const Matrix4& viewport ){ - manip2world = pivot2world; - - Matrix4 pivot2screen; - ConstructObject2Screen( pivot2screen, pivot2world, modelview, projection, viewport ); - - Matrix4 scale; - pivot_scale( scale, pivot2screen ); - matrix4_multiply_by_matrix4( manip2world, scale ); - - billboard_viewplaneOriented( scale, pivot2screen ); - matrix4_multiply_by_matrix4( manip2world, scale ); - - pivot_perspective( scale, pivot2screen ); - matrix4_multiply_by_matrix4( manip2world, scale ); -} - - -#include "renderable.h" -#include "cullable.h" -#include "render.h" - -const Colour4b g_colour_x( 255, 0, 0, 255 ); -const Colour4b g_colour_y( 0, 255, 0, 255 ); -const Colour4b g_colour_z( 0, 0, 255, 255 ); - -class Shader; - -class RenderablePivot : public OpenGLRenderable -{ -VertexBuffer m_vertices; -public: -mutable Matrix4 m_localToWorld; -typedef Static StaticShader; -static Shader* getShader(){ - return StaticShader::instance(); -} - -RenderablePivot(){ - m_vertices.reserve( 6 ); - - m_vertices.push_back( PointVertex( Vertex3f( 0, 0, 0 ), g_colour_x ) ); - m_vertices.push_back( PointVertex( Vertex3f( 16, 0, 0 ), g_colour_x ) ); - - m_vertices.push_back( PointVertex( Vertex3f( 0, 0, 0 ), g_colour_y ) ); - m_vertices.push_back( PointVertex( Vertex3f( 0, 16, 0 ), g_colour_y ) ); - - m_vertices.push_back( PointVertex( Vertex3f( 0, 0, 0 ), g_colour_z ) ); - m_vertices.push_back( PointVertex( Vertex3f( 0, 0, 16 ), g_colour_z ) ); -} - -void render( RenderStateFlags state ) const { - if ( m_vertices.size() == 0 ) { - return; - } - if ( m_vertices.data() == 0 ) { - return; - } - glVertexPointer( 3, GL_FLOAT, sizeof( PointVertex ), &m_vertices.data()->vertex ); - glColorPointer( 4, GL_UNSIGNED_BYTE, sizeof( PointVertex ), &m_vertices.data()->colour ); - glDrawArrays( GL_LINES, 0, m_vertices.size() ); -} - -void render( Renderer& renderer, const VolumeTest& volume, const Matrix4& localToWorld ) const { - renderer.PushState(); - - Pivot2World_worldSpace( m_localToWorld, localToWorld, volume.GetModelview(), volume.GetProjection(), volume.GetViewport() ); - - renderer.Highlight( Renderer::ePrimitive, false ); - renderer.SetState( getShader(), Renderer::eWireframeOnly ); - renderer.SetState( getShader(), Renderer::eFullMaterials ); - renderer.addRenderable( *this, m_localToWorld ); - - renderer.PopState(); -} -}; - - - -#endif diff --git a/tools/urt/libs/profile/file.cpp b/tools/urt/libs/profile/file.cpp deleted file mode 100644 index ec23096..0000000 --- a/tools/urt/libs/profile/file.cpp +++ /dev/null @@ -1,376 +0,0 @@ -/* - Copyright (c) 2001, Loki software, inc. - All rights reserved. - - Redistribution and use in source and binary forms, with or without modification, - are permitted provided that the following conditions are met: - - Redistributions of source code must retain the above copyright notice, this list - of conditions and the following disclaimer. - - Redistributions in binary form must reproduce the above copyright notice, this - list of conditions and the following disclaimer in the documentation and/or - other materials provided with the distribution. - - Neither the name of Loki software nor the names of its contributors may be used - to endorse or promote products derived from this software without specific prior - written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' - AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY - DIRECT,INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -// -// File class, can be a memory file or a regular disk file. -// Originally from LeoCAD, used with permission from the author. :) -// -// Leonardo Zide (leo@lokigames.com) -// - -#include "file.h" - -#include -#include -#include -#include - -///////////////////////////////////////////////////////////////////////////// -// File construction/destruction - -MemStream::MemStream(){ - m_nGrowBytes = 1024; - m_nPosition = 0; - m_nBufferSize = 0; - m_nFileSize = 0; - m_pBuffer = NULL; - m_bAutoDelete = true; -} - -MemStream::MemStream( size_type nLen ){ - m_nGrowBytes = 1024; - m_nPosition = 0; - m_nBufferSize = 0; - m_nFileSize = 0; - m_pBuffer = NULL; - m_bAutoDelete = true; - - GrowFile( nLen ); -} - -FileStream::FileStream(){ - m_hFile = NULL; - m_bCloseOnDelete = false; -} - -MemStream::~MemStream(){ - if ( m_pBuffer ) { - Close(); - } - - m_nGrowBytes = 0; - m_nPosition = 0; - m_nBufferSize = 0; - m_nFileSize = 0; -} - -FileStream::~FileStream(){ - if ( m_hFile != NULL && m_bCloseOnDelete ) { - Close(); - } -} - -///////////////////////////////////////////////////////////////////////////// -// File operations - -char* MemStream::ReadString( char* pBuf, size_type nMax ){ - int nRead = 0; - unsigned char ch; - - if ( nMax <= 0 ) { - return NULL; - } - if ( m_nPosition >= m_nFileSize ) { - return NULL; - } - - while ( ( --nMax ) ) - { - if ( m_nPosition == m_nFileSize ) { - break; - } - - ch = m_pBuffer[m_nPosition]; - m_nPosition++; - pBuf[nRead++] = ch; - - if ( ch == '\n' ) { - break; - } - } - - pBuf[nRead] = '\0'; - return pBuf; -} - -char* FileStream::ReadString( char* pBuf, size_type nMax ){ - return fgets( pBuf, static_cast( nMax ), m_hFile ); -} - -MemStream::size_type MemStream::read( byte_type* buffer, size_type length ){ - if ( length == 0 ) { - return 0; - } - - if ( m_nPosition > m_nFileSize ) { - return 0; - } - - size_type nRead; - if ( m_nPosition + length > m_nFileSize ) { - nRead = m_nFileSize - m_nPosition; - } - else{ - nRead = length; - } - - memcpy( (unsigned char*)buffer, (unsigned char*)m_pBuffer + m_nPosition, nRead ); - m_nPosition += nRead; - - return nRead; -} - -FileStream::size_type FileStream::read( byte_type* buffer, size_type length ){ - return fread( buffer, 1, length, m_hFile ); -} - -int MemStream::GetChar(){ - if ( m_nPosition > m_nFileSize ) { - return 0; - } - - unsigned char* ret = (unsigned char*)m_pBuffer + m_nPosition; - m_nPosition++; - - return *ret; -} - -int FileStream::GetChar(){ - return fgetc( m_hFile ); -} - -MemStream::size_type MemStream::write( const byte_type* buffer, size_type length ){ - if ( length == 0 ) { - return 0; - } - - if ( m_nPosition + length > m_nBufferSize ) { - GrowFile( m_nPosition + length ); - } - - memcpy( (unsigned char*)m_pBuffer + m_nPosition, (unsigned char*)buffer, length ); - - m_nPosition += size_type( length ); - - if ( m_nPosition > m_nFileSize ) { - m_nFileSize = m_nPosition; - } - - return length; -} - -FileStream::size_type FileStream::write( const byte_type* buffer, size_type length ){ - return fwrite( buffer, 1, length, m_hFile ); -} - -int MemStream::PutChar( int c ){ - if ( m_nPosition + 1 > m_nBufferSize ) { - GrowFile( m_nPosition + 1 ); - } - - unsigned char* bt = (unsigned char*)m_pBuffer + m_nPosition; - *bt = c; - - m_nPosition++; - - if ( m_nPosition > m_nFileSize ) { - m_nFileSize = m_nPosition; - } - - return 1; -} - -/*!\todo SPoG suggestion: replace printf with operator >> using c++ iostream and strstream */ -void FileStream::printf( const char* s, ... ){ - va_list args; - - va_start( args, s ); - vfprintf( m_hFile, s, args ); - va_end( args ); -} - -/*!\todo SPoG suggestion: replace printf with operator >> using c++ iostream and strstream */ -void MemStream::printf( const char* s, ... ){ - va_list args; - - char buffer[4096]; - va_start( args, s ); - vsprintf( buffer, s, args ); - va_end( args ); - write( reinterpret_cast( buffer ), strlen( buffer ) ); -} - -int FileStream::PutChar( int c ){ - return fputc( c, m_hFile ); -} - -bool FileStream::Open( const char *filename, const char *mode ){ - m_hFile = fopen( filename, mode ); - m_bCloseOnDelete = true; - - return ( m_hFile != NULL ); -} - -void MemStream::Close(){ - m_nGrowBytes = 0; - m_nPosition = 0; - m_nBufferSize = 0; - m_nFileSize = 0; - if ( m_pBuffer && m_bAutoDelete ) { - free( m_pBuffer ); - } - m_pBuffer = NULL; -} - -void FileStream::Close(){ - if ( m_hFile != NULL ) { - fclose( m_hFile ); - } - - m_hFile = NULL; - m_bCloseOnDelete = false; -} - -int MemStream::Seek( offset_type lOff, int nFrom ){ - size_type lNewPos = m_nPosition; - - if ( nFrom == SEEK_SET ) { - lNewPos = lOff; - } - else if ( nFrom == SEEK_CUR ) { - lNewPos += lOff; - } - else if ( nFrom == SEEK_END ) { - lNewPos = m_nFileSize + lOff; - } - else{ - return ( position_type ) - 1; - } - - m_nPosition = lNewPos; - - return static_cast( m_nPosition ); -} - -int FileStream::Seek( offset_type lOff, int nFrom ){ - fseek( m_hFile, lOff, nFrom ); - - return ftell( m_hFile ); -} - -MemStream::position_type MemStream::GetPosition() const { - return m_nPosition; -} - -FileStream::position_type FileStream::GetPosition() const { - return ftell( m_hFile ); -} - -void MemStream::GrowFile( size_type nNewLen ){ - if ( nNewLen > m_nBufferSize ) { - // grow the buffer - size_type nNewBufferSize = m_nBufferSize; - - // determine new buffer size - while ( nNewBufferSize < nNewLen ) - nNewBufferSize += m_nGrowBytes; - - // allocate new buffer - unsigned char* lpNew; - if ( m_pBuffer == NULL ) { - lpNew = static_cast( malloc( nNewBufferSize ) ); - } - else{ - lpNew = static_cast( realloc( m_pBuffer, nNewBufferSize ) ); - } - - m_pBuffer = lpNew; - m_nBufferSize = nNewBufferSize; - } -} - -void MemStream::Flush(){ - // Nothing to be done -} - -void FileStream::Flush(){ - if ( m_hFile == NULL ) { - return; - } - - fflush( m_hFile ); -} - -void MemStream::Abort(){ - Close(); -} - -void FileStream::Abort(){ - if ( m_hFile != NULL ) { - // close but ignore errors - if ( m_bCloseOnDelete ) { - fclose( m_hFile ); - } - m_hFile = NULL; - m_bCloseOnDelete = false; - } -} - -void MemStream::SetLength( size_type nNewLen ){ - if ( nNewLen > m_nBufferSize ) { - GrowFile( nNewLen ); - } - - if ( nNewLen < m_nPosition ) { - m_nPosition = nNewLen; - } - - m_nFileSize = nNewLen; -} - -void FileStream::SetLength( size_type nNewLen ){ - fseek( m_hFile, static_cast( nNewLen ), SEEK_SET ); -} - -MemStream::size_type MemStream::GetLength() const { - return m_nFileSize; -} - -FileStream::size_type FileStream::GetLength() const { - size_type nLen, nCur; - - // Seek is a non const operation - nCur = ftell( m_hFile ); - fseek( m_hFile, 0, SEEK_END ); - nLen = ftell( m_hFile ); - fseek( m_hFile, static_cast( nCur ), SEEK_SET ); - - return nLen; -} diff --git a/tools/urt/libs/profile/file.h b/tools/urt/libs/profile/file.h deleted file mode 100644 index c4cdc14..0000000 --- a/tools/urt/libs/profile/file.h +++ /dev/null @@ -1,166 +0,0 @@ -/* - Copyright (c) 2001, Loki software, inc. - All rights reserved. - - Redistribution and use in source and binary forms, with or without modification, - are permitted provided that the following conditions are met: - - Redistributions of source code must retain the above copyright notice, this list - of conditions and the following disclaimer. - - Redistributions in binary form must reproduce the above copyright notice, this - list of conditions and the following disclaimer in the documentation and/or - other materials provided with the distribution. - - Neither the name of Loki software nor the names of its contributors may be used - to endorse or promote products derived from this software without specific prior - written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' - AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY - DIRECT,INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -// -// file.h -//////////////////////////////////////////////////// - -#if !defined( INCLUDED_PROFILE_FILE_H ) -#define INCLUDED_PROFILE_FILE_H - -#include "idatastream.h" - -/*! - API for data streams - - Based on an initial implementation by Loki software - modified to be abstracted and shared across modules - - NOTE: why IDataStream and not IStream? because IStream is defined in windows IDL headers - */ - -class IDataStream : public InputStream, public OutputStream -{ -public: -typedef int offset_type; -typedef std::size_t position_type; - -virtual void IncRef() = 0; ///< Increment the number of references to this object -virtual void DecRef() = 0; ///< Decrement the reference count - -virtual position_type GetPosition() const = 0; -virtual int Seek( offset_type lOff, int nFrom ) = 0; - -virtual void SetLength( size_type nNewLen ) = 0; -virtual size_type GetLength() const = 0; - -virtual char* ReadString( char* pBuf, size_type nMax ) = 0; -virtual int GetChar() = 0; - -virtual int PutChar( int c ) = 0; -virtual void printf( const char*, ... ) = 0; ///< completely matches the usual printf behaviour - -virtual void Abort() = 0; -virtual void Flush() = 0; -virtual void Close() = 0; -}; - -#include - -class MemStream : public IDataStream -{ -public: -MemStream(); -MemStream( size_type nLen ); -virtual ~MemStream(); - -int refCount; -void IncRef() { refCount++; } -void DecRef() { - refCount--; if ( refCount <= 0 ) { - delete this; - } -} - -protected: -// MemFile specific: -size_type m_nGrowBytes; -size_type m_nPosition; -size_type m_nBufferSize; -size_type m_nFileSize; -unsigned char* m_pBuffer; -bool m_bAutoDelete; -void GrowFile( size_type nNewLen ); - -public: -position_type GetPosition() const; -int Seek( offset_type lOff, int nFrom ); -void SetLength( size_type nNewLen ); -size_type GetLength() const; - -unsigned char* GetBuffer() const -{ return m_pBuffer; } - -size_type read( byte_type* buffer, size_type length ); -size_type write( const byte_type* buffer, size_type length ); - -char* ReadString( char* pBuf, size_type nMax ); -int GetChar(); - -int PutChar( int c ); -void printf( const char*, ... ); ///< \todo implement on MemStream - -void Abort(); -void Flush(); -void Close(); -bool Open( const char *filename, const char *mode ); -}; - -class FileStream : public IDataStream -{ -public: -FileStream(); -virtual ~FileStream(); - -int refCount; -void IncRef() { refCount++; } -void DecRef() { - refCount--; if ( refCount <= 0 ) { - delete this; - } -} - -protected: -// DiscFile specific: -FILE* m_hFile; -bool m_bCloseOnDelete; - -public: -position_type GetPosition() const; -int Seek( offset_type lOff, int nFrom ); -void SetLength( size_type nNewLen ); -size_type GetLength() const; - -size_type read( byte_type* buffer, size_type length ); -size_type write( const byte_type* buffer, size_type length ); - -char* ReadString( char* pBuf, size_type nMax ); -int GetChar(); - -int PutChar( int c ); -void printf( const char*, ... ); ///< completely matches the usual printf behaviour - -void Abort(); -void Flush(); -void Close(); -bool Open( const char *filename, const char *mode ); -}; - -#endif diff --git a/tools/urt/libs/profile/profile.cpp b/tools/urt/libs/profile/profile.cpp deleted file mode 100644 index bfcb942..0000000 --- a/tools/urt/libs/profile/profile.cpp +++ /dev/null @@ -1,292 +0,0 @@ -/* - Copyright (c) 2001, Loki software, inc. - All rights reserved. - - Redistribution and use in source and binary forms, with or without modification, - are permitted provided that the following conditions are met: - - Redistributions of source code must retain the above copyright notice, this list - of conditions and the following disclaimer. - - Redistributions in binary form must reproduce the above copyright notice, this - list of conditions and the following disclaimer in the documentation and/or - other materials provided with the distribution. - - Neither the name of Loki software nor the names of its contributors may be used - to endorse or promote products derived from this software without specific prior - written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' - AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY - DIRECT,INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -// -// Application settings load/save -// -// Leonardo Zide (leo@lokigames.com) -// - -#include "profile.h" - -#include -#include -#include - -#include "file.h" - -#include - -#include "str.h" - - -// ============================================================================= -// Static functions - -bool read_var( const char *filename, const char *section, const char *key, char *value ){ - char line[1024], *ptr; - FILE *rc; - - rc = fopen( filename, "rt" ); - - if ( rc == NULL ) { - return false; - } - - while ( fgets( line, 1024, rc ) != 0 ) - { - // First we find the section - if ( line[0] != '[' ) { - continue; - } - - ptr = strchr( line, ']' ); - *ptr = '\0'; - - if ( strcmp( &line[1], section ) == 0 ) { - while ( fgets( line, 1024, rc ) != 0 ) - { - ptr = strchr( line, '=' ); - - if ( ptr == NULL ) { - // reached the end of the section - fclose( rc ); - return false; - } - *ptr = '\0'; - - // remove spaces - while ( line[strlen( line ) - 1] == ' ' ) - line[strlen( line ) - 1] = '\0'; - - if ( strcmp( line, key ) == 0 ) { - strcpy( value, ptr + 1 ); - fclose( rc ); - - if ( value[strlen( value ) - 1] == 10 || value[strlen( value ) - 1] == 13 || value[strlen( value ) - 1] == 32 ) { - value[strlen( value ) - 1] = 0; - } - - return true; - } - } - } - } - - fclose( rc ); - return false; -} - -static bool save_var( const char *filename, const char *section, const char *key, const char *value ){ - char line[1024], *ptr; - MemStream old_rc; - bool found; - FILE *rc; - - rc = fopen( filename, "rb" ); - - if ( rc != NULL ) { - unsigned int len; - void *buf; - - fseek( rc, 0, SEEK_END ); - len = ftell( rc ); - rewind( rc ); - buf = malloc( len ); - fread( buf, len, 1, rc ); - old_rc.write( reinterpret_cast( buf ), len ); - free( buf ); - fclose( rc ); - old_rc.Seek( 0, SEEK_SET ); - } - - // TTimo: changed to binary writing. It doesn't seem to affect linux version, and win32 version was happending a lot of '\n' - rc = fopen( filename, "wb" ); - - if ( rc == NULL ) { - return false; - } - - // First we need to find the section - found = false; - while ( old_rc.ReadString( line, 1024 ) != NULL ) - { - fputs( line, rc ); - - if ( line[0] == '[' ) { - ptr = strchr( line, ']' ); - *ptr = '\0'; - - if ( strcmp( &line[1], section ) == 0 ) { - found = true; - break; - } - } - } - - if ( !found ) { - fputs( "\n", rc ); - fprintf( rc, "[%s]\n", section ); - } - - fprintf( rc, "%s=%s\n", key, value ); - - while ( old_rc.ReadString( line, 1024 ) != NULL ) - { - ptr = strchr( line, '=' ); - - if ( ptr != NULL ) { - *ptr = '\0'; - - if ( strcmp( line, key ) == 0 ) { - break; - } - - *ptr = '='; - fputs( line, rc ); - } - else - { - fputs( line, rc ); - break; - } - } - - while ( old_rc.ReadString( line, 1024 ) != NULL ) - fputs( line, rc ); - - fclose( rc ); - return true; -} - -// ============================================================================= -// Global functions - -bool profile_save_int( const char *filename, const char *section, const char *key, int value ){ - char buf[16]; - sprintf( buf, "%d", value ); - return save_var( filename, section, key, buf ); -} - -bool profile_save_float( const char *filename, const char *section, const char *key, float value ){ - char buf[16]; - sprintf( buf, "%f", value ); - return save_var( filename, section, key, buf ); -} - -bool profile_save_string( const char * filename, const char *section, const char *key, const char *value ){ - return save_var( filename, section, key, value ); -} - -bool profile_save_buffer( const char * rc_path, const char *name, void *buffer, unsigned int size ){ - bool ret = false; - char filename[1024]; - sprintf( filename, "%s/%s.bin", rc_path, name ); - FILE *f; - - f = fopen( filename, "wb" ); - - if ( f != NULL ) { - if ( fwrite( buffer, size, 1, f ) == 1 ) { - ret = true; - } - - fclose( f ); - } - - return ret; -} - -bool profile_load_buffer( const char * rc_path, const char *name, void *buffer, unsigned int *plSize ){ - char filename[1024]; - sprintf( filename, "%s/%s.bin", rc_path, name ); - bool ret = false; - unsigned int len; - FILE *f; - - f = fopen( filename, "rb" ); - - if ( f != NULL ) { - fseek( f, 0, SEEK_END ); - len = ftell( f ); - rewind( f ); - - if ( len > *plSize ) { - len = *plSize; - } - else{ - *plSize = len; - } - - if ( fread( buffer, len, 1, f ) == 1 ) { - ret = true; - } - - fclose( f ); - } - - return true; -} - -int profile_load_int( const char *filename, const char *section, const char *key, int default_value ){ - char value[1024]; - - if ( read_var( filename, section, key, value ) ) { - return atoi( value ); - } - else{ - return default_value; - } -} - -float profile_load_float( const char *filename, const char *section, const char *key, float default_value ){ - char value[1024]; - - if ( read_var( filename, section, key, value ) ) { - return static_cast( atof( value ) ); - } - else{ - return default_value; - } -} - -char* profile_load_string( const char *filename, const char *section, const char *key, const char *default_value ){ - static Str ret; - char value[1024]; - - if ( read_var( filename, section, key, value ) ) { - ret = value; - } - else{ - ret = default_value; - } - - return (char*)ret.GetBuffer(); -} diff --git a/tools/urt/libs/profile/profile.h b/tools/urt/libs/profile/profile.h deleted file mode 100644 index 65271a3..0000000 --- a/tools/urt/libs/profile/profile.h +++ /dev/null @@ -1,19 +0,0 @@ - -#if !defined( INCLUDED_PROFILE_PROFILE_H ) -#define INCLUDED_PROFILE_PROFILE_H - -// profile functions - kind of utility lib -// they are kind of dumb, they expect to get the path to the .ini file or to the prefs directory when called -// load_buffer and save_buffer expect the path only, theyll build a $(pszName).bin file -bool profile_save_int( const char *filename, const char *section, const char *key, int value ); -bool profile_save_float( const char *filename, const char *section, const char *key, float value ); -bool profile_save_string( const char *filename, const char *section, const char *key, const char *value ); -bool profile_save_buffer( const char *rc_path, const char *pszName, void *pvBuf, unsigned int lSize ); -bool profile_load_buffer( const char *rc_path, const char *pszName, void *pvBuf, unsigned int *plSize ); -int profile_load_int( const char *filename, const char *section, const char *key, int default_value ); -float profile_load_float( const char *filename, const char *section, const char *key, float default_value ); -char* profile_load_string( const char *filename, const char *section, const char *key, const char *default_value ); -// used in the command map code -bool read_var( const char *filename, const char *section, const char *key, char *value ); - -#endif diff --git a/tools/urt/libs/profile/profile.vcproj b/tools/urt/libs/profile/profile.vcproj deleted file mode 100644 index f1a27fb..0000000 --- a/tools/urt/libs/profile/profile.vcproj +++ /dev/null @@ -1,129 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/tools/urt/libs/radiant_jpeglib.h b/tools/urt/libs/radiant_jpeglib.h deleted file mode 100644 index 62562bd..0000000 --- a/tools/urt/libs/radiant_jpeglib.h +++ /dev/null @@ -1,1123 +0,0 @@ -/* - Copyright (C) 1999-2007 id Software, Inc. and contributors. - For a list of contributors, see the accompanying CONTRIBUTORS file. - - This file is part of GtkRadiant. - - GtkRadiant is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - GtkRadiant is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with GtkRadiant; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - */ - -/* - * jpeglib.h - * - * Copyright (C) 1991-1995, Thomas G. Lane. - * This file is part of the Independent JPEG Group's software. - * For conditions of distribution and use, see the accompanying README file. - * - * This file defines the application interface for the JPEG library. - * Most applications using the library need only include this file, - * and perhaps jerror.h if they want to know the exact error codes. - */ - -#ifndef JPEGLIB_H -#define JPEGLIB_H - -#ifdef __cplusplus -extern "C" -{ -#endif - -// LZ: linux stuff -#if defined ( __linux__ ) || defined ( __APPLE__ ) - -#include -#include - -#ifndef boolean -#ifdef __cplusplus -#define boolean bool -#else -typedef int boolean; -#endif -#endif - -#endif - -#ifdef __MACOS__ - -// JDC: stuff to make mac version compile -#define boolean qboolean -#define register -#define INT32 int - -#endif - -// rad additions -// 11.29.99 - -//#include "cmdlib.h" -#ifdef _WIN32 -#include "windows.h" -#include "stdio.h" -#endif - -#ifndef INT32 -#define INT32 int -#endif - -// TTimo: if LoadJPGBuff returns -1, *pic is the error message -extern int LoadJPGBuff( unsigned char *fbuffer, int bufsize, unsigned char **pic, int *width, int *height ); -// rad end - - -/* - * First we include the configuration files that record how this - * installation of the JPEG library is set up. jconfig.h can be - * generated automatically for many systems. jmorecfg.h contains - * manual configuration options that most people need not worry about. - */ - -#ifndef JCONFIG_INCLUDED /* in case jinclude.h already did */ -#include "jpeg6/jconfig.h" /* widely used configuration options */ -#endif -#include "jpeg6/jmorecfg.h" /* seldom changed options */ - - -/* Version ID for the JPEG library. - * Might be useful for tests like "#if JPEG_LIB_VERSION >= 60". - */ - -#define JPEG_LIB_VERSION 60 /* Version 6 */ - - -/* Various constants determining the sizes of things. - * All of these are specified by the JPEG standard, so don't change them - * if you want to be compatible. - */ - -#define DCTSIZE 8 /* The basic DCT block is 8x8 samples */ -#define DCTSIZE2 64 /* DCTSIZE squared; # of elements in a block */ -#define NUM_QUANT_TBLS 4 /* Quantization tables are numbered 0..3 */ -#define NUM_HUFF_TBLS 4 /* Huffman tables are numbered 0..3 */ -#define NUM_ARITH_TBLS 16 /* Arith-coding tables are numbered 0..15 */ -#define MAX_COMPS_IN_SCAN 4 /* JPEG limit on # of components in one scan */ -#define MAX_SAMP_FACTOR 4 /* JPEG limit on sampling factors */ -/* Unfortunately, some bozo at Adobe saw no reason to be bound by the standard; - * the PostScript DCT filter can emit files with many more than 10 blocks/MCU. - * If you happen to run across such a file, you can up D_MAX_BLOCKS_IN_MCU - * to handle it. We even let you do this from the jconfig.h file. However, - * we strongly discourage changing C_MAX_BLOCKS_IN_MCU; just because Adobe - * sometimes emits noncompliant files doesn't mean you should too. - */ -#define C_MAX_BLOCKS_IN_MCU 10 /* compressor's limit on blocks per MCU */ -#ifndef D_MAX_BLOCKS_IN_MCU -#define D_MAX_BLOCKS_IN_MCU 10 /* decompressor's limit on blocks per MCU */ -#endif - - -/* This macro is used to declare a "method", that is, a function pointer. - * We want to supply prototype parameters if the compiler can cope. - * Note that the arglist parameter must be parenthesized! - */ - -#ifdef HAVE_PROTOTYPES -#define JMETHOD( type,methodname,arglist ) type( *methodname ) arglist -#else -#define JMETHOD( type,methodname,arglist ) type ( *methodname )() -#endif - - -/* Data structures for images (arrays of samples and of DCT coefficients). - * On 80x86 machines, the image arrays are too big for near pointers, - * but the pointer arrays can fit in near memory. - */ - -typedef JSAMPLE FAR *JSAMPROW; /* ptr to one image row of pixel samples. */ -typedef JSAMPROW *JSAMPARRAY; /* ptr to some rows (a 2-D sample array) */ -typedef JSAMPARRAY *JSAMPIMAGE; /* a 3-D sample array: top index is color */ - -typedef JCOEF JBLOCK[DCTSIZE2]; /* one block of coefficients */ -typedef JBLOCK FAR *JBLOCKROW; /* pointer to one row of coefficient blocks */ -typedef JBLOCKROW *JBLOCKARRAY; /* a 2-D array of coefficient blocks */ -typedef JBLOCKARRAY *JBLOCKIMAGE; /* a 3-D array of coefficient blocks */ - -typedef JCOEF FAR *JCOEFPTR; /* useful in a couple of places */ - - -/* Types for JPEG compression parameters and working tables. */ - - -/* DCT coefficient quantization tables. */ - -typedef struct { - /* This field directly represents the contents of a JPEG DQT marker. - * Note: the values are always given in zigzag order. - */ - UINT16 quantval[DCTSIZE2]; /* quantization step for each coefficient */ - /* This field is used only during compression. It's initialized FALSE when - * the table is created, and set TRUE when it's been output to the file. - * You could suppress output of a table by setting this to TRUE. - * (See jpeg_suppress_tables for an example.) - */ - boolean sent_table; /* TRUE when table has been output */ -} JQUANT_TBL; - - -/* Huffman coding tables. */ - -typedef struct { - /* These two fields directly represent the contents of a JPEG DHT marker */ - UINT8 bits[17]; /* bits[k] = # of symbols with codes of */ - /* length k bits; bits[0] is unused */ - UINT8 huffval[256]; /* The symbols, in order of incr code length */ - /* This field is used only during compression. It's initialized FALSE when - * the table is created, and set TRUE when it's been output to the file. - * You could suppress output of a table by setting this to TRUE. - * (See jpeg_suppress_tables for an example.) - */ - boolean sent_table; /* TRUE when table has been output */ -} JHUFF_TBL; - - -/* Basic info about one component (color channel). */ - -typedef struct { - /* These values are fixed over the whole image. */ - /* For compression, they must be supplied by parameter setup; */ - /* for decompression, they are read from the SOF marker. */ - int component_id; /* identifier for this component (0..255) */ - int component_index; /* its index in SOF or cinfo->comp_info[] */ - int h_samp_factor; /* horizontal sampling factor (1..4) */ - int v_samp_factor; /* vertical sampling factor (1..4) */ - int quant_tbl_no; /* quantization table selector (0..3) */ - /* These values may vary between scans. */ - /* For compression, they must be supplied by parameter setup; */ - /* for decompression, they are read from the SOS marker. */ - /* The decompressor output side may not use these variables. */ - int dc_tbl_no; /* DC entropy table selector (0..3) */ - int ac_tbl_no; /* AC entropy table selector (0..3) */ - - /* Remaining fields should be treated as private by applications. */ - - /* These values are computed during compression or decompression startup: */ - /* Component's size in DCT blocks. - * Any dummy blocks added to complete an MCU are not counted; therefore - * these values do not depend on whether a scan is interleaved or not. - */ - JDIMENSION width_in_blocks; - JDIMENSION height_in_blocks; - /* Size of a DCT block in samples. Always DCTSIZE for compression. - * For decompression this is the size of the output from one DCT block, - * reflecting any scaling we choose to apply during the IDCT step. - * Values of 1,2,4,8 are likely to be supported. Note that different - * components may receive different IDCT scalings. - */ - int DCT_scaled_size; - /* The downsampled dimensions are the component's actual, unpadded number - * of samples at the main buffer (preprocessing/compression interface), thus - * downsampled_width = ceil(image_width * Hi/Hmax) - * and similarly for height. For decompression, IDCT scaling is included, so - * downsampled_width = ceil(image_width * Hi/Hmax * DCT_scaled_size/DCTSIZE) - */ - JDIMENSION downsampled_width; /* actual width in samples */ - JDIMENSION downsampled_height; /* actual height in samples */ - /* This flag is used only for decompression. In cases where some of the - * components will be ignored (eg grayscale output from YCbCr image), - * we can skip most computations for the unused components. - */ - boolean component_needed; /* do we need the value of this component? */ - - /* These values are computed before starting a scan of the component. */ - /* The decompressor output side may not use these variables. */ - int MCU_width; /* number of blocks per MCU, horizontally */ - int MCU_height; /* number of blocks per MCU, vertically */ - int MCU_blocks; /* MCU_width * MCU_height */ - int MCU_sample_width; /* MCU width in samples, MCU_width*DCT_scaled_size */ - int last_col_width; /* # of non-dummy blocks across in last MCU */ - int last_row_height; /* # of non-dummy blocks down in last MCU */ - - /* Saved quantization table for component; NULL if none yet saved. - * See jdinput.c comments about the need for this information. - * This field is not currently used by the compressor. - */ - JQUANT_TBL * quant_table; - - /* Private per-component storage for DCT or IDCT subsystem. */ - void * dct_table; -} jpeg_component_info; - - -/* The script for encoding a multiple-scan file is an array of these: */ - -typedef struct { - int comps_in_scan; /* number of components encoded in this scan */ - int component_index[MAX_COMPS_IN_SCAN]; /* their SOF/comp_info[] indexes */ - int Ss, Se; /* progressive JPEG spectral selection parms */ - int Ah, Al; /* progressive JPEG successive approx. parms */ -} jpeg_scan_info; - - -/* Known color spaces. */ - -typedef enum { - JCS_UNKNOWN, /* error/unspecified */ - JCS_GRAYSCALE, /* monochrome */ - JCS_RGB, /* red/green/blue */ - JCS_YCbCr, /* Y/Cb/Cr (also known as YUV) */ - JCS_CMYK, /* C/M/Y/K */ - JCS_YCCK /* Y/Cb/Cr/K */ -} J_COLOR_SPACE; - -/* DCT/IDCT algorithm options. */ - -typedef enum { - JDCT_ISLOW, /* slow but accurate integer algorithm */ - JDCT_IFAST, /* faster, less accurate integer method */ - JDCT_FLOAT /* floating-point: accurate, fast on fast HW */ -} J_DCT_METHOD; - -#ifndef JDCT_DEFAULT /* may be overridden in jconfig.h */ -#define JDCT_DEFAULT JDCT_ISLOW -#endif -#ifndef JDCT_FASTEST /* may be overridden in jconfig.h */ -#define JDCT_FASTEST JDCT_IFAST -#endif - -/* Dithering options for decompression. */ - -typedef enum { - JDITHER_NONE, /* no dithering */ - JDITHER_ORDERED, /* simple ordered dither */ - JDITHER_FS /* Floyd-Steinberg error diffusion dither */ -} J_DITHER_MODE; - - -/* Common fields between JPEG compression and decompression master structs. */ - -#define jpeg_common_fields \ - struct jpeg_error_mgr * err; /* Error handler module */ \ - struct jpeg_memory_mgr * mem; /* Memory manager module */ \ - struct jpeg_progress_mgr * progress; /* Progress monitor, or NULL if none */ \ - boolean is_decompressor; /* so common code can tell which is which */ \ - int global_state /* for checking call sequence validity */ - -/* Routines that are to be used by both halves of the library are declared - * to receive a pointer to this structure. There are no actual instances of - * jpeg_common_struct, only of jpeg_compress_struct and jpeg_decompress_struct. - */ -struct jpeg_common_struct { - jpeg_common_fields; /* Fields common to both master struct types */ - /* Additional fields follow in an actual jpeg_compress_struct or - * jpeg_decompress_struct. All three structs must agree on these - * initial fields! (This would be a lot cleaner in C++.) - */ -}; - -typedef struct jpeg_common_struct * j_common_ptr; -typedef struct jpeg_compress_struct * j_compress_ptr; -typedef struct jpeg_decompress_struct * j_decompress_ptr; - - -/* Master record for a compression instance */ - -struct jpeg_compress_struct { - jpeg_common_fields; /* Fields shared with jpeg_decompress_struct */ - - /* Destination for compressed data */ - struct jpeg_destination_mgr * dest; - - /* Description of source image --- these fields must be filled in by - * outer application before starting compression. in_color_space must - * be correct before you can even call jpeg_set_defaults(). - */ - - JDIMENSION image_width; /* input image width */ - JDIMENSION image_height; /* input image height */ - int input_components; /* # of color components in input image */ - J_COLOR_SPACE in_color_space; /* colorspace of input image */ - - double input_gamma; /* image gamma of input image */ - - /* Compression parameters --- these fields must be set before calling - * jpeg_start_compress(). We recommend calling jpeg_set_defaults() to - * initialize everything to reasonable defaults, then changing anything - * the application specifically wants to change. That way you won't get - * burnt when new parameters are added. Also note that there are several - * helper routines to simplify changing parameters. - */ - - int data_precision; /* bits of precision in image data */ - - int num_components; /* # of color components in JPEG image */ - J_COLOR_SPACE jpeg_color_space; /* colorspace of JPEG image */ - - jpeg_component_info * comp_info; - /* comp_info[i] describes component that appears i'th in SOF */ - - JQUANT_TBL * quant_tbl_ptrs[NUM_QUANT_TBLS]; - /* ptrs to coefficient quantization tables, or NULL if not defined */ - - JHUFF_TBL * dc_huff_tbl_ptrs[NUM_HUFF_TBLS]; - JHUFF_TBL * ac_huff_tbl_ptrs[NUM_HUFF_TBLS]; - /* ptrs to Huffman coding tables, or NULL if not defined */ - - UINT8 arith_dc_L[NUM_ARITH_TBLS]; /* L values for DC arith-coding tables */ - UINT8 arith_dc_U[NUM_ARITH_TBLS]; /* U values for DC arith-coding tables */ - UINT8 arith_ac_K[NUM_ARITH_TBLS]; /* Kx values for AC arith-coding tables */ - - int num_scans; /* # of entries in scan_info array */ - const jpeg_scan_info * scan_info; /* script for multi-scan file, or NULL */ - /* The default value of scan_info is NULL, which causes a single-scan - * sequential JPEG file to be emitted. To create a multi-scan file, - * set num_scans and scan_info to point to an array of scan definitions. - */ - - boolean raw_data_in; /* TRUE=caller supplies downsampled data */ - boolean arith_code; /* TRUE=arithmetic coding, FALSE=Huffman */ - boolean optimize_coding; /* TRUE=optimize entropy encoding parms */ - boolean CCIR601_sampling; /* TRUE=first samples are cosited */ - int smoothing_factor; /* 1..100, or 0 for no input smoothing */ - J_DCT_METHOD dct_method; /* DCT algorithm selector */ - - /* The restart interval can be specified in absolute MCUs by setting - * restart_interval, or in MCU rows by setting restart_in_rows - * (in which case the correct restart_interval will be figured - * for each scan). - */ - unsigned int restart_interval; /* MCUs per restart, or 0 for no restart */ - int restart_in_rows; /* if > 0, MCU rows per restart interval */ - - /* Parameters controlling emission of special markers. */ - - boolean write_JFIF_header; /* should a JFIF marker be written? */ - /* These three values are not used by the JPEG code, merely copied */ - /* into the JFIF APP0 marker. density_unit can be 0 for unknown, */ - /* 1 for dots/inch, or 2 for dots/cm. Note that the pixel aspect */ - /* ratio is defined by X_density/Y_density even when density_unit=0. */ - UINT8 density_unit; /* JFIF code for pixel size units */ - UINT16 X_density; /* Horizontal pixel density */ - UINT16 Y_density; /* Vertical pixel density */ - boolean write_Adobe_marker; /* should an Adobe marker be written? */ - - /* State variable: index of next scanline to be written to - * jpeg_write_scanlines(). Application may use this to control its - * processing loop, e.g., "while (next_scanline < image_height)". - */ - - JDIMENSION next_scanline; /* 0 .. image_height-1 */ - - /* Remaining fields are known throughout compressor, but generally - * should not be touched by a surrounding application. - */ - - /* - * These fields are computed during compression startup - */ - boolean progressive_mode; /* TRUE if scan script uses progressive mode */ - int max_h_samp_factor; /* largest h_samp_factor */ - int max_v_samp_factor; /* largest v_samp_factor */ - - JDIMENSION total_iMCU_rows; /* # of iMCU rows to be input to coef ctlr */ - /* The coefficient controller receives data in units of MCU rows as defined - * for fully interleaved scans (whether the JPEG file is interleaved or not). - * There are v_samp_factor * DCTSIZE sample rows of each component in an - * "iMCU" (interleaved MCU) row. - */ - - /* - * These fields are valid during any one scan. - * They describe the components and MCUs actually appearing in the scan. - */ - int comps_in_scan; /* # of JPEG components in this scan */ - jpeg_component_info * cur_comp_info[MAX_COMPS_IN_SCAN]; - /* *cur_comp_info[i] describes component that appears i'th in SOS */ - - JDIMENSION MCUs_per_row; /* # of MCUs across the image */ - JDIMENSION MCU_rows_in_scan; /* # of MCU rows in the image */ - - int blocks_in_MCU; /* # of DCT blocks per MCU */ - int MCU_membership[C_MAX_BLOCKS_IN_MCU]; - /* MCU_membership[i] is index in cur_comp_info of component owning */ - /* i'th block in an MCU */ - - int Ss, Se, Ah, Al; /* progressive JPEG parameters for scan */ - - /* - * Links to compression subobjects (methods and private variables of modules) - */ - struct jpeg_comp_master * master; - struct jpeg_c_main_controller * main; - struct jpeg_c_prep_controller * prep; - struct jpeg_c_coef_controller * coef; - struct jpeg_marker_writer * marker; - struct jpeg_color_converter * cconvert; - struct jpeg_downsampler * downsample; - struct jpeg_forward_dct * fdct; - struct jpeg_entropy_encoder * entropy; -}; - - -/* Master record for a decompression instance */ - -struct jpeg_decompress_struct { - jpeg_common_fields; /* Fields shared with jpeg_compress_struct */ - - /* Source of compressed data */ - struct jpeg_source_mgr * src; - - /* Basic description of image --- filled in by jpeg_read_header(). */ - /* Application may inspect these values to decide how to process image. */ - - JDIMENSION image_width; /* nominal image width (from SOF marker) */ - JDIMENSION image_height; /* nominal image height */ - int num_components; /* # of color components in JPEG image */ - J_COLOR_SPACE jpeg_color_space; /* colorspace of JPEG image */ - - /* Decompression processing parameters --- these fields must be set before - * calling jpeg_start_decompress(). Note that jpeg_read_header() initializes - * them to default values. - */ - - J_COLOR_SPACE out_color_space; /* colorspace for output */ - - unsigned int scale_num, scale_denom; /* fraction by which to scale image */ - - double output_gamma; /* image gamma wanted in output */ - - boolean buffered_image; /* TRUE=multiple output passes */ - boolean raw_data_out; /* TRUE=downsampled data wanted */ - - J_DCT_METHOD dct_method; /* IDCT algorithm selector */ - boolean do_fancy_upsampling; /* TRUE=apply fancy upsampling */ - boolean do_block_smoothing; /* TRUE=apply interblock smoothing */ - - boolean quantize_colors; /* TRUE=colormapped output wanted */ - /* the following are ignored if not quantize_colors: */ - J_DITHER_MODE dither_mode; /* type of color dithering to use */ - boolean two_pass_quantize; /* TRUE=use two-pass color quantization */ - int desired_number_of_colors; /* max # colors to use in created colormap */ - /* these are significant only in buffered-image mode: */ - boolean enable_1pass_quant; /* enable future use of 1-pass quantizer */ - boolean enable_external_quant; /* enable future use of external colormap */ - boolean enable_2pass_quant; /* enable future use of 2-pass quantizer */ - - /* Description of actual output image that will be returned to application. - * These fields are computed by jpeg_start_decompress(). - * You can also use jpeg_calc_output_dimensions() to determine these values - * in advance of calling jpeg_start_decompress(). - */ - - JDIMENSION output_width; /* scaled image width */ - JDIMENSION output_height; /* scaled image height */ - int out_color_components; /* # of color components in out_color_space */ - int output_components; /* # of color components returned */ - /* output_components is 1 (a colormap index) when quantizing colors; - * otherwise it equals out_color_components. - */ - int rec_outbuf_height; /* min recommended height of scanline buffer */ - /* If the buffer passed to jpeg_read_scanlines() is less than this many rows - * high, space and time will be wasted due to unnecessary data copying. - * Usually rec_outbuf_height will be 1 or 2, at most 4. - */ - - /* When quantizing colors, the output colormap is described by these fields. - * The application can supply a colormap by setting colormap non-NULL before - * calling jpeg_start_decompress; otherwise a colormap is created during - * jpeg_start_decompress or jpeg_start_output. - * The map has out_color_components rows and actual_number_of_colors columns. - */ - int actual_number_of_colors; /* number of entries in use */ - JSAMPARRAY colormap; /* The color map as a 2-D pixel array */ - - /* State variables: these variables indicate the progress of decompression. - * The application may examine these but must not modify them. - */ - - /* Row index of next scanline to be read from jpeg_read_scanlines(). - * Application may use this to control its processing loop, e.g., - * "while (output_scanline < output_height)". - */ - JDIMENSION output_scanline; /* 0 .. output_height-1 */ - - /* Current input scan number and number of iMCU rows completed in scan. - * These indicate the progress of the decompressor input side. - */ - int input_scan_number; /* Number of SOS markers seen so far */ - JDIMENSION input_iMCU_row; /* Number of iMCU rows completed */ - - /* The "output scan number" is the notional scan being displayed by the - * output side. The decompressor will not allow output scan/row number - * to get ahead of input scan/row, but it can fall arbitrarily far behind. - */ - int output_scan_number; /* Nominal scan number being displayed */ - JDIMENSION output_iMCU_row; /* Number of iMCU rows read */ - - /* Current progression status. coef_bits[c][i] indicates the precision - * with which component c's DCT coefficient i (in zigzag order) is known. - * It is -1 when no data has yet been received, otherwise it is the point - * transform (shift) value for the most recent scan of the coefficient - * (thus, 0 at completion of the progression). - * This pointer is NULL when reading a non-progressive file. - */ - int (*coef_bits)[DCTSIZE2]; /* -1 or current Al value for each coef */ - - /* Internal JPEG parameters --- the application usually need not look at - * these fields. Note that the decompressor output side may not use - * any parameters that can change between scans. - */ - - /* Quantization and Huffman tables are carried forward across input - * datastreams when processing abbreviated JPEG datastreams. - */ - - JQUANT_TBL * quant_tbl_ptrs[NUM_QUANT_TBLS]; - /* ptrs to coefficient quantization tables, or NULL if not defined */ - - JHUFF_TBL * dc_huff_tbl_ptrs[NUM_HUFF_TBLS]; - JHUFF_TBL * ac_huff_tbl_ptrs[NUM_HUFF_TBLS]; - /* ptrs to Huffman coding tables, or NULL if not defined */ - - /* These parameters are never carried across datastreams, since they - * are given in SOF/SOS markers or defined to be reset by SOI. - */ - - int data_precision; /* bits of precision in image data */ - - jpeg_component_info * comp_info; - /* comp_info[i] describes component that appears i'th in SOF */ - - boolean progressive_mode; /* TRUE if SOFn specifies progressive mode */ - boolean arith_code; /* TRUE=arithmetic coding, FALSE=Huffman */ - - UINT8 arith_dc_L[NUM_ARITH_TBLS]; /* L values for DC arith-coding tables */ - UINT8 arith_dc_U[NUM_ARITH_TBLS]; /* U values for DC arith-coding tables */ - UINT8 arith_ac_K[NUM_ARITH_TBLS]; /* Kx values for AC arith-coding tables */ - - unsigned int restart_interval; /* MCUs per restart interval, or 0 for no restart */ - - /* These fields record data obtained from optional markers recognized by - * the JPEG library. - */ - boolean saw_JFIF_marker; /* TRUE iff a JFIF APP0 marker was found */ - /* Data copied from JFIF marker: */ - UINT8 density_unit; /* JFIF code for pixel size units */ - UINT16 X_density; /* Horizontal pixel density */ - UINT16 Y_density; /* Vertical pixel density */ - boolean saw_Adobe_marker; /* TRUE iff an Adobe APP14 marker was found */ - UINT8 Adobe_transform; /* Color transform code from Adobe marker */ - - boolean CCIR601_sampling; /* TRUE=first samples are cosited */ - - /* Remaining fields are known throughout decompressor, but generally - * should not be touched by a surrounding application. - */ - - /* - * These fields are computed during decompression startup - */ - int max_h_samp_factor; /* largest h_samp_factor */ - int max_v_samp_factor; /* largest v_samp_factor */ - - int min_DCT_scaled_size; /* smallest DCT_scaled_size of any component */ - - JDIMENSION total_iMCU_rows; /* # of iMCU rows in image */ - /* The coefficient controller's input and output progress is measured in - * units of "iMCU" (interleaved MCU) rows. These are the same as MCU rows - * in fully interleaved JPEG scans, but are used whether the scan is - * interleaved or not. We define an iMCU row as v_samp_factor DCT block - * rows of each component. Therefore, the IDCT output contains - * v_samp_factor*DCT_scaled_size sample rows of a component per iMCU row. - */ - - JSAMPLE * sample_range_limit; /* table for fast range-limiting */ - - /* - * These fields are valid during any one scan. - * They describe the components and MCUs actually appearing in the scan. - * Note that the decompressor output side must not use these fields. - */ - int comps_in_scan; /* # of JPEG components in this scan */ - jpeg_component_info * cur_comp_info[MAX_COMPS_IN_SCAN]; - /* *cur_comp_info[i] describes component that appears i'th in SOS */ - - JDIMENSION MCUs_per_row; /* # of MCUs across the image */ - JDIMENSION MCU_rows_in_scan; /* # of MCU rows in the image */ - - int blocks_in_MCU; /* # of DCT blocks per MCU */ - int MCU_membership[D_MAX_BLOCKS_IN_MCU]; - /* MCU_membership[i] is index in cur_comp_info of component owning */ - /* i'th block in an MCU */ - - int Ss, Se, Ah, Al; /* progressive JPEG parameters for scan */ - - /* This field is shared between entropy decoder and marker parser. - * It is either zero or the code of a JPEG marker that has been - * read from the data source, but has not yet been processed. - */ - int unread_marker; - - /* - * Links to decompression subobjects (methods, private variables of modules) - */ - struct jpeg_decomp_master * master; - struct jpeg_d_main_controller * main; - struct jpeg_d_coef_controller * coef; - struct jpeg_d_post_controller * post; - struct jpeg_input_controller * inputctl; - struct jpeg_marker_reader * marker; - struct jpeg_entropy_decoder * entropy; - struct jpeg_inverse_dct * idct; - struct jpeg_upsampler * upsample; - struct jpeg_color_deconverter * cconvert; - struct jpeg_color_quantizer * cquantize; -}; - - -/* "Object" declarations for JPEG modules that may be supplied or called - * directly by the surrounding application. - * As with all objects in the JPEG library, these structs only define the - * publicly visible methods and state variables of a module. Additional - * private fields may exist after the public ones. - */ - - -/* Error handler object */ - -struct jpeg_error_mgr { - /* Error exit handler: does not return to caller */ - JMETHOD( void, error_exit, (j_common_ptr cinfo) ); - /* Conditionally emit a trace or warning message */ - JMETHOD( void, emit_message, ( j_common_ptr cinfo, int msg_level ) ); - /* Routine that actually outputs a trace or error message */ - JMETHOD( void, output_message, (j_common_ptr cinfo) ); - /* Format a message string for the most recent JPEG error or message */ - JMETHOD( void, format_message, ( j_common_ptr cinfo, char * buffer ) ); -#define JMSG_LENGTH_MAX 200 /* recommended size of format_message buffer */ - /* Reset error state variables at start of a new image */ - JMETHOD( void, reset_error_mgr, (j_common_ptr cinfo) ); - - /* The message ID code and any parameters are saved here. - * A message can have one string parameter or up to 8 int parameters. - */ - int msg_code; -#define JMSG_STR_PARM_MAX 80 - union { - int i[8]; - char s[JMSG_STR_PARM_MAX]; - } msg_parm; - - /* Standard state variables for error facility */ - - int trace_level; /* max msg_level that will be displayed */ - - /* For recoverable corrupt-data errors, we emit a warning message, - * but keep going unless emit_message chooses to abort. emit_message - * should count warnings in num_warnings. The surrounding application - * can check for bad data by seeing if num_warnings is nonzero at the - * end of processing. - */ - long num_warnings; /* number of corrupt-data warnings */ - - /* These fields point to the table(s) of error message strings. - * An application can change the table pointer to switch to a different - * message list (typically, to change the language in which errors are - * reported). Some applications may wish to add additional error codes - * that will be handled by the JPEG library error mechanism; the second - * table pointer is used for this purpose. - * - * First table includes all errors generated by JPEG library itself. - * Error code 0 is reserved for a "no such error string" message. - */ - const char * const * jpeg_message_table; /* Library errors */ - int last_jpeg_message; /* Table contains strings 0..last_jpeg_message */ - /* Second table can be added by application (see cjpeg/djpeg for example). - * It contains strings numbered first_addon_message..last_addon_message. - */ - const char * const * addon_message_table; /* Non-library errors */ - int first_addon_message; /* code for first string in addon table */ - int last_addon_message; /* code for last string in addon table */ -}; - - -/* Progress monitor object */ - -struct jpeg_progress_mgr { - JMETHOD( void, progress_monitor, (j_common_ptr cinfo) ); - - long pass_counter; /* work units completed in this pass */ - long pass_limit; /* total number of work units in this pass */ - int completed_passes; /* passes completed so far */ - int total_passes; /* total number of passes expected */ -}; - - -/* Data destination object for compression */ - -struct jpeg_destination_mgr { - JOCTET * next_output_byte; /* => next byte to write in buffer */ - size_t free_in_buffer; /* # of byte spaces remaining in buffer */ - - JMETHOD( void, init_destination, (j_compress_ptr cinfo) ); - JMETHOD( boolean, empty_output_buffer, (j_compress_ptr cinfo) ); - JMETHOD( void, term_destination, (j_compress_ptr cinfo) ); -}; - - -/* Data source object for decompression */ - -struct jpeg_source_mgr { - const JOCTET * next_input_byte; /* => next byte to read from buffer */ - size_t bytes_in_buffer; /* # of bytes remaining in buffer */ - - JMETHOD( void, init_source, (j_decompress_ptr cinfo) ); - JMETHOD( boolean, fill_input_buffer, (j_decompress_ptr cinfo) ); - JMETHOD( void, skip_input_data, ( j_decompress_ptr cinfo, long num_bytes ) ); - JMETHOD( boolean, resync_to_restart, ( j_decompress_ptr cinfo, int desired ) ); - JMETHOD( void, term_source, (j_decompress_ptr cinfo) ); -}; - - -/* Memory manager object. - * Allocates "small" objects (a few K total), "large" objects (tens of K), - * and "really big" objects (virtual arrays with backing store if needed). - * The memory manager does not allow individual objects to be freed; rather, - * each created object is assigned to a pool, and whole pools can be freed - * at once. This is faster and more convenient than remembering exactly what - * to free, especially where malloc()/free() are not too speedy. - * NB: alloc routines never return NULL. They exit to error_exit if not - * successful. - */ - -#define JPOOL_PERMANENT 0 /* lasts until master record is destroyed */ -#define JPOOL_IMAGE 1 /* lasts until done with image/datastream */ -#define JPOOL_NUMPOOLS 2 - -typedef struct jvirt_sarray_control * jvirt_sarray_ptr; -typedef struct jvirt_barray_control * jvirt_barray_ptr; - - -struct jpeg_memory_mgr { - /* Method pointers */ - JMETHOD( void *, alloc_small, ( j_common_ptr cinfo, int pool_id, - size_t sizeofobject ) ); - JMETHOD( void FAR *, alloc_large, ( j_common_ptr cinfo, int pool_id, - size_t sizeofobject ) ); - JMETHOD( JSAMPARRAY, alloc_sarray, ( j_common_ptr cinfo, int pool_id, - JDIMENSION samplesperrow, - JDIMENSION numrows ) ); - JMETHOD( JBLOCKARRAY, alloc_barray, ( j_common_ptr cinfo, int pool_id, - JDIMENSION blocksperrow, - JDIMENSION numrows ) ); - JMETHOD( jvirt_sarray_ptr, request_virt_sarray, ( j_common_ptr cinfo, - int pool_id, - boolean pre_zero, - JDIMENSION samplesperrow, - JDIMENSION numrows, - JDIMENSION maxaccess ) ); - JMETHOD( jvirt_barray_ptr, request_virt_barray, ( j_common_ptr cinfo, - int pool_id, - boolean pre_zero, - JDIMENSION blocksperrow, - JDIMENSION numrows, - JDIMENSION maxaccess ) ); - JMETHOD( void, realize_virt_arrays, (j_common_ptr cinfo) ); - JMETHOD( JSAMPARRAY, access_virt_sarray, ( j_common_ptr cinfo, - jvirt_sarray_ptr ptr, - JDIMENSION start_row, - JDIMENSION num_rows, - boolean writable ) ); - JMETHOD( JBLOCKARRAY, access_virt_barray, ( j_common_ptr cinfo, - jvirt_barray_ptr ptr, - JDIMENSION start_row, - JDIMENSION num_rows, - boolean writable ) ); - JMETHOD( void, free_pool, ( j_common_ptr cinfo, int pool_id ) ); - JMETHOD( void, self_destruct, (j_common_ptr cinfo) ); - - /* Limit on memory allocation for this JPEG object. (Note that this is - * merely advisory, not a guaranteed maximum; it only affects the space - * used for virtual-array buffers.) May be changed by outer application - * after creating the JPEG object. - */ - long max_memory_to_use; -}; - - -/* Routine signature for application-supplied marker processing methods. - * Need not pass marker code since it is stored in cinfo->unread_marker. - */ -typedef JMETHOD ( boolean, jpeg_marker_parser_method, ( j_decompress_ptr cinfo ) ); - - -/* Declarations for routines called by application. - * The JPP macro hides prototype parameters from compilers that can't cope. - * Note JPP requires double parentheses. - */ - -#ifdef HAVE_PROTOTYPES -#define JPP( arglist ) arglist -#else -#define JPP( arglist ) ( ) -#endif - - -/* Short forms of external names for systems with brain-damaged linkers. - * We shorten external names to be unique in the first six letters, which - * is good enough for all known systems. - * (If your compiler itself needs names to be unique in less than 15 - * characters, you are out of luck. Get a better compiler.) - */ - -#ifdef NEED_SHORT_EXTERNAL_NAMES -#define jpeg_std_error jStdError -#define jpeg_create_compress jCreaCompress -#define jpeg_create_decompress jCreaDecompress -#define jpeg_destroy_compress jDestCompress -#define jpeg_destroy_decompress jDestDecompress -#define jpeg_stdio_dest jStdDest -#define jpeg_stdio_src jStdSrc -#define jpeg_set_defaults jSetDefaults -#define jpeg_set_colorspace jSetColorspace -#define jpeg_default_colorspace jDefColorspace -#define jpeg_set_quality jSetQuality -#define jpeg_set_linear_quality jSetLQuality -#define jpeg_add_quant_table jAddQuantTable -#define jpeg_quality_scaling jQualityScaling -#define jpeg_simple_progression jSimProgress -#define jpeg_suppress_tables jSuppressTables -#define jpeg_alloc_quant_table jAlcQTable -#define jpeg_alloc_huff_table jAlcHTable -#define jpeg_start_compress jStrtCompress -#define jpeg_write_scanlines jWrtScanlines -#define jpeg_finish_compress jFinCompress -#define jpeg_write_raw_data jWrtRawData -#define jpeg_write_marker jWrtMarker -#define jpeg_write_tables jWrtTables -#define jpeg_read_header jReadHeader -#define jpeg_start_decompress jStrtDecompress -#define jpeg_read_scanlines jReadScanlines -#define jpeg_finish_decompress jFinDecompress -#define jpeg_read_raw_data jReadRawData -#define jpeg_has_multiple_scans jHasMultScn -#define jpeg_start_output jStrtOutput -#define jpeg_finish_output jFinOutput -#define jpeg_input_complete jInComplete -#define jpeg_new_colormap jNewCMap -#define jpeg_consume_input jConsumeInput -#define jpeg_calc_output_dimensions jCalcDimensions -#define jpeg_set_marker_processor jSetMarker -#define jpeg_read_coefficients jReadCoefs -#define jpeg_write_coefficients jWrtCoefs -#define jpeg_copy_critical_parameters jCopyCrit -#define jpeg_abort_compress jAbrtCompress -#define jpeg_abort_decompress jAbrtDecompress -#define jpeg_abort jAbort -#define jpeg_destroy jDestroy -#define jpeg_resync_to_restart jResyncRestart -#endif /* NEED_SHORT_EXTERNAL_NAMES */ - - -/* Default error-management setup */ -EXTERN struct jpeg_error_mgr *jpeg_std_error JPP( (struct jpeg_error_mgr *err) ); - -/* Initialization and destruction of JPEG compression objects */ -/* NB: you must set up the error-manager BEFORE calling jpeg_create_xxx */ -EXTERN void jpeg_create_compress JPP( (j_compress_ptr cinfo) ); -EXTERN void jpeg_create_decompress JPP( (j_decompress_ptr cinfo) ); -EXTERN void jpeg_destroy_compress JPP( (j_compress_ptr cinfo) ); -EXTERN void jpeg_destroy_decompress JPP( (j_decompress_ptr cinfo) ); - -/* Standard data source and destination managers: stdio streams. */ -/* Caller is responsible for opening the file before and closing after. */ -EXTERN void jpeg_stdio_dest JPP( ( j_compress_ptr cinfo, FILE * outfile ) ); -EXTERN void jpeg_stdio_src JPP( ( j_decompress_ptr cinfo, unsigned char *infile, int bufsize ) ); - -/* Default parameter setup for compression */ -EXTERN void jpeg_set_defaults JPP( (j_compress_ptr cinfo) ); -/* Compression parameter setup aids */ -EXTERN void jpeg_set_colorspace JPP( ( j_compress_ptr cinfo, - J_COLOR_SPACE colorspace ) ); -EXTERN void jpeg_default_colorspace JPP( (j_compress_ptr cinfo) ); -EXTERN void jpeg_set_quality JPP( ( j_compress_ptr cinfo, int quality, - boolean force_baseline ) ); -EXTERN void jpeg_set_linear_quality JPP( ( j_compress_ptr cinfo, - int scale_factor, - boolean force_baseline ) ); -EXTERN void jpeg_add_quant_table JPP( ( j_compress_ptr cinfo, int which_tbl, - const unsigned int *basic_table, - int scale_factor, - boolean force_baseline ) ); -EXTERN int jpeg_quality_scaling JPP( (int quality) ); -EXTERN void jpeg_simple_progression JPP( (j_compress_ptr cinfo) ); -EXTERN void jpeg_suppress_tables JPP( ( j_compress_ptr cinfo, - boolean suppress ) ); -EXTERN JQUANT_TBL * jpeg_alloc_quant_table JPP( (j_common_ptr cinfo) ); -EXTERN JHUFF_TBL * jpeg_alloc_huff_table JPP( (j_common_ptr cinfo) ); - -/* Main entry points for compression */ -EXTERN void jpeg_start_compress JPP( ( j_compress_ptr cinfo, - boolean write_all_tables ) ); -EXTERN JDIMENSION jpeg_write_scanlines JPP( ( j_compress_ptr cinfo, - JSAMPARRAY scanlines, - JDIMENSION num_lines ) ); -EXTERN void jpeg_finish_compress JPP( (j_compress_ptr cinfo) ); - -/* Replaces jpeg_write_scanlines when writing raw downsampled data. */ -EXTERN JDIMENSION jpeg_write_raw_data JPP( ( j_compress_ptr cinfo, - JSAMPIMAGE data, - JDIMENSION num_lines ) ); - -/* Write a special marker. See libjpeg.doc concerning safe usage. */ -EXTERN void jpeg_write_marker JPP( ( j_compress_ptr cinfo, int marker, - const JOCTET * dataptr, unsigned int datalen ) ); - -/* Alternate compression function: just write an abbreviated table file */ -EXTERN void jpeg_write_tables JPP( (j_compress_ptr cinfo) ); - -/* Decompression startup: read start of JPEG datastream to see what's there */ -EXTERN int jpeg_read_header JPP( ( j_decompress_ptr cinfo, - boolean require_image ) ); -/* Return value is one of: */ -#define JPEG_SUSPENDED 0 /* Suspended due to lack of input data */ -#define JPEG_HEADER_OK 1 /* Found valid image datastream */ -#define JPEG_HEADER_TABLES_ONLY 2 /* Found valid table-specs-only datastream */ -/* If you pass require_image = TRUE (normal case), you need not check for - * a TABLES_ONLY return code; an abbreviated file will cause an error exit. - * JPEG_SUSPENDED is only possible if you use a data source module that can - * give a suspension return (the stdio source module doesn't). - */ - -/* Main entry points for decompression */ -EXTERN boolean jpeg_start_decompress JPP( (j_decompress_ptr cinfo) ); -EXTERN JDIMENSION jpeg_read_scanlines JPP( ( j_decompress_ptr cinfo, - JSAMPARRAY scanlines, - JDIMENSION max_lines ) ); -EXTERN boolean jpeg_finish_decompress JPP( (j_decompress_ptr cinfo) ); - -/* Replaces jpeg_read_scanlines when reading raw downsampled data. */ -EXTERN JDIMENSION jpeg_read_raw_data JPP( ( j_decompress_ptr cinfo, - JSAMPIMAGE data, - JDIMENSION max_lines ) ); - -/* Additional entry points for buffered-image mode. */ -EXTERN boolean jpeg_has_multiple_scans JPP( (j_decompress_ptr cinfo) ); -EXTERN boolean jpeg_start_output JPP( ( j_decompress_ptr cinfo, - int scan_number ) ); -EXTERN boolean jpeg_finish_output JPP( (j_decompress_ptr cinfo) ); -EXTERN boolean jpeg_input_complete JPP( (j_decompress_ptr cinfo) ); -EXTERN void jpeg_new_colormap JPP( (j_decompress_ptr cinfo) ); -EXTERN int jpeg_consume_input JPP( (j_decompress_ptr cinfo) ); -/* Return value is one of: */ -/* #define JPEG_SUSPENDED 0 Suspended due to lack of input data */ -#define JPEG_REACHED_SOS 1 /* Reached start of new scan */ -#define JPEG_REACHED_EOI 2 /* Reached end of image */ -#define JPEG_ROW_COMPLETED 3 /* Completed one iMCU row */ -#define JPEG_SCAN_COMPLETED 4 /* Completed last iMCU row of a scan */ - -/* Precalculate output dimensions for current decompression parameters. */ -EXTERN void jpeg_calc_output_dimensions JPP( (j_decompress_ptr cinfo) ); - -/* Install a special processing method for COM or APPn markers. */ -EXTERN void jpeg_set_marker_processor JPP( ( j_decompress_ptr cinfo, - int marker_code, - jpeg_marker_parser_method routine ) ); - -/* Read or write raw DCT coefficients --- useful for lossless transcoding. */ -EXTERN jvirt_barray_ptr * jpeg_read_coefficients JPP( (j_decompress_ptr cinfo) ); -EXTERN void jpeg_write_coefficients JPP( ( j_compress_ptr cinfo, - jvirt_barray_ptr * coef_arrays ) ); -EXTERN void jpeg_copy_critical_parameters JPP( ( j_decompress_ptr srcinfo, - j_compress_ptr dstinfo ) ); - -/* If you choose to abort compression or decompression before completing - * jpeg_finish_(de)compress, then you need to clean up to release memory, - * temporary files, etc. You can just call jpeg_destroy_(de)compress - * if you're done with the JPEG object, but if you want to clean it up and - * reuse it, call this: - */ -EXTERN void jpeg_abort_compress JPP( (j_compress_ptr cinfo) ); -EXTERN void jpeg_abort_decompress JPP( (j_decompress_ptr cinfo) ); - -/* Generic versions of jpeg_abort and jpeg_destroy that work on either - * flavor of JPEG object. These may be more convenient in some places. - */ -EXTERN void jpeg_abort JPP( (j_common_ptr cinfo) ); -EXTERN void jpeg_destroy JPP( (j_common_ptr cinfo) ); - -/* Default restart-marker-resync procedure for use by data source modules */ -EXTERN boolean jpeg_resync_to_restart JPP( ( j_decompress_ptr cinfo, - int desired ) ); - - -/* These marker codes are exported since applications and data source modules - * are likely to want to use them. - */ - -#define JPEG_RST0 0xD0 /* RST0 marker code */ -#define JPEG_EOI 0xD9 /* EOI marker code */ -#define JPEG_APP0 0xE0 /* APP0 marker code */ -#define JPEG_COM 0xFE /* COM marker code */ - - -/* If we have a brain-damaged compiler that emits warnings (or worse, errors) - * for structure definitions that are never filled in, keep it quiet by - * supplying dummy definitions for the various substructures. - */ - -#ifdef INCOMPLETE_TYPES_BROKEN -#ifndef JPEG_INTERNALS /* will be defined in jpegint.h */ -struct jvirt_sarray_control { long dummy; }; -struct jvirt_barray_control { long dummy; }; -struct jpeg_comp_master { long dummy; }; -struct jpeg_c_main_controller { long dummy; }; -struct jpeg_c_prep_controller { long dummy; }; -struct jpeg_c_coef_controller { long dummy; }; -struct jpeg_marker_writer { long dummy; }; -struct jpeg_color_converter { long dummy; }; -struct jpeg_downsampler { long dummy; }; -struct jpeg_forward_dct { long dummy; }; -struct jpeg_entropy_encoder { long dummy; }; -struct jpeg_decomp_master { long dummy; }; -struct jpeg_d_main_controller { long dummy; }; -struct jpeg_d_coef_controller { long dummy; }; -struct jpeg_d_post_controller { long dummy; }; -struct jpeg_input_controller { long dummy; }; -struct jpeg_marker_reader { long dummy; }; -struct jpeg_entropy_decoder { long dummy; }; -struct jpeg_inverse_dct { long dummy; }; -struct jpeg_upsampler { long dummy; }; -struct jpeg_color_deconverter { long dummy; }; -struct jpeg_color_quantizer { long dummy; }; -#endif /* JPEG_INTERNALS */ -#endif /* INCOMPLETE_TYPES_BROKEN */ - - -/* - * The JPEG library modules define JPEG_INTERNALS before including this file. - * The internal structure declarations are read only when that is true. - * Applications using the library should not include jpegint.h, but may wish - * to include jerror.h. - */ - -#ifdef JPEG_INTERNALS -#include "jpegint.h" /* fetch private declarations */ -#include "jerror.h" /* fetch error codes too */ -#endif - -#ifdef __cplusplus -} -#endif - -#endif /* JPEGLIB_H */ diff --git a/tools/urt/libs/render.cpp b/tools/urt/libs/render.cpp deleted file mode 100644 index d7f765b..0000000 --- a/tools/urt/libs/render.cpp +++ /dev/null @@ -1,2 +0,0 @@ - -#include "render.h" diff --git a/tools/urt/libs/render.h b/tools/urt/libs/render.h deleted file mode 100644 index 4005d6c..0000000 --- a/tools/urt/libs/render.h +++ /dev/null @@ -1,1171 +0,0 @@ - -#if !defined( INCLUDED_RENDER_H ) -#define INCLUDED_RENDER_H - -/// \file -/// \brief High-level constructs for efficient OpenGL rendering. - -#include "irender.h" -#include "igl.h" - -#include "container/array.h" -#include "math/vector.h" -#include "math/pi.h" - -#include - -typedef unsigned int RenderIndex; -const GLenum RenderIndexTypeID = GL_UNSIGNED_INT; - -/// \brief A resizable buffer of indices. -class IndexBuffer -{ -typedef std::vector Indices; -Indices m_data; -public: -typedef Indices::iterator iterator; -typedef Indices::const_iterator const_iterator; - -iterator begin(){ - return m_data.begin(); -} -const_iterator begin() const { - return m_data.begin(); -} -iterator end(){ - return m_data.end(); -} -const_iterator end() const { - return m_data.end(); -} - -bool empty() const { - return m_data.empty(); -} -std::size_t size() const { - return m_data.size(); -} -const RenderIndex* data() const { - return &( *m_data.begin() ); -} -RenderIndex& operator[]( std::size_t index ){ - return m_data[index]; -} -const RenderIndex& operator[]( std::size_t index ) const { - return m_data[index]; -} -void clear(){ - m_data.clear(); -} -void reserve( std::size_t max_indices ){ - m_data.reserve( max_indices ); -} -void insert( RenderIndex index ){ - m_data.push_back( index ); -} -void swap( IndexBuffer& other ){ - std::swap( m_data, m_data ); -} -}; - -namespace std -{ -/// \brief Swaps the values of \p self and \p other. -/// Overloads std::swap. -inline void swap( IndexBuffer& self, IndexBuffer& other ){ - self.swap( other ); -} -} - -/// \brief A resizable buffer of vertices. -/// \param Vertex The vertex data type. -template -class VertexBuffer -{ -typedef typename std::vector Vertices; -Vertices m_data; -public: -typedef typename Vertices::iterator iterator; -typedef typename Vertices::const_iterator const_iterator; - -iterator begin(){ - return m_data.begin(); -} -iterator end(){ - return m_data.end(); -} -const_iterator begin() const { - return m_data.begin(); -} -const_iterator end() const { - return m_data.end(); -} - -bool empty() const { - return m_data.empty(); -} -RenderIndex size() const { - return RenderIndex( m_data.size() ); -} -const Vertex* data() const { - return &( *m_data.begin() ); -} -Vertex& operator[]( std::size_t index ){ - return m_data[index]; -} -const Vertex& operator[]( std::size_t index ) const { - return m_data[index]; -} - -void clear(){ - m_data.clear(); -} -void reserve( std::size_t max_vertices ){ - m_data.reserve( max_vertices ); -} -void push_back( const Vertex& vertex ){ - m_data.push_back( vertex ); -} -}; - -/// \brief A wrapper around a VertexBuffer which inserts only vertices which have not already been inserted. -/// \param Vertex The vertex data type. Must support operator<, operator== and operator!=. -/// For best performance, quantise vertices before inserting them. -template -class UniqueVertexBuffer -{ -typedef VertexBuffer Vertices; -Vertices& m_data; - -struct bnode -{ - bnode() - : m_left( 0 ), m_right( 0 ){ - } - RenderIndex m_left; - RenderIndex m_right; -}; - -std::vector m_btree; -RenderIndex m_prev0; -RenderIndex m_prev1; -RenderIndex m_prev2; - -const RenderIndex find_or_insert( const Vertex& vertex ){ - RenderIndex index = 0; - - while ( 1 ) - { - if ( vertex < m_data[index] ) { - bnode& node = m_btree[index]; - if ( node.m_left != 0 ) { - index = node.m_left; - continue; - } - else - { - node.m_left = RenderIndex( m_btree.size() ); - m_btree.push_back( bnode() ); - m_data.push_back( vertex ); - return RenderIndex( m_btree.size() - 1 ); - } - } - if ( m_data[index] < vertex ) { - bnode& node = m_btree[index]; - if ( node.m_right != 0 ) { - index = node.m_right; - continue; - } - else - { - node.m_right = RenderIndex( m_btree.size() ); - m_btree.push_back( bnode() ); - m_data.push_back( vertex ); - return RenderIndex( m_btree.size() - 1 ); - } - } - - return index; - } -} -public: -UniqueVertexBuffer( Vertices& data ) - : m_data( data ), m_prev0( 0 ), m_prev1( 0 ), m_prev2( 0 ){ -} - -typedef typename Vertices::const_iterator iterator; - -iterator begin() const { - return m_data.begin(); -} -iterator end() const { - return m_data.end(); -} - -std::size_t size() const { - return m_data.size(); -} -const Vertex* data() const { - return &( *m_data.begin() ); -} -Vertex& operator[]( std::size_t index ){ - return m_data[index]; -} -const Vertex& operator[]( std::size_t index ) const { - return m_data[index]; -} - -void clear(){ - m_prev0 = 0; - m_prev1 = 0; - m_prev2 = 0; - m_data.clear(); - m_btree.clear(); -} -void reserve( std::size_t max_vertices ){ - m_data.reserve( max_vertices ); - m_btree.reserve( max_vertices ); -} -/// \brief Returns the index of the element equal to \p vertex. -RenderIndex insert( const Vertex& vertex ){ - if ( m_data.empty() ) { - m_data.push_back( vertex ); - m_btree.push_back( bnode() ); - return 0; - } - - if ( m_data[m_prev0] == vertex ) { - return m_prev0; - } - if ( m_prev1 != m_prev0 && m_data[m_prev1] == vertex ) { - return m_prev1; - } - if ( m_prev2 != m_prev0 && m_prev2 != m_prev1 && m_data[m_prev2] == vertex ) { - return m_prev2; - } - - m_prev2 = m_prev1; - m_prev1 = m_prev0; - m_prev0 = find_or_insert( vertex ); - - return m_prev0; -} -}; - - -/// \brief A 4-byte colour. -struct Colour4b -{ - unsigned char r, g, b, a; - - Colour4b(){ - } - - Colour4b( unsigned char _r, unsigned char _g, unsigned char _b, unsigned char _a ) - : r( _r ), g( _g ), b( _b ), a( _a ){ - } -}; - -inline bool operator<( const Colour4b& self, const Colour4b& other ){ - if ( self.r != other.r ) { - return self.r < other.r; - } - if ( self.g != other.g ) { - return self.g < other.g; - } - if ( self.b != other.b ) { - return self.b < other.b; - } - if ( self.a != other.a ) { - return self.a < other.a; - } - return false; -} - -inline bool operator==( const Colour4b& self, const Colour4b& other ){ - return self.r == other.r && self.g == other.g && self.b == other.b && self.a == other.a; -} - -inline bool operator!=( const Colour4b& self, const Colour4b& other ){ - return !operator==( self, other ); -} - -/// \brief A 3-float vertex. -struct Vertex3f -{ - float x, y, z; - - Vertex3f(){ - } - - Vertex3f( float _x, float _y, float _z ) - : x( _x ), y( _y ), z( _z ){ - } -}; - -inline bool operator<( const Vertex3f& self, const Vertex3f& other ){ - if ( self.x != other.x ) { - return self.x < other.x; - } - if ( self.y != other.y ) { - return self.y < other.y; - } - if ( self.z != other.z ) { - return self.z < other.z; - } - return false; -} - -inline bool operator==( const Vertex3f& self, const Vertex3f& other ){ - return self.x == other.x && self.y == other.y && self.z == other.z; -} - -inline bool operator!=( const Vertex3f& self, const Vertex3f& other ){ - return !operator==( self, other ); -} - - -inline const Vertex3f& vertex3f_from_array( const float* array ){ - return *reinterpret_cast( array ); -} - -inline float* vertex3f_to_array( Vertex3f& vertex ){ - return reinterpret_cast( &vertex ); -} - -inline const float* vertex3f_to_array( const Vertex3f& vertex ){ - return reinterpret_cast( &vertex ); -} - -const Vertex3f vertex3f_identity( 0, 0, 0 ); - -inline Vertex3f vertex3f_for_vector3( const Vector3& vector3 ){ - return Vertex3f( vector3.x(), vector3.y(), vector3.z() ); -} - -inline const Vector3& vertex3f_to_vector3( const Vertex3f& vertex ){ - return reinterpret_cast( vertex ); -} - -inline Vector3& vertex3f_to_vector3( Vertex3f& vertex ){ - return reinterpret_cast( vertex ); -} - - -/// \brief A 3-float normal. -struct Normal3f -{ - float x, y, z; - - Normal3f(){ - } - - Normal3f( float _x, float _y, float _z ) - : x( _x ), y( _y ), z( _z ){ - } -}; - -inline bool operator<( const Normal3f& self, const Normal3f& other ){ - if ( self.x != other.x ) { - return self.x < other.x; - } - if ( self.y != other.y ) { - return self.y < other.y; - } - if ( self.z != other.z ) { - return self.z < other.z; - } - return false; -} - -inline bool operator==( const Normal3f& self, const Normal3f& other ){ - return self.x == other.x && self.y == other.y && self.z == other.z; -} - -inline bool operator!=( const Normal3f& self, const Normal3f& other ){ - return !operator==( self, other ); -} - - -inline Normal3f normal3f_from_array( const float* array ){ - return Normal3f( array[0], array[1], array[2] ); -} - -inline float* normal3f_to_array( Normal3f& normal ){ - return reinterpret_cast( &normal ); -} - -inline const float* normal3f_to_array( const Normal3f& normal ){ - return reinterpret_cast( &normal ); -} - -inline Normal3f normal3f_for_vector3( const Vector3& vector3 ){ - return Normal3f( vector3.x(), vector3.y(), vector3.z() ); -} - -inline const Vector3& normal3f_to_vector3( const Normal3f& normal ){ - return reinterpret_cast( normal ); -} - -inline Vector3& normal3f_to_vector3( Normal3f& normal ){ - return reinterpret_cast( normal ); -} - - -/// \brief A 2-float texture-coordinate set. -struct TexCoord2f -{ - float s, t; - - TexCoord2f(){ - } - - TexCoord2f( float _s, float _t ) - : s( _s ), t( _t ){ - } -}; - -inline bool operator<( const TexCoord2f& self, const TexCoord2f& other ){ - if ( self.s != other.s ) { - return self.s < other.s; - } - if ( self.t != other.t ) { - return self.t < other.t; - } - return false; -} - -inline bool operator==( const TexCoord2f& self, const TexCoord2f& other ){ - return self.s == other.s && self.t == other.t; -} - -inline bool operator!=( const TexCoord2f& self, const TexCoord2f& other ){ - return !operator==( self, other ); -} - - -inline float* texcoord2f_to_array( TexCoord2f& texcoord ){ - return reinterpret_cast( &texcoord ); -} - -inline const float* texcoord2f_to_array( const TexCoord2f& texcoord ){ - return reinterpret_cast( &texcoord ); -} - -inline const TexCoord2f& texcoord2f_from_array( const float* array ){ - return *reinterpret_cast( array ); -} - -inline TexCoord2f texcoord2f_for_vector2( const Vector2& vector2 ){ - return TexCoord2f( vector2.x(), vector2.y() ); -} - -inline const Vector2& texcoord2f_to_vector2( const TexCoord2f& vertex ){ - return reinterpret_cast( vertex ); -} - -inline Vector2& texcoord2f_to_vector2( TexCoord2f& vertex ){ - return reinterpret_cast( vertex ); -} - -/// \brief Returns \p normal rescaled to be unit-length. -inline Normal3f normal3f_normalised( const Normal3f& normal ){ - return normal3f_for_vector3( vector3_normalised( normal3f_to_vector3( normal ) ) ); -} - -enum UnitSphereOctant -{ - UNITSPHEREOCTANT_000 = 0 << 0 | 0 << 1 | 0 << 2, - UNITSPHEREOCTANT_001 = 0 << 0 | 0 << 1 | 1 << 2, - UNITSPHEREOCTANT_010 = 0 << 0 | 1 << 1 | 0 << 2, - UNITSPHEREOCTANT_011 = 0 << 0 | 1 << 1 | 1 << 2, - UNITSPHEREOCTANT_100 = 1 << 0 | 0 << 1 | 0 << 2, - UNITSPHEREOCTANT_101 = 1 << 0 | 0 << 1 | 1 << 2, - UNITSPHEREOCTANT_110 = 1 << 0 | 1 << 1 | 0 << 2, - UNITSPHEREOCTANT_111 = 1 << 0 | 1 << 1 | 1 << 2, -}; - -/// \brief Returns the octant for \p normal indicating the sign of the region of unit-sphere space it lies within. -inline UnitSphereOctant normal3f_classify_octant( const Normal3f& normal ){ - return static_cast( - ( ( normal.x > 0 ) << 0 ) | ( ( normal.y > 0 ) << 1 ) | ( ( normal.z > 0 ) << 2 ) - ); -} - -/// \brief Returns \p normal with its components signs made positive based on \p octant. -inline Normal3f normal3f_fold_octant( const Normal3f& normal, UnitSphereOctant octant ){ - switch ( octant ) - { - case UNITSPHEREOCTANT_000: - return Normal3f( -normal.x, -normal.y, -normal.z ); - case UNITSPHEREOCTANT_001: - return Normal3f( normal.x, -normal.y, -normal.z ); - case UNITSPHEREOCTANT_010: - return Normal3f( -normal.x, normal.y, -normal.z ); - case UNITSPHEREOCTANT_011: - return Normal3f( normal.x, normal.y, -normal.z ); - case UNITSPHEREOCTANT_100: - return Normal3f( -normal.x, -normal.y, normal.z ); - case UNITSPHEREOCTANT_101: - return Normal3f( normal.x, -normal.y, normal.z ); - case UNITSPHEREOCTANT_110: - return Normal3f( -normal.x, normal.y, normal.z ); - case UNITSPHEREOCTANT_111: - return Normal3f( normal.x, normal.y, normal.z ); - } - return Normal3f(); -} - -/// \brief Reverses the effect of normal3f_fold_octant() on \p normal with \p octant. -/// \p normal must have been obtained with normal3f_fold_octant(). -/// \p octant must have been obtained with normal3f_classify_octant(). -inline Normal3f normal3f_unfold_octant( const Normal3f& normal, UnitSphereOctant octant ){ - return normal3f_fold_octant( normal, octant ); -} - -enum UnitSphereSextant -{ - UNITSPHERESEXTANT_XYZ = 0, - UNITSPHERESEXTANT_XZY = 1, - UNITSPHERESEXTANT_YXZ = 2, - UNITSPHERESEXTANT_YZX = 3, - UNITSPHERESEXTANT_ZXY = 4, - UNITSPHERESEXTANT_ZYX = 5, -}; - -/// \brief Returns the sextant for \p normal indicating how to sort its components so that x > y > z. -/// All components of \p normal must be positive. -/// \p normal must be normalised. -inline UnitSphereSextant normal3f_classify_sextant( const Normal3f& normal ){ - return - normal.x >= normal.y - ? normal.x >= normal.z - ? normal.y >= normal.z - ? UNITSPHERESEXTANT_XYZ - : UNITSPHERESEXTANT_XZY - : UNITSPHERESEXTANT_ZXY - : normal.y >= normal.z - ? normal.x >= normal.z - ? UNITSPHERESEXTANT_YXZ - : UNITSPHERESEXTANT_YZX - : UNITSPHERESEXTANT_ZYX; -} - -/// \brief Returns \p normal with its components sorted so that x > y > z based on \p sextant. -/// All components of \p normal must be positive. -/// \p normal must be normalised. -inline Normal3f normal3f_fold_sextant( const Normal3f& normal, UnitSphereSextant sextant ){ - switch ( sextant ) - { - case UNITSPHERESEXTANT_XYZ: - return Normal3f( normal.x, normal.y, normal.z ); - case UNITSPHERESEXTANT_XZY: - return Normal3f( normal.x, normal.z, normal.y ); - case UNITSPHERESEXTANT_YXZ: - return Normal3f( normal.y, normal.x, normal.z ); - case UNITSPHERESEXTANT_YZX: - return Normal3f( normal.y, normal.z, normal.x ); - case UNITSPHERESEXTANT_ZXY: - return Normal3f( normal.z, normal.x, normal.y ); - case UNITSPHERESEXTANT_ZYX: - return Normal3f( normal.z, normal.y, normal.x ); - } - return Normal3f(); -} - -/// \brief Reverses the effect of normal3f_fold_sextant() on \p normal with \p sextant. -/// \p normal must have been obtained with normal3f_fold_sextant(). -/// \p sextant must have been obtained with normal3f_classify_sextant(). -inline Normal3f normal3f_unfold_sextant( const Normal3f& normal, UnitSphereSextant sextant ){ - return normal3f_fold_sextant( normal, sextant ); -} - -const std::size_t c_quantise_normal = 1 << 6; - -/// \brief All the components of \p folded must be positive and sorted so that x > y > z. -inline Normal3f normal3f_folded_quantised( const Normal3f& folded ){ - // compress - double scale = static_cast( c_quantise_normal ) / ( folded.x + folded.y + folded.z ); - unsigned int zbits = static_cast( folded.z * scale ); - unsigned int ybits = static_cast( folded.y * scale ); - - // decompress - return normal3f_normalised( Normal3f( - static_cast( c_quantise_normal - zbits - ybits ), - static_cast( ybits ), - static_cast( zbits ) - ) ); -} - -/// \brief Returns \p normal quantised by compressing and then decompressing its representation. -inline Normal3f normal3f_quantised_custom( const Normal3f& normal ){ - UnitSphereOctant octant = normal3f_classify_octant( normal ); - Normal3f folded = normal3f_fold_octant( normal, octant ); - UnitSphereSextant sextant = normal3f_classify_sextant( folded ); - folded = normal3f_fold_sextant( folded, sextant ); - return normal3f_unfold_octant( normal3f_unfold_sextant( normal3f_folded_quantised( folded ), sextant ), octant ); -} - - - -struct spherical_t -{ - double longditude, latitude; - - spherical_t( double _longditude, double _latitude ) - : longditude( _longditude ), latitude( _latitude ){ - } -}; - -/* - { - theta = 2pi * U; - phi = acos((2 * V) - 1); - - U = theta / 2pi; - V = (cos(phi) + 1) / 2; - } - - longitude = atan(y / x); - latitude = acos(z); - */ -struct uniformspherical_t -{ - double U, V; - - uniformspherical_t( double U_, double V_ ) - : U( U_ ), V( V_ ){ - } -}; - - -inline spherical_t spherical_from_normal3f( const Normal3f& normal ){ - return spherical_t( normal.x == 0 ? c_pi / 2 : normal.x > 0 ? atan( normal.y / normal.x ) : atan( normal.y / normal.x ) + c_pi, acos( normal.z ) ); -} - -inline Normal3f normal3f_from_spherical( const spherical_t& spherical ){ - return Normal3f( - static_cast( cos( spherical.longditude ) * sin( spherical.latitude ) ), - static_cast( sin( spherical.longditude ) * sin( spherical.latitude ) ), - static_cast( cos( spherical.latitude ) ) - ); -} - -inline uniformspherical_t uniformspherical_from_spherical( const spherical_t& spherical ){ - return uniformspherical_t( spherical.longditude * c_inv_2pi, ( cos( spherical.latitude ) + 1 ) * 0.5 ); -} - -inline spherical_t spherical_from_uniformspherical( const uniformspherical_t& uniformspherical ){ - return spherical_t( c_2pi * uniformspherical.U, acos( ( 2 * uniformspherical.V ) - 1 ) ); -} - -inline uniformspherical_t uniformspherical_from_normal3f( const Normal3f& normal ){ - return uniformspherical_from_spherical( spherical_from_normal3f( normal ) ); - //return uniformspherical_t(atan2(normal.y / normal.x) * c_inv_2pi, (normal.z + 1) * 0.5); -} - -inline Normal3f normal3f_from_uniformspherical( const uniformspherical_t& uniformspherical ){ - return normal3f_from_spherical( spherical_from_uniformspherical( uniformspherical ) ); -} - -/// \brief Returns a single-precision \p component quantised to \p precision. -inline float float_quantise( float component, float precision ){ - return float_snapped( component, precision ); -} - -/// \brief Returns a double-precision \p component quantised to \p precision. -inline double double_quantise( double component, double precision ){ - return float_snapped( component, precision ); -} - -inline spherical_t spherical_quantised( const spherical_t& spherical, float snap ){ - return spherical_t( double_quantise( spherical.longditude, snap ), double_quantise( spherical.latitude, snap ) ); -} - -inline uniformspherical_t uniformspherical_quantised( const uniformspherical_t& uniformspherical, float snap ){ - return uniformspherical_t( double_quantise( uniformspherical.U, snap ), double_quantise( uniformspherical.V, snap ) ); -} - -/// \brief Returns a \p vertex quantised to \p precision. -inline Vertex3f vertex3f_quantised( const Vertex3f& vertex, float precision ){ - return Vertex3f( float_quantise( vertex.x, precision ), float_quantise( vertex.y, precision ), float_quantise( vertex.z, precision ) ); -} - -/// \brief Returns a \p normal quantised to a fixed precision. -inline Normal3f normal3f_quantised( const Normal3f& normal ){ - return normal3f_quantised_custom( normal ); - //return normal3f_from_spherical(spherical_quantised(spherical_from_normal3f(normal), snap)); - //return normal3f_from_uniformspherical(uniformspherical_quantised(uniformspherical_from_normal3f(normal), snap)); - // float_quantise(normal.x, snap), float_quantise(normal.y, snap), float_quantise(normal.y, snap)); -} - -/// \brief Returns a \p texcoord quantised to \p precision. -inline TexCoord2f texcoord2f_quantised( const TexCoord2f& texcoord, float precision ){ - return TexCoord2f( float_quantise( texcoord.s, precision ), float_quantise( texcoord.t, precision ) ); -} - -/// \brief Standard vertex type for lines and points. -struct PointVertex -{ - Colour4b colour; - Vertex3f vertex; - - PointVertex(){ - } - PointVertex( Vertex3f _vertex ) - : colour( Colour4b( 255, 255, 255, 255 ) ), vertex( _vertex ){ - } - PointVertex( Vertex3f _vertex, Colour4b _colour ) - : colour( _colour ), vertex( _vertex ){ - } -}; - -inline bool operator<( const PointVertex& self, const PointVertex& other ){ - if ( self.vertex != other.vertex ) { - return self.vertex < other.vertex; - } - if ( self.colour != other.colour ) { - return self.colour < other.colour; - } - return false; -} - -inline bool operator==( const PointVertex& self, const PointVertex& other ){ - return self.colour == other.colour && self.vertex == other.vertex; -} - -inline bool operator!=( const PointVertex& self, const PointVertex& other ){ - return !operator==( self, other ); -} - -/// \brief Standard vertex type for lit/textured meshes. -struct ArbitraryMeshVertex -{ - TexCoord2f texcoord; - Normal3f normal; - Vertex3f vertex; - Normal3f tangent; - Normal3f bitangent; - - ArbitraryMeshVertex() : tangent( 0, 0, 0 ), bitangent( 0, 0, 0 ){ - } - ArbitraryMeshVertex( Vertex3f _vertex, Normal3f _normal, TexCoord2f _texcoord ) - : texcoord( _texcoord ), normal( _normal ), vertex( _vertex ), tangent( 0, 0, 0 ), bitangent( 0, 0, 0 ){ - } -}; - -inline bool operator<( const ArbitraryMeshVertex& self, const ArbitraryMeshVertex& other ){ - if ( self.texcoord != other.texcoord ) { - return self.texcoord < other.texcoord; - } - if ( self.normal != other.normal ) { - return self.normal < other.normal; - } - if ( self.vertex != other.vertex ) { - return self.vertex < other.vertex; - } - return false; -} - -inline bool operator==( const ArbitraryMeshVertex& self, const ArbitraryMeshVertex& other ){ - return self.texcoord == other.texcoord && self.normal == other.normal && self.vertex == other.vertex; -} - -inline bool operator!=( const ArbitraryMeshVertex& self, const ArbitraryMeshVertex& other ){ - return !operator==( self, other ); -} - -const float c_quantise_vertex = 1.f / static_cast( 1 << 3 ); - -/// \brief Returns \p v with vertex quantised to a fixed precision. -inline PointVertex pointvertex_quantised( const PointVertex& v ){ - return PointVertex( vertex3f_quantised( v.vertex, c_quantise_vertex ), v.colour ); -} - -const float c_quantise_texcoord = 1.f / static_cast( 1 << 8 ); - -/// \brief Returns \p v with vertex, normal and texcoord quantised to a fixed precision. -inline ArbitraryMeshVertex arbitrarymeshvertex_quantised( const ArbitraryMeshVertex& v ){ - return ArbitraryMeshVertex( vertex3f_quantised( v.vertex, c_quantise_vertex ), normal3f_quantised( v.normal ), texcoord2f_quantised( v.texcoord, c_quantise_texcoord ) ); -} - - -/// \brief Sets up the OpenGL colour and vertex arrays for \p array. -inline void pointvertex_gl_array( const PointVertex* array ){ - glColorPointer( 4, GL_UNSIGNED_BYTE, sizeof( PointVertex ), &array->colour ); - glVertexPointer( 3, GL_FLOAT, sizeof( PointVertex ), &array->vertex ); -} - -class RenderablePointArray : public OpenGLRenderable -{ -const Array& m_array; -const GLenum m_mode; -public: -RenderablePointArray( const Array& array, GLenum mode ) - : m_array( array ), m_mode( mode ){ -} -void render( RenderStateFlags state ) const { -#define NV_DRIVER_BUG 1 -#if NV_DRIVER_BUG - glColorPointer( 4, GL_UNSIGNED_BYTE, 0, 0 ); - glVertexPointer( 3, GL_FLOAT, 0, 0 ); - glDrawArrays( GL_TRIANGLE_FAN, 0, 0 ); -#endif - pointvertex_gl_array( m_array.data() ); - glDrawArrays( m_mode, 0, GLsizei( m_array.size() ) ); -} -}; - -class RenderablePointVector : public OpenGLRenderable -{ -std::vector m_vector; -const GLenum m_mode; -public: -RenderablePointVector( GLenum mode ) - : m_mode( mode ){ -} - -void render( RenderStateFlags state ) const { - pointvertex_gl_array( &m_vector.front() ); - glDrawArrays( m_mode, 0, GLsizei( m_vector.size() ) ); -} - -std::size_t size() const { - return m_vector.size(); -} -bool empty() const { - return m_vector.empty(); -} -void clear(){ - m_vector.clear(); -} -void reserve( std::size_t size ){ - m_vector.reserve( size ); -} -void push_back( const PointVertex& point ){ - m_vector.push_back( point ); -} -}; - - -class RenderableVertexBuffer : public OpenGLRenderable -{ -const GLenum m_mode; -const VertexBuffer& m_vertices; -public: -RenderableVertexBuffer( GLenum mode, const VertexBuffer& vertices ) - : m_mode( mode ), m_vertices( vertices ){ -} - -void render( RenderStateFlags state ) const { - pointvertex_gl_array( m_vertices.data() ); - glDrawArrays( m_mode, 0, m_vertices.size() ); -} -}; - -class RenderableIndexBuffer : public OpenGLRenderable -{ -const GLenum m_mode; -const IndexBuffer& m_indices; -const VertexBuffer& m_vertices; -public: -RenderableIndexBuffer( GLenum mode, const IndexBuffer& indices, const VertexBuffer& vertices ) - : m_mode( mode ), m_indices( indices ), m_vertices( vertices ){ -} - -void render( RenderStateFlags state ) const { -#if 1 - pointvertex_gl_array( m_vertices.data() ); - glDrawElements( m_mode, GLsizei( m_indices.size() ), RenderIndexTypeID, m_indices.data() ); -#else - glBegin( m_mode ); - if ( state & RENDER_COLOUR != 0 ) { - for ( std::size_t i = 0; i < m_indices.size(); ++i ) - { - glColor4ubv( &m_vertices[m_indices[i]].colour.r ); - glVertex3fv( &m_vertices[m_indices[i]].vertex.x ); - } - } - else - { - for ( std::size_t i = 0; i < m_indices.size(); ++i ) - { - glVertex3fv( &m_vertices[m_indices[i]].vertex.x ); - } - } - glEnd(); -#endif -} -}; - - -class RemapXYZ -{ -public: -static void set( Vertex3f& vertex, float x, float y, float z ){ - vertex.x = x; - vertex.y = y; - vertex.z = z; -} -}; - -class RemapYZX -{ -public: -static void set( Vertex3f& vertex, float x, float y, float z ){ - vertex.x = z; - vertex.y = x; - vertex.z = y; -} -}; - -class RemapZXY -{ -public: -static void set( Vertex3f& vertex, float x, float y, float z ){ - vertex.x = y; - vertex.y = z; - vertex.z = x; -} -}; - -template -inline void draw_circle( const std::size_t segments, const float radius, PointVertex* vertices, remap_policy remap ){ - const double increment = c_pi / double(segments << 2); - - std::size_t count = 0; - float x = radius; - float y = 0; - while ( count < segments ) - { - PointVertex* i = vertices + count; - PointVertex* j = vertices + ( ( segments << 1 ) - ( count + 1 ) ); - - PointVertex* k = i + ( segments << 1 ); - PointVertex* l = j + ( segments << 1 ); - - PointVertex* m = i + ( segments << 2 ); - PointVertex* n = j + ( segments << 2 ); - PointVertex* o = k + ( segments << 2 ); - PointVertex* p = l + ( segments << 2 ); - - remap_policy::set( i->vertex, x,-y, 0 ); - remap_policy::set( k->vertex,-y,-x, 0 ); - remap_policy::set( m->vertex,-x, y, 0 ); - remap_policy::set( o->vertex, y, x, 0 ); - - ++count; - - { - const double theta = increment * count; - x = static_cast( radius * cos( theta ) ); - y = static_cast( radius * sin( theta ) ); - } - - remap_policy::set( j->vertex, y,-x, 0 ); - remap_policy::set( l->vertex,-x,-y, 0 ); - remap_policy::set( n->vertex,-y, x, 0 ); - remap_policy::set( p->vertex, x, y, 0 ); - } -} - -#if 0 -class PointVertexArrayIterator -{ -PointVertex* m_point; -public: -PointVertexArrayIterator( PointVertex* point ) - : m_point( point ){ -} -PointVertexArrayIterator& operator++(){ - ++m_point; - return *this; -} -PointVertexArrayIterator operator++( int ){ - PointVertexArrayIterator tmp( *this ); - ++m_point; - return tmp; -} -Vertex3f& operator*(){ - return m_point.vertex; -} -Vertex3f* operator->(){ - return &( operator*() ); -} -} - -template 0.000001f ) { - s.x() = -cross.y() / cross.x(); - } - - if ( fabs( cross.x() ) > 0.000001f ) { - t.x() = -cross.z() / cross.x(); - } - } - - { - Vector3 cross( - vector3_cross( - vector3_subtracted( - Vector3( b.vertex.y, b.texcoord.s, b.texcoord.t ), - Vector3( a.vertex.y, a.texcoord.s, a.texcoord.t ) - ), - vector3_subtracted( - Vector3( c.vertex.y, c.texcoord.s, c.texcoord.t ), - Vector3( a.vertex.y, a.texcoord.s, a.texcoord.t ) - ) - ) - ); - - if ( fabs( cross.x() ) > 0.000001f ) { - s.y() = -cross.y() / cross.x(); - } - - if ( fabs( cross.x() ) > 0.000001f ) { - t.y() = -cross.z() / cross.x(); - } - } - - { - Vector3 cross( - vector3_cross( - vector3_subtracted( - Vector3( b.vertex.z, b.texcoord.s, b.texcoord.t ), - Vector3( a.vertex.z, a.texcoord.s, a.texcoord.t ) - ), - vector3_subtracted( - Vector3( c.vertex.z, c.texcoord.s, c.texcoord.t ), - Vector3( a.vertex.z, a.texcoord.s, a.texcoord.t ) - ) - ) - ); - - if ( fabs( cross.x() ) > 0.000001f ) { - s.z() = -cross.y() / cross.x(); - } - - if ( fabs( cross.x() ) > 0.000001f ) { - t.z() = -cross.z() / cross.x(); - } - } -} - -inline void ArbitraryMeshTriangle_sumTangents( ArbitraryMeshVertex& a, ArbitraryMeshVertex& b, ArbitraryMeshVertex& c ){ - Vector3 s, t; - - ArbitraryMeshTriangle_calcTangents( a, b, c, s, t ); - - reinterpret_cast( a.tangent ) += s; - reinterpret_cast( b.tangent ) += s; - reinterpret_cast( c.tangent ) += s; - - reinterpret_cast( a.bitangent ) += t; - reinterpret_cast( b.bitangent ) += t; - reinterpret_cast( c.bitangent ) += t; -} - - -#endif diff --git a/tools/urt/libs/scenelib.cpp b/tools/urt/libs/scenelib.cpp deleted file mode 100644 index 0830611..0000000 --- a/tools/urt/libs/scenelib.cpp +++ /dev/null @@ -1,2 +0,0 @@ - -#include "scenelib.h" diff --git a/tools/urt/libs/scenelib.h b/tools/urt/libs/scenelib.h deleted file mode 100644 index 3ac2bec..0000000 --- a/tools/urt/libs/scenelib.h +++ /dev/null @@ -1,796 +0,0 @@ - -#if !defined ( INCLUDED_SCENELIB_H ) -#define INCLUDED_SCENELIB_H - -#include "iscenegraph.h" -#include "iselection.h" - -#include "warnings.h" -#include -#include - -#include "math/aabb.h" -#include "transformlib.h" -#include "generic/callback.h" -#include "generic/reference.h" -#include "container/stack.h" -#include "typesystem.h" - -class Selector; -class SelectionTest; -class VolumeTest; -template class BasicVector3; -typedef BasicVector3 Vector3; -class Matrix4; -class Vector4; -typedef Vector4 Quaternion; -class AABB; - -class ComponentSelectionTestable -{ -public: -static const char* getTypeName(){ - return "ComponentSelectionTestable"; -} - -virtual void setSelectedComponents( bool select, SelectionSystem::EComponentMode mode ) = 0; -virtual void testSelectComponents( Selector& selector, SelectionTest& test, SelectionSystem::EComponentMode mode ) = 0; -}; - -class ComponentEditable -{ -public: -static const char* getTypeName(){ - return "ComponentEditable"; -} - -virtual const AABB& getSelectedComponentsBounds() const = 0; -virtual void translateComponents( const Vector3& translation ) = 0; -virtual void rotateComponents( const Quaternion& rotation ) = 0; -virtual void scaleComponents( const Vector3& scaling ) = 0; -virtual void snapComponents( float snap ) = 0; -virtual void freezeComponents() = 0; -}; - -class Bounded -{ -public: -static const char* getTypeName(){ - return "Bounded"; -} - -virtual const AABB& localAABB() const = 0; -}; - -class BrushDoom3 -{ -public: -static const char* getTypeName(){ - return "BrushDoom3"; -} - -virtual void setDoom3GroupOrigin( const Vector3& origin ) = 0; -}; - - - - -typedef TypeCastTable NodeTypeCastTable; - -template -class NodeType : public StaticTypeSystemInitialiser -{ -TypeId m_typeId; -public: -static const char* getTypeName(){ - return Type::getTypeName(); -} -NodeType() : m_typeId( NODETYPEID_NONE ){ - StaticTypeSystemInitialiser::instance().addInitialiser( InitialiseCaller( *this ) ); -} -void initialise(){ - m_typeId = GlobalSceneGraph().getNodeTypeId( getTypeName() ); -} -typedef MemberCaller, &NodeType::initialise> InitialiseCaller; -TypeId getTypeId(){ -#if defined( _DEBUG ) - ASSERT_MESSAGE( m_typeId != NODETYPEID_NONE, "node-type " << makeQuoted( getTypeName() ) << " used before being initialised" ); -#endif - return m_typeId; -} -}; - -template -class StaticNodeType -{ -public: -enum { SIZE = NODETYPEID_MAX }; -static TypeId getTypeId(){ - return Static< NodeType >::instance().getTypeId(); -} -}; - -template -class NodeStaticCast : - public CastInstaller< - StaticNodeType, - StaticCast - > -{ -}; - -template -class NodeContainedCast : - public CastInstaller< - StaticNodeType, - ContainedCast - > -{ -}; - -template -class NodeIdentityCast : - public CastInstaller< - StaticNodeType, - IdentityCast - > -{ -}; - -namespace scene -{ -class Node -{ -public: -enum { eVisible = 0 }; -enum { eHidden = 1 << 0 }; -enum { eFiltered = 1 << 1 }; -enum { eExcluded = 1 << 2 }; - -class Symbiot -{ -public: -virtual void release() = 0; -}; - -private: -unsigned int m_state; -std::size_t m_refcount; -Symbiot* m_symbiot; -void* m_node; -NodeTypeCastTable& m_casts; - -public: -bool m_isRoot; - -bool isRoot(){ - return m_isRoot; -} - -Node( Symbiot* symbiot, void* node, NodeTypeCastTable& casts ) : - m_state( eVisible ), - m_refcount( 0 ), - m_symbiot( symbiot ), - m_node( node ), - m_casts( casts ), - m_isRoot( false ){ -} -~Node(){ -} - -void IncRef(){ - ASSERT_MESSAGE( m_refcount < ( 1 << 24 ), "Node::decref: uninitialised refcount" ); - ++m_refcount; -} -void DecRef(){ - ASSERT_MESSAGE( m_refcount < ( 1 << 24 ), "Node::decref: uninitialised refcount" ); - if ( --m_refcount == 0 ) { - m_symbiot->release(); - } -} -std::size_t getReferenceCount() const { - return m_refcount; -} - -void* cast( TypeId typeId ) const { - return m_casts.cast( typeId, m_node ); -} - -void enable( unsigned int state ){ - m_state |= state; -} -void disable( unsigned int state ){ - m_state &= ~state; -} -bool visible(){ - return m_state == eVisible; -} -bool excluded(){ - return ( m_state & eExcluded ) != 0; -} -}; - -class NullNode : public Node::Symbiot -{ -NodeTypeCastTable m_casts; -Node m_node; -public: -NullNode() : m_node( this, 0, m_casts ){ -} -void release(){ - delete this; -} -scene::Node& node(){ - return m_node; -} -}; -} - -template -class NodeTypeCast -{ -public: -static Type* cast( scene::Node& node ){ - return static_cast( node.cast( StaticNodeType::getTypeId() ) ); -} -static const Type* cast( const scene::Node& node ){ - return static_cast( node.cast( StaticNodeType::getTypeId() ) ); -} -}; - - -inline Transformable* Node_getTransformable( scene::Node& node ){ - return NodeTypeCast::cast( node ); -} - -inline scene::Instantiable* Node_getInstantiable( scene::Node& node ){ - return NodeTypeCast::cast( node ); -} - -inline scene::Traversable* Node_getTraversable( scene::Node& node ){ - return NodeTypeCast::cast( node ); -} - -inline void Node_traverseSubgraph( scene::Node& node, const scene::Traversable::Walker& walker ){ - if ( walker.pre( node ) ) { - scene::Traversable* traversable = Node_getTraversable( node ); - if ( traversable != 0 ) { - traversable->traverse( walker ); - } - } - walker.post( node ); -} - -inline bool operator<( scene::Node& node, scene::Node& other ){ - return &node < &other; -} -inline bool operator==( scene::Node& node, scene::Node& other ){ - return &node == &other; -} -inline bool operator!=( scene::Node& node, scene::Node& other ){ - return !::operator==( node, other ); -} - - -inline scene::Node& NewNullNode(){ - return ( new scene::NullNode )->node(); -} - -inline void Path_deleteTop( const scene::Path& path ){ - Node_getTraversable( path.parent() )->erase( path.top() ); -} - - - - - -class delete_all : public scene::Traversable::Walker -{ -scene::Node& m_parent; -public: -delete_all( scene::Node& parent ) : m_parent( parent ){ -} -bool pre( scene::Node& node ) const { - return false; -} -void post( scene::Node& node ) const { - Node_getTraversable( m_parent )->erase( node ); -} -}; - -inline void DeleteSubgraph( scene::Node& subgraph ){ - Node_getTraversable( subgraph )->traverse( delete_all( subgraph ) ); -} - - -class EntityUndefined -{ -public: -static const char* getTypeName(){ - return "Entity"; -} -}; - -inline bool Node_isEntity( scene::Node& node ){ - return NodeTypeCast::cast( node ); -} - -class BrushUndefined -{ -public: -static const char* getTypeName(){ - return "Brush"; -} -}; - -inline bool Node_isBrush( scene::Node& node ){ - return NodeTypeCast::cast( node ) != 0; -} - -class PatchUndefined -{ -public: -static const char* getTypeName(){ - return "Patch"; -} -}; - -inline bool Node_isPatch( scene::Node& node ){ - return NodeTypeCast::cast( node ) != 0; -} - -inline bool Node_isPrimitive( scene::Node& node ){ -#if 1 - return Node_isBrush( node ) || Node_isPatch( node ); -#else - return !node.isRoot(); -#endif -} - -class ParentBrushes : public scene::Traversable::Walker -{ -scene::Node& m_parent; -public: -ParentBrushes( scene::Node& parent ) - : m_parent( parent ){ -} -bool pre( scene::Node& node ) const { - return false; -} -void post( scene::Node& node ) const { - if ( Node_isPrimitive( node ) ) { - Node_getTraversable( m_parent )->insert( node ); - } -} -}; - -inline void parentBrushes( scene::Node& subgraph, scene::Node& parent ){ - Node_getTraversable( subgraph )->traverse( ParentBrushes( parent ) ); -} - -class HasBrushes : public scene::Traversable::Walker -{ -bool& m_hasBrushes; -public: -HasBrushes( bool& hasBrushes ) - : m_hasBrushes( hasBrushes ){ - m_hasBrushes = true; -} -bool pre( scene::Node& node ) const { - if ( !Node_isPrimitive( node ) ) { - m_hasBrushes = false; - } - return false; -} -}; - -inline bool node_is_group( scene::Node& node ){ - scene::Traversable* traversable = Node_getTraversable( node ); - if ( traversable != 0 ) { - bool hasBrushes = false; - traversable->traverse( HasBrushes( hasBrushes ) ); - return hasBrushes; - } - return false; -} - -typedef TypeCastTable InstanceTypeCastTable; - -template -class InstanceType : public StaticTypeSystemInitialiser -{ -TypeId m_typeId; -public: -static const char* getTypeName(){ - return Type::getTypeName(); -} -InstanceType() : m_typeId( INSTANCETYPEID_NONE ){ - StaticTypeSystemInitialiser::instance().addInitialiser( InitialiseCaller( *this ) ); -} -void initialise(){ - m_typeId = GlobalSceneGraph().getInstanceTypeId( getTypeName() ); -} -typedef MemberCaller, &InstanceType::initialise> InitialiseCaller; -TypeId getTypeId(){ -#if defined( _DEBUG ) - ASSERT_MESSAGE( m_typeId != INSTANCETYPEID_NONE, "instance-type " << makeQuoted( getTypeName() ) << " used before being initialised" ); -#endif - return m_typeId; -} -}; - -template -class StaticInstanceType -{ -public: -enum { SIZE = INSTANCETYPEID_MAX }; -static TypeId getTypeId(){ - return Static< InstanceType >::instance().getTypeId(); -} -}; - -template -class InstanceStaticCast : - public CastInstaller< - StaticInstanceType, - StaticCast - > -{ -}; - -template -class InstanceContainedCast : - public CastInstaller< - StaticInstanceType, - ContainedCast - > -{ -}; - -template -class InstanceIdentityCast : - public CastInstaller< - StaticInstanceType, - IdentityCast - > -{ -}; - - -inline Selectable* Instance_getSelectable( scene::Instance& instance ); -inline const Selectable* Instance_getSelectable( const scene::Instance& instance ); - -inline Bounded* Instance_getBounded( scene::Instance& instance ); -inline const Bounded* Instance_getBounded( const scene::Instance& instance ); - -namespace scene -{ -class Instance -{ -class AABBAccumulateWalker : public scene::Graph::Walker -{ -AABB& m_aabb; -mutable std::size_t m_depth; -public: -AABBAccumulateWalker( AABB& aabb ) : m_aabb( aabb ), m_depth( 0 ){ -} -bool pre( const scene::Path& path, scene::Instance& instance ) const { - if ( m_depth == 1 ) { - aabb_extend_by_aabb_safe( m_aabb, instance.worldAABB() ); - } - return ++m_depth != 2; -} -void post( const scene::Path& path, scene::Instance& instance ) const { - --m_depth; -} -}; - - -class TransformChangedWalker : public scene::Graph::Walker -{ -public: -bool pre( const scene::Path& path, scene::Instance& instance ) const { - instance.transformChangedLocal(); - return true; -} -}; - -class ParentSelectedChangedWalker : public scene::Graph::Walker -{ -public: -bool pre( const scene::Path& path, scene::Instance& instance ) const { - instance.parentSelectedChanged(); - return true; -} -}; - -class ChildSelectedWalker : public scene::Graph::Walker -{ -bool& m_childSelected; -mutable std::size_t m_depth; -public: -ChildSelectedWalker( bool& childSelected ) : m_childSelected( childSelected ), m_depth( 0 ){ - m_childSelected = false; -} -bool pre( const scene::Path& path, scene::Instance& instance ) const { - if ( m_depth == 1 && !m_childSelected ) { - m_childSelected = instance.isSelected() || instance.childSelected(); - } - return ++m_depth != 2; -} -void post( const scene::Path& path, scene::Instance& instance ) const { - --m_depth; -} -}; - -Path m_path; -Instance* m_parent; -void* m_instance; -InstanceTypeCastTable& m_casts; - -mutable Matrix4 m_local2world; -mutable AABB m_bounds; -mutable AABB m_childBounds; -mutable bool m_transformChanged; -mutable bool m_transformMutex; -mutable bool m_boundsChanged; -mutable bool m_boundsMutex; -mutable bool m_childBoundsChanged; -mutable bool m_childBoundsMutex; -mutable bool m_isSelected; -mutable bool m_isSelectedChanged; -mutable bool m_childSelected; -mutable bool m_childSelectedChanged; -mutable bool m_parentSelected; -mutable bool m_parentSelectedChanged; -Callback m_childSelectedChangedCallback; -Callback m_transformChangedCallback; - - -void evaluateTransform() const { - if ( m_transformChanged ) { - ASSERT_MESSAGE( !m_transformMutex, "re-entering transform evaluation" ); - m_transformMutex = true; - - m_local2world = ( m_parent != 0 ) ? m_parent->localToWorld() : g_matrix4_identity; - Transformable* transformable = Node_getTransformable( m_path.top() ); - if ( transformable != 0 ) { - matrix4_multiply_by_matrix4( m_local2world, transformable->localToParent() ); - } - - m_transformMutex = false; - m_transformChanged = false; - } -} -void evaluateChildBounds() const { - if ( m_childBoundsChanged ) { - ASSERT_MESSAGE( !m_childBoundsMutex, "re-entering bounds evaluation" ); - m_childBoundsMutex = true; - - m_childBounds = AABB(); - - GlobalSceneGraph().traverse_subgraph( AABBAccumulateWalker( m_childBounds ), m_path ); - - m_childBoundsMutex = false; - m_childBoundsChanged = false; - } -} -void evaluateBounds() const { - if ( m_boundsChanged ) { - ASSERT_MESSAGE( !m_boundsMutex, "re-entering bounds evaluation" ); - m_boundsMutex = true; - - m_bounds = childBounds(); - - const Bounded* bounded = Instance_getBounded( *this ); - if ( bounded != 0 ) { - aabb_extend_by_aabb_safe( - m_bounds, - aabb_for_oriented_aabb_safe( bounded->localAABB(), localToWorld() ) - ); - } - - m_boundsMutex = false; - m_boundsChanged = false; - } -} - -Instance( const scene::Instance& other ); -Instance& operator=( const scene::Instance& other ); -public: - -Instance( const scene::Path& path, Instance* parent, void* instance, InstanceTypeCastTable& casts ) : - m_path( path ), - m_parent( parent ), - m_instance( instance ), - m_casts( casts ), - m_transformChanged( true ), - m_transformMutex( false ), - m_boundsChanged( true ), - m_boundsMutex( false ), - m_childBoundsChanged( true ), - m_childBoundsMutex( false ), - m_isSelectedChanged( true ), - m_childSelectedChanged( true ), - m_parentSelectedChanged( true ){ - ASSERT_MESSAGE( ( parent == 0 ) == ( path.size() == 1 ), "instance has invalid parent" ); -} -virtual ~Instance(){ -} - -const scene::Path& path() const { - return m_path; -} - -void* cast( TypeId typeId ) const { - return m_casts.cast( typeId, m_instance ); -} - -const Matrix4& localToWorld() const { - evaluateTransform(); - return m_local2world; -} -void transformChangedLocal(){ - ASSERT_NOTNULL( m_parent ); - m_transformChanged = true; - m_boundsChanged = true; - m_childBoundsChanged = true; - m_transformChangedCallback(); -} -void transformChanged(){ - GlobalSceneGraph().traverse_subgraph( TransformChangedWalker(), m_path ); - boundsChanged(); -} -void setTransformChangedCallback( const Callback& callback ){ - m_transformChangedCallback = callback; -} - - -const AABB& worldAABB() const { - evaluateBounds(); - return m_bounds; -} -const AABB& childBounds() const { - evaluateChildBounds(); - return m_childBounds; -} -void boundsChanged(){ - m_boundsChanged = true; - m_childBoundsChanged = true; - if ( m_parent != 0 ) { - m_parent->boundsChanged(); - } - GlobalSceneGraph().boundsChanged(); -} - -void childSelectedChanged(){ - m_childSelectedChanged = true; - m_childSelectedChangedCallback(); - selectedChanged(); -} -bool childSelected() const { - if ( m_childSelectedChanged ) { - m_childSelectedChanged = false; - GlobalSceneGraph().traverse_subgraph( ChildSelectedWalker( m_childSelected ), m_path ); - } - return m_childSelected; -} - -void setChildSelectedChangedCallback( const Callback& callback ){ - m_childSelectedChangedCallback = callback; -} -void selectedChanged(){ - m_isSelectedChanged = true; - if ( m_parent != 0 ) { - m_parent->childSelectedChanged(); - } - GlobalSceneGraph().traverse_subgraph( ParentSelectedChangedWalker(), m_path ); -} -bool isSelected() const { - if ( m_isSelectedChanged ) { - m_isSelectedChanged = false; - const Selectable* selectable = Instance_getSelectable( *this ); - m_isSelected = selectable != 0 && selectable->isSelected(); - } - return m_isSelected; -} - -void parentSelectedChanged(){ - m_parentSelectedChanged = true; -} -bool parentSelected() const { - if ( m_parentSelectedChanged ) { - m_parentSelectedChanged = false; - m_parentSelected = m_parent != 0 && ( m_parent->isSelected() || m_parent->parentSelected() ); - } - return m_parentSelected; -} -}; -} - -template -class InstanceTypeCast -{ -public: -static Type* cast( scene::Instance& instance ){ - return static_cast( instance.cast( StaticInstanceType::getTypeId() ) ); -} -static const Type* cast( const scene::Instance& instance ){ - return static_cast( instance.cast( StaticInstanceType::getTypeId() ) ); -} -}; - -inline Selectable* Instance_getSelectable( scene::Instance& instance ){ - return InstanceTypeCast::cast( instance ); -} -inline const Selectable* Instance_getSelectable( const scene::Instance& instance ){ - return InstanceTypeCast::cast( instance ); -} - -inline Bounded* Instance_getBounded( scene::Instance& instance ){ - return InstanceTypeCast::cast( instance ); -} -inline const Bounded* Instance_getBounded( const scene::Instance& instance ){ - return InstanceTypeCast::cast( instance ); -} - - -inline ComponentSelectionTestable* Instance_getComponentSelectionTestable( scene::Instance& instance ){ - return InstanceTypeCast::cast( instance ); -} - -inline ComponentEditable* Instance_getComponentEditable( scene::Instance& instance ){ - return InstanceTypeCast::cast( instance ); -} - - - -class InstanceCounter -{ -public: -unsigned int m_count; -InstanceCounter() : m_count( 0 ){ -} -}; - - -class Counter -{ -public: -virtual void increment() = 0; -virtual void decrement() = 0; -}; - -#include "generic/callback.h" - -class SimpleCounter : public Counter -{ -Callback m_countChanged; -std::size_t m_count; -public: -void setCountChangedCallback( const Callback& countChanged ){ - m_countChanged = countChanged; -} -void increment(){ - ++m_count; - m_countChanged(); -} -void decrement(){ - --m_count; - m_countChanged(); -} -std::size_t get() const { - return m_count; -} -}; - - -template -class ConstReference; -typedef ConstReference PathConstReference; - -#include "generic/referencecounted.h" -typedef SmartReference > NodeSmartReference; - - -#endif diff --git a/tools/urt/libs/script/scripttokeniser.cpp b/tools/urt/libs/script/scripttokeniser.cpp deleted file mode 100644 index 9b96f74..0000000 --- a/tools/urt/libs/script/scripttokeniser.cpp +++ /dev/null @@ -1,2 +0,0 @@ - -#include "scripttokeniser.h" diff --git a/tools/urt/libs/script/scripttokeniser.h b/tools/urt/libs/script/scripttokeniser.h deleted file mode 100644 index 997e1d5..0000000 --- a/tools/urt/libs/script/scripttokeniser.h +++ /dev/null @@ -1,297 +0,0 @@ - -#if !defined( INCLUDED_SCRIPT_SCRIPTTOKENISER_H ) -#define INCLUDED_SCRIPT_SCRIPTTOKENISER_H - -#include "iscriplib.h" - -class ScriptTokeniser : public Tokeniser -{ -enum CharType -{ - eWhitespace, - eCharToken, - eNewline, - eCharQuote, - eCharSolidus, - eCharStar, - eCharSpecial, -}; - -typedef bool ( ScriptTokeniser::*Tokenise )( char c ); - -Tokenise m_stack[3]; -Tokenise* m_state; -SingleCharacterInputStream m_istream; -std::size_t m_scriptline; - -char m_token[MAXTOKEN]; -char* m_write; - -char m_current; -bool m_eof; -bool m_crossline; -bool m_unget; - -bool m_special; - -CharType charType( const char c ){ - switch ( c ) - { - case '\n': return eNewline; - case '"': return eCharQuote; - case '/': return eCharSolidus; - case '*': return eCharStar; - case '{': case '(': case '}': case ')': case '[': case ']': case ',': case ':': return ( m_special ) ? eCharSpecial : eCharToken; - } - - if ( c > 32 ) { - return eCharToken; - } - return eWhitespace; -} - -Tokenise state(){ - return *m_state; -} -void push( Tokenise state ){ - ASSERT_MESSAGE( m_state != m_stack + 2, "token parser: illegal stack push" ); - *( ++m_state ) = state; -} -void pop(){ - ASSERT_MESSAGE( m_state != m_stack, "token parser: illegal stack pop" ); - --m_state; -} -void add( const char c ){ - if ( m_write < m_token + MAXTOKEN - 1 ) { - *m_write++ = c; - } -} -void remove(){ - ASSERT_MESSAGE( m_write > m_token, "no char to remove" ); - --m_write; -} - -bool tokeniseDefault( char c ){ - switch ( charType( c ) ) - { - case eNewline: - ASSERT_MESSAGE( m_crossline, "unexpected end-of-line before token" ); - break; - case eCharToken: - case eCharStar: - push( Tokenise( &ScriptTokeniser::tokeniseToken ) ); - add( c ); - break; - case eCharSpecial: - push( Tokenise( &ScriptTokeniser::tokeniseSpecial ) ); - add( c ); - break; - case eCharQuote: - push( Tokenise( &ScriptTokeniser::tokeniseQuotedToken ) ); - break; - case eCharSolidus: - push( Tokenise( &ScriptTokeniser::tokeniseSolidus ) ); - break; - default: - break; - } - return false; -} -bool tokeniseToken( char c ){ - switch ( charType( c ) ) - { - case eNewline: - case eWhitespace: - case eCharQuote: - case eCharSpecial: - pop(); - return true; // emit token - case eCharSolidus: - push( Tokenise( &ScriptTokeniser::tokeniseSolidus ) ); - break; - case eCharToken: - case eCharStar: - add( c ); - break; - default: - break; - } - return false; -} -bool tokeniseQuotedToken( char c ){ - switch ( charType( c ) ) - { - case eNewline: - ASSERT_MESSAGE( !m_crossline, "unexpected end-of-line in quoted token" ); - break; - case eWhitespace: - case eCharToken: - case eCharSolidus: - case eCharStar: - case eCharSpecial: - add( c ); - break; - case eCharQuote: - pop(); - push( Tokenise( &ScriptTokeniser::tokeniseEndQuote ) ); - break; - default: - break; - } - return false; -} -bool tokeniseSolidus( char c ){ - switch ( charType( c ) ) - { - case eNewline: - case eWhitespace: - case eCharQuote: - case eCharSpecial: - pop(); - add( '/' ); - return true; // emit single slash - case eCharToken: - pop(); - add( '/' ); - add( c ); - break; - case eCharSolidus: - pop(); - push( Tokenise( &ScriptTokeniser::tokeniseComment ) ); - break; // dont emit single slash - case eCharStar: - pop(); - push( Tokenise( &ScriptTokeniser::tokeniseBlockComment ) ); - break; // dont emit single slash - default: - break; - } - return false; -} -bool tokeniseComment( char c ){ - if ( c == '\n' ) { - pop(); - if ( state() == Tokenise( &ScriptTokeniser::tokeniseToken ) ) { - pop(); - return true; // emit token immediatly preceding comment - } - } - return false; -} -bool tokeniseBlockComment( char c ){ - if ( c == '*' ) { - pop(); - push( Tokenise( &ScriptTokeniser::tokeniseEndBlockComment ) ); - } - return false; -} -bool tokeniseEndBlockComment( char c ){ - switch ( c ) - { - case '/': - pop(); - if ( state() == Tokenise( &ScriptTokeniser::tokeniseToken ) ) { - pop(); - return true; // emit token immediatly preceding comment - } - break; // dont emit comment - case '*': - break; // no state change - default: - pop(); - push( Tokenise( &ScriptTokeniser::tokeniseBlockComment ) ); - break; - } - return false; -} -bool tokeniseEndQuote( char c ){ - pop(); - return true; // emit quoted token -} -bool tokeniseSpecial( char c ){ - pop(); - return true; // emit single-character token -} - -void tokenise(){ - m_write = m_token; - while ( !eof() ) - { - char c = m_current; - - if ( c == '\n' ) { - ++m_scriptline; - } - - if ( ( ( *this ).*state() )( c ) ) { - return; - } - - m_eof = !m_istream.readChar( m_current ); - } -} - -const char* fillToken(){ - if ( eof() ) { - return 0; - } - - tokenise(); - - if ( eof() && m_write == m_token ) { - return 0; - } - - add( '\0' ); - return m_token; -} - -bool eof(){ - return m_eof; -} - -public: -ScriptTokeniser( TextInputStream& istream, bool special ) - : m_state( m_stack ), - m_istream( istream ), - m_scriptline( 0 ), - m_crossline( false ), - m_unget( false ), - m_special( special ){ - m_stack[0] = Tokenise( &ScriptTokeniser::tokeniseDefault ); - m_eof = !m_istream.readChar( m_current ); - m_token[MAXTOKEN - 1] = '\0'; -} -void release(){ - delete this; -} -void nextLine(){ - m_crossline = true; -} -const char* getToken(){ - if ( m_unget ) { - m_unget = false; - return m_token; - } - - return fillToken(); -} -void ungetToken(){ - ASSERT_MESSAGE( !m_unget, "can't unget more than one token" ); - m_unget = true; -} -std::size_t getLine() const { - return m_scriptline; -} -}; - - -inline Tokeniser& NewScriptTokeniser( TextInputStream& istream ){ - return *( new ScriptTokeniser( istream, true ) ); -} - -inline Tokeniser& NewSimpleTokeniser( TextInputStream& istream ){ - return *( new ScriptTokeniser( istream, false ) ); -} - -#endif diff --git a/tools/urt/libs/script/scripttokenwriter.cpp b/tools/urt/libs/script/scripttokenwriter.cpp deleted file mode 100644 index 1a04b02..0000000 --- a/tools/urt/libs/script/scripttokenwriter.cpp +++ /dev/null @@ -1,2 +0,0 @@ - -#include "scripttokenwriter.h" diff --git a/tools/urt/libs/script/scripttokenwriter.h b/tools/urt/libs/script/scripttokenwriter.h deleted file mode 100644 index 6d8d67a..0000000 --- a/tools/urt/libs/script/scripttokenwriter.h +++ /dev/null @@ -1,57 +0,0 @@ - -#if !defined( INCLUDED_SCRIPT_SCRIPTTOKENWRITER_H ) -#define INCLUDED_SCRIPT_SCRIPTTOKENWRITER_H - -#include "iscriplib.h" - -class SimpleTokenWriter : public TokenWriter -{ -public: -SimpleTokenWriter( TextOutputStream& ostream ) - : m_ostream( ostream ), m_separator( '\n' ){ -} -~SimpleTokenWriter(){ - writeSeparator(); -} -void release(){ - delete this; -} -void nextLine(){ - m_separator = '\n'; -} -void writeToken( const char* token ){ - ASSERT_MESSAGE( strchr( token, ' ' ) == 0, "token contains whitespace: " ); - writeSeparator(); - m_ostream << token; -} -void writeString( const char* string ){ - writeSeparator(); - m_ostream << '"' << string << '"'; -} -void writeInteger( int i ){ - writeSeparator(); - m_ostream << i; -} -void writeUnsigned( std::size_t i ){ - writeSeparator(); - m_ostream << Unsigned( i ); -} -void writeFloat( double f ){ - writeSeparator(); - m_ostream << Decimal( f ); -} - -private: -void writeSeparator(){ - m_ostream << m_separator; - m_separator = ' '; -} -TextOutputStream& m_ostream; -char m_separator; -}; - -inline TokenWriter& NewSimpleTokenWriter( TextOutputStream& ostream ){ - return *( new SimpleTokenWriter( ostream ) ); -} - -#endif diff --git a/tools/urt/libs/selectionlib.cpp b/tools/urt/libs/selectionlib.cpp deleted file mode 100644 index 60ee825..0000000 --- a/tools/urt/libs/selectionlib.cpp +++ /dev/null @@ -1,2 +0,0 @@ - -#include "selectionlib.h" diff --git a/tools/urt/libs/selectionlib.h b/tools/urt/libs/selectionlib.h deleted file mode 100644 index e9f173f..0000000 --- a/tools/urt/libs/selectionlib.h +++ /dev/null @@ -1,159 +0,0 @@ - -#if !defined ( INCLUDED_SELECTIONLIB_H ) -#define INCLUDED_SELECTIONLIB_H - -#include "iselection.h" -#include "generic/callback.h" -#include "scenelib.h" -#include - -class SelectableBool : public Selectable -{ -bool m_selected; -public: -SelectableBool() - : m_selected( false ) -{} - -void setSelected( bool select = true ){ - m_selected = select; -} -bool isSelected() const { - return m_selected; -} -}; - -class ObservedSelectable : public Selectable -{ -SelectionChangeCallback m_onchanged; -bool m_selected; -public: -ObservedSelectable( const SelectionChangeCallback& onchanged ) : m_onchanged( onchanged ), m_selected( false ){ -} -ObservedSelectable( const ObservedSelectable& other ) : Selectable( other ), m_onchanged( other.m_onchanged ), m_selected( false ){ - setSelected( other.isSelected() ); -} -ObservedSelectable& operator=( const ObservedSelectable& other ){ - setSelected( other.isSelected() ); - return *this; -} -~ObservedSelectable(){ - setSelected( false ); -} - -void setSelected( bool select ){ - if ( select ^ m_selected ) { - m_selected = select; - - m_onchanged( *this ); - } -} -bool isSelected() const { - return m_selected; -} -}; - -class SelectableInstance : public scene::Instance -{ -class TypeCasts -{ -InstanceTypeCastTable m_casts; -public: -TypeCasts(){ - InstanceContainedCast::install( m_casts ); -} -InstanceTypeCastTable& get(){ - return m_casts; -} -}; - -ObservedSelectable m_selectable; -public: - -typedef LazyStatic StaticTypeCasts; - -SelectableInstance( const scene::Path& path, scene::Instance* parent, void* instance = 0, InstanceTypeCastTable& casts = StaticTypeCasts::instance().get() ) : - Instance( path, parent, instance != 0 ? instance : this, casts ), - m_selectable( SelectedChangedCaller( *this ) ){ -} - -Selectable& get( NullType){ - return m_selectable; -} - -Selectable& getSelectable(){ - return m_selectable; -} -const Selectable& getSelectable() const { - return m_selectable; -} - -void selectedChanged( const Selectable& selectable ){ - GlobalSelectionSystem().getObserver ( SelectionSystem::ePrimitive )( selectable ); - GlobalSelectionSystem().onSelectedChanged( *this, selectable ); - - Instance::selectedChanged(); -} -typedef MemberCaller1 SelectedChangedCaller; -}; - - -template -inline bool range_check( Iterator start, Iterator finish, Iterator iter ){ - for (; start != finish; ++start ) - { - if ( start == iter ) { - return true; - } - } - return false; -} - -#include - -template -class SelectionList -{ -typedef std::list List; -List m_selection; -public: -typedef typename List::iterator iterator; -typedef typename List::const_iterator const_iterator; - -iterator begin(){ - return m_selection.begin(); -} -const_iterator begin() const { - return m_selection.begin(); -} -iterator end(){ - return m_selection.end(); -} -const_iterator end() const { - return m_selection.end(); -} -bool empty() const { - return m_selection.empty(); -} -std::size_t size() const { - return m_selection.size(); -} -Selected& back(){ - return *m_selection.back(); -} -Selected& back() const { - return *m_selection.back(); -} -void append( Selected& selected ){ - m_selection.push_back( &selected ); -} -void erase( Selected& selected ){ - typename List::reverse_iterator i = std::find( m_selection.rbegin(), m_selection.rend(), &selected ); - ASSERT_MESSAGE( i != m_selection.rend(), "selection-tracking error" ); - ASSERT_MESSAGE( range_check( m_selection.begin(), m_selection.end(), --i.base() ), "selection-tracking error" ); - m_selection.erase( --i.base() ); -} -}; - - -#endif diff --git a/tools/urt/libs/shaderlib.cpp b/tools/urt/libs/shaderlib.cpp deleted file mode 100644 index 2d5a529..0000000 --- a/tools/urt/libs/shaderlib.cpp +++ /dev/null @@ -1,2 +0,0 @@ - -#include "shaderlib.h" diff --git a/tools/urt/libs/shaderlib.h b/tools/urt/libs/shaderlib.h deleted file mode 100644 index 470d88c..0000000 --- a/tools/urt/libs/shaderlib.h +++ /dev/null @@ -1,64 +0,0 @@ - -#if !defined ( INCLUDED_SHADERLIB_H ) -#define INCLUDED_SHADERLIB_H - -#include "string/string.h" -#include "character.h" -#include "ishaders.h" - -inline bool shader_equal( const char* shader, const char* other ){ - return string_equal_nocase( shader, other ); -} - -inline bool shader_equal_n( const char* shader, const char* other, std::size_t n ){ - return string_equal_nocase_n( shader, other, n ); -} - -inline bool shader_less( const char* shader, const char* other ){ - return string_less_nocase( shader, other ); -} - -inline bool shader_equal_prefix( const char* string, const char* prefix ){ - return shader_equal_n( string, prefix, string_length( prefix ) ); -} - -class shader_less_t -{ -public: -bool operator()( const CopiedString& shader, const CopiedString& other ) const { - return shader_less( shader.c_str(), other.c_str() ); -} -}; - -inline bool shader_valid( const char* shader ){ - return string_is_ascii( shader ) - && strchr( shader, ' ' ) == 0 - && strchr( shader, '\n' ) == 0 - && strchr( shader, '\r' ) == 0 - && strchr( shader, '\t' ) == 0 - && strchr( shader, '\v' ) == 0 - && strchr( shader, '\\' ) == 0; -} - -inline const char* GlobalTexturePrefix_get(){ - return GlobalShaderSystem().getTexturePrefix(); -} - -inline bool shader_is_texture( const char* name ){ - return shader_equal_prefix( name, GlobalTexturePrefix_get() ); -} - -inline const char* shader_get_textureName( const char* name ){ - return name + string_length( GlobalTexturePrefix_get() ); -} - -inline bool texdef_name_valid( const char* name ){ - return shader_valid( name ) && shader_is_texture( name ); -} - -inline const char* texdef_name_default(){ - return GlobalTexturePrefix_get(); -} - - -#endif diff --git a/tools/urt/libs/splines/Splines.dsp b/tools/urt/libs/splines/Splines.dsp deleted file mode 100644 index 5526312..0000000 --- a/tools/urt/libs/splines/Splines.dsp +++ /dev/null @@ -1,160 +0,0 @@ -# Microsoft Developer Studio Project File - Name="Splines" - Package Owner=<4> -# Microsoft Developer Studio Generated Build File, Format Version 6.00 -# ** DO NOT EDIT ** - -# TARGTYPE "Win32 (x86) Static Library" 0x0104 - -CFG=Splines - Win32 Release -!MESSAGE This is not a valid makefile. To build this project using NMAKE, -!MESSAGE use the Export Makefile command and run -!MESSAGE -!MESSAGE NMAKE /f "Splines.mak". -!MESSAGE -!MESSAGE You can specify a configuration when running NMAKE -!MESSAGE by defining the macro CFG on the command line. For example: -!MESSAGE -!MESSAGE NMAKE /f "Splines.mak" CFG="Splines - Win32 Release" -!MESSAGE -!MESSAGE Possible choices for configuration are: -!MESSAGE -!MESSAGE "Splines - Win32 Release" (based on "Win32 (x86) Static Library") -!MESSAGE "Splines - Win32 Debug" (based on "Win32 (x86) Static Library") -!MESSAGE - -# Begin Project -# PROP AllowPerConfigDependencies 0 -# PROP Scc_ProjName ""$/Wolf5/src/splines", ENNAAAAA" -# PROP Scc_LocalPath "." -CPP=cl.exe -RSC=rc.exe - -!IF "$(CFG)" == "Splines - Win32 Release" - -# PROP BASE Use_MFC 0 -# PROP BASE Use_Debug_Libraries 0 -# PROP BASE Output_Dir "Release" -# PROP BASE Intermediate_Dir "Release" -# PROP BASE Target_Dir "" -# PROP Use_MFC 0 -# PROP Use_Debug_Libraries 0 -# PROP Output_Dir "Release" -# PROP Intermediate_Dir "Release" -# PROP Target_Dir "" -MTL=midl.exe -F90=df.exe -# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_MBCS" /D "_LIB" /YX /FD /c -# ADD CPP /nologo /MD /W3 /GX /O2 /I ".." /I "..\..\include" /D "WIN32" /D "NDEBUG" /D "_MBCS" /D "_LIB" /YX /FD /c -# ADD BASE RSC /l 0x409 /d "NDEBUG" -# ADD RSC /l 0x409 /d "NDEBUG" -BSC32=bscmake.exe -# ADD BASE BSC32 /nologo -# ADD BSC32 /nologo -LIB32=link.exe -lib -# ADD BASE LIB32 /nologo -# ADD LIB32 /nologo - -!ELSEIF "$(CFG)" == "Splines - Win32 Debug" - -# PROP BASE Use_MFC 0 -# PROP BASE Use_Debug_Libraries 1 -# PROP BASE Output_Dir "Debug" -# PROP BASE Intermediate_Dir "Debug" -# PROP BASE Target_Dir "" -# PROP Use_MFC 0 -# PROP Use_Debug_Libraries 1 -# PROP Output_Dir "Debug" -# PROP Intermediate_Dir "Debug" -# PROP Target_Dir "" -MTL=midl.exe -F90=df.exe -# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_MBCS" /D "_LIB" /YX /FD /GZ /c -# ADD CPP /nologo /MDd /W3 /Gm /GR /GX /ZI /Od /I ".." /I "..\..\include" /D "WIN32" /D "_DEBUG" /D "_MBCS" /D "_LIB" /YX /FD /GZ /c -# ADD BASE RSC /l 0x409 /d "_DEBUG" -# ADD RSC /l 0x409 /d "_DEBUG" -BSC32=bscmake.exe -# ADD BASE BSC32 /nologo -# ADD BSC32 /nologo -LIB32=link.exe -lib -# ADD BASE LIB32 /nologo -# ADD LIB32 /nologo - -!ENDIF - -# Begin Target - -# Name "Splines - Win32 Release" -# Name "Splines - Win32 Debug" -# Begin Group "Source Files" - -# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat" -# Begin Source File - -SOURCE=.\math_angles.cpp -# End Source File -# Begin Source File - -SOURCE=.\math_matrix.cpp -# End Source File -# Begin Source File - -SOURCE=.\math_quaternion.cpp -# End Source File -# Begin Source File - -SOURCE=.\math_vector.cpp -# End Source File -# Begin Source File - -SOURCE=.\q_parse.cpp -# End Source File -# Begin Source File - -SOURCE=.\q_shared.cpp -# End Source File -# Begin Source File - -SOURCE=.\splines.cpp -# End Source File -# Begin Source File - -SOURCE=.\util_str.cpp -# End Source File -# End Group -# Begin Group "Header Files" - -# PROP Default_Filter "h;hpp;hxx;hm;inl" -# Begin Source File - -SOURCE=.\math_angles.h -# End Source File -# Begin Source File - -SOURCE=.\math_matrix.h -# End Source File -# Begin Source File - -SOURCE=.\math_quaternion.h -# End Source File -# Begin Source File - -SOURCE=.\math_vector.h -# End Source File -# Begin Source File - -SOURCE=.\q_shared.h -# End Source File -# Begin Source File - -SOURCE=.\splines.h -# End Source File -# Begin Source File - -SOURCE=.\util_list.h -# End Source File -# Begin Source File - -SOURCE=.\util_str.h -# End Source File -# End Group -# End Target -# End Project diff --git a/tools/urt/libs/splines/Splines.vcproj b/tools/urt/libs/splines/Splines.vcproj deleted file mode 100644 index 2cb4332..0000000 --- a/tools/urt/libs/splines/Splines.vcproj +++ /dev/null @@ -1,163 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/tools/urt/libs/splines/math_angles.cpp b/tools/urt/libs/splines/math_angles.cpp deleted file mode 100644 index 5c1bb59..0000000 --- a/tools/urt/libs/splines/math_angles.cpp +++ /dev/null @@ -1,152 +0,0 @@ -/* - Copyright (C) 1999-2007 id Software, Inc. and contributors. - For a list of contributors, see the accompanying CONTRIBUTORS file. - - This file is part of GtkRadiant. - - GtkRadiant is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - GtkRadiant is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with GtkRadiant; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - */ - -#include "q_shared.h" -#include - -angles_t ang_zero( 0.0f, 0.0f, 0.0f ); - -void toAngles( mat3_t &src, angles_t &dst ) { - double theta; - double cp; - double sp; - - sp = src[ 0 ][ 2 ]; - - // cap off our sin value so that we don't get any NANs - if ( sp > 1.0 ) { - sp = 1.0; - } - else if ( sp < -1.0 ) { - sp = -1.0; - } - - theta = -asin( sp ); - cp = cos( theta ); - - if ( cp > 8192 * FLT_EPSILON ) { - dst.pitch = theta * 180 / M_PI; - dst.yaw = atan2( src[ 0 ][ 1 ], src[ 0 ][ 0 ] ) * 180 / M_PI; - dst.roll = atan2( src[ 1 ][ 2 ], src[ 2 ][ 2 ] ) * 180 / M_PI; - } - else { - dst.pitch = theta * 180 / M_PI; - dst.yaw = -atan2( src[ 1 ][ 0 ], src[ 1 ][ 1 ] ) * 180 / M_PI; - dst.roll = 0; - } -} - -void toAngles( quat_t &src, angles_t &dst ) { - mat3_t temp; - - toMatrix( src, temp ); - toAngles( temp, dst ); -} - -void toAngles( idVec3 &src, angles_t &dst ) { - dst.pitch = src[ 0 ]; - dst.yaw = src[ 1 ]; - dst.roll = src[ 2 ]; -} - -void angles_t::toVectors( idVec3 *forward, idVec3 *right, idVec3 *up ) { - float angle; - static float sr, sp, sy, cr, cp, cy; // static to help MS compiler fp bugs - - angle = yaw * ( M_PI * 2 / 360 ); - sy = sin( angle ); - cy = cos( angle ); - - angle = pitch * ( M_PI * 2 / 360 ); - sp = sin( angle ); - cp = cos( angle ); - - angle = roll * ( M_PI * 2 / 360 ); - sr = sin( angle ); - cr = cos( angle ); - - if ( forward ) { - forward->set( cp * cy, cp * sy, -sp ); - } - - if ( right ) { - right->set( -sr * sp * cy + cr * sy, -sr * sp * sy + -cr * cy, -sr * cp ); - } - - if ( up ) { - up->set( cr * sp * cy + -sr * -sy, cr * sp * sy + -sr * cy, cr * cp ); - } -} - -idVec3 angles_t::toForward( void ) { - float angle; - static float sp, sy, cp, cy; // static to help MS compiler fp bugs - - angle = yaw * ( M_PI * 2 / 360 ); - sy = sin( angle ); - cy = cos( angle ); - - angle = pitch * ( M_PI * 2 / 360 ); - sp = sin( angle ); - cp = cos( angle ); - - return idVec3( cp * cy, cp * sy, -sp ); -} - -/* - ================= - Normalize360 - - returns angles normalized to the range [0 <= angle < 360] - ================= - */ -angles_t& angles_t::Normalize360( void ) { - pitch = ( 360.0 / 65536 ) * ( ( int )( pitch * ( 65536 / 360.0 ) ) & 65535 ); - yaw = ( 360.0 / 65536 ) * ( ( int )( yaw * ( 65536 / 360.0 ) ) & 65535 ); - roll = ( 360.0 / 65536 ) * ( ( int )( roll * ( 65536 / 360.0 ) ) & 65535 ); - - return *this; -} - - -/* - ================= - Normalize180 - - returns angles normalized to the range [-180 < angle <= 180] - ================= - */ -angles_t& angles_t::Normalize180( void ) { - Normalize360(); - - if ( pitch > 180.0 ) { - pitch -= 360.0; - } - - if ( yaw > 180.0 ) { - yaw -= 360.0; - } - - if ( roll > 180.0 ) { - roll -= 360.0; - } - return *this; -} diff --git a/tools/urt/libs/splines/math_angles.h b/tools/urt/libs/splines/math_angles.h deleted file mode 100644 index 1661d78..0000000 --- a/tools/urt/libs/splines/math_angles.h +++ /dev/null @@ -1,195 +0,0 @@ -/* - Copyright (C) 1999-2007 id Software, Inc. and contributors. - For a list of contributors, see the accompanying CONTRIBUTORS file. - - This file is part of GtkRadiant. - - GtkRadiant is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - GtkRadiant is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with GtkRadiant; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - */ - -#ifndef __MATH_ANGLES_H__ -#define __MATH_ANGLES_H__ - -#include -#include - -#include "math_vector.h" - -class mat3_t; -class quat_t; -class idVec3; -typedef idVec3 &vec3_p; - -class angles_t { -public: -float pitch; -float yaw; -float roll; - -angles_t(); -angles_t( float pitch, float yaw, float roll ); -angles_t( const idVec3 &vec ); - -friend void toAngles( idVec3 &src, angles_t &dst ); -friend void toAngles( quat_t &src, angles_t &dst ); -friend void toAngles( mat3_t &src, angles_t &dst ); - -operator vec3_p(); - -float operator[]( int index ) const; -float& operator[]( int index ); - -void set( float pitch, float yaw, float roll ); - -void operator=( angles_t const &a ); -void operator=( idVec3 const &a ); - -friend angles_t operator+( const angles_t &a, const angles_t &b ); -angles_t &operator+=( angles_t const &a ); -angles_t &operator+=( idVec3 const &a ); - -friend angles_t operator-( angles_t &a, angles_t &b ); -angles_t &operator-=( angles_t &a ); - -friend angles_t operator*( const angles_t &a, float b ); -friend angles_t operator*( float a, const angles_t &b ); -angles_t &operator*=( float a ); - -friend int operator==( angles_t &a, angles_t &b ); - -friend int operator!=( angles_t &a, angles_t &b ); - -void toVectors( idVec3 *forward, idVec3 *right = NULL, idVec3 *up = NULL ); -idVec3 toForward( void ); - -angles_t &Zero( void ); - -angles_t &Normalize360( void ); -angles_t &Normalize180( void ); -}; - -extern angles_t ang_zero; - -inline angles_t::angles_t() {} - -inline angles_t::angles_t( float pitch, float yaw, float roll ) { - this->pitch = pitch; - this->yaw = yaw; - this->roll = roll; -} - -inline angles_t::angles_t( const idVec3 &vec ) { - this->pitch = vec.x; - this->yaw = vec.y; - this->roll = vec.z; -} - -inline float angles_t::operator[]( int index ) const { - assert( ( index >= 0 ) && ( index < 3 ) ); - return ( &pitch )[ index ]; -} - -inline float& angles_t::operator[]( int index ) { - assert( ( index >= 0 ) && ( index < 3 ) ); - return ( &pitch )[ index ]; -} - -inline angles_t::operator vec3_p( void ) { - return *( idVec3 * )&pitch; -} - -inline void angles_t::set( float pitch, float yaw, float roll ) { - this->pitch = pitch; - this->yaw = yaw; - this->roll = roll; -} - -inline void angles_t::operator=( angles_t const &a ) { - pitch = a.pitch; - yaw = a.yaw; - roll = a.roll; -} - -inline void angles_t::operator=( idVec3 const &a ) { - pitch = a[ 0 ]; - yaw = a[ 1 ]; - roll = a[ 2 ]; -} - -inline angles_t operator+( const angles_t &a, const angles_t &b ) { - return angles_t( a.pitch + b.pitch, a.yaw + b.yaw, a.roll + b.roll ); -} - -inline angles_t& angles_t::operator+=( angles_t const &a ) { - pitch += a.pitch; - yaw += a.yaw; - roll += a.roll; - - return *this; -} - -inline angles_t& angles_t::operator+=( idVec3 const &a ) { - pitch += a.x; - yaw += a.y; - roll += a.z; - - return *this; -} - -inline angles_t operator-( angles_t &a, angles_t &b ) { - return angles_t( a.pitch - b.pitch, a.yaw - b.yaw, a.roll - b.roll ); -} - -inline angles_t& angles_t::operator-=( angles_t &a ) { - pitch -= a.pitch; - yaw -= a.yaw; - roll -= a.roll; - - return *this; -} - -inline angles_t operator*( const angles_t &a, float b ) { - return angles_t( a.pitch * b, a.yaw * b, a.roll * b ); -} - -inline angles_t operator*( float a, const angles_t &b ) { - return angles_t( a * b.pitch, a * b.yaw, a * b.roll ); -} - -inline angles_t& angles_t::operator*=( float a ) { - pitch *= a; - yaw *= a; - roll *= a; - - return *this; -} - -inline int operator==( angles_t &a, angles_t &b ) { - return ( ( a.pitch == b.pitch ) && ( a.yaw == b.yaw ) && ( a.roll == b.roll ) ); -} - -inline int operator!=( angles_t &a, angles_t &b ) { - return ( ( a.pitch != b.pitch ) || ( a.yaw != b.yaw ) || ( a.roll != b.roll ) ); -} - -inline angles_t& angles_t::Zero( void ) { - pitch = 0.0f; - yaw = 0.0f; - roll = 0.0f; - - return *this; -} - -#endif /* !__MATH_ANGLES_H__ */ diff --git a/tools/urt/libs/splines/math_matrix.cpp b/tools/urt/libs/splines/math_matrix.cpp deleted file mode 100644 index 587a0c8..0000000 --- a/tools/urt/libs/splines/math_matrix.cpp +++ /dev/null @@ -1,134 +0,0 @@ -/* - Copyright (C) 1999-2007 id Software, Inc. and contributors. - For a list of contributors, see the accompanying CONTRIBUTORS file. - - This file is part of GtkRadiant. - - GtkRadiant is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - GtkRadiant is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with GtkRadiant; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - */ - -#include "q_shared.h" - -mat3_t mat3_default( idVec3( 1, 0, 0 ), idVec3( 0, 1, 0 ), idVec3( 0, 0, 1 ) ); - -void toMatrix( quat_t const &src, mat3_t &dst ) { - float wx, wy, wz; - float xx, yy, yz; - float xy, xz, zz; - float x2, y2, z2; - - x2 = src.x + src.x; - y2 = src.y + src.y; - z2 = src.z + src.z; - - xx = src.x * x2; - xy = src.x * y2; - xz = src.x * z2; - - yy = src.y * y2; - yz = src.y * z2; - zz = src.z * z2; - - wx = src.w * x2; - wy = src.w * y2; - wz = src.w * z2; - - dst[ 0 ][ 0 ] = 1.0f - ( yy + zz ); - dst[ 0 ][ 1 ] = xy - wz; - dst[ 0 ][ 2 ] = xz + wy; - - dst[ 1 ][ 0 ] = xy + wz; - dst[ 1 ][ 1 ] = 1.0f - ( xx + zz ); - dst[ 1 ][ 2 ] = yz - wx; - - dst[ 2 ][ 0 ] = xz - wy; - dst[ 2 ][ 1 ] = yz + wx; - dst[ 2 ][ 2 ] = 1.0f - ( xx + yy ); -} - -void toMatrix( angles_t const &src, mat3_t &dst ) { - float angle; - static float sr, sp, sy, cr, cp, cy; // static to help MS compiler fp bugs - - angle = src.yaw * ( M_PI * 2.0f / 360.0f ); - sy = sin( angle ); - cy = cos( angle ); - - angle = src.pitch * ( M_PI * 2.0f / 360.0f ); - sp = sin( angle ); - cp = cos( angle ); - - angle = src.roll * ( M_PI * 2.0f / 360.0f ); - sr = sin( angle ); - cr = cos( angle ); - - dst[ 0 ].set( cp * cy, cp * sy, -sp ); - dst[ 1 ].set( sr * sp * cy + cr * -sy, sr * sp * sy + cr * cy, sr * cp ); - dst[ 2 ].set( cr * sp * cy + -sr * -sy, cr * sp * sy + -sr * cy, cr * cp ); -} - -void toMatrix( idVec3 const &src, mat3_t &dst ) { - angles_t sup = src; - toMatrix( sup, dst ); -} - -void mat3_t::ProjectVector( const idVec3 &src, idVec3 &dst ) const { - dst.x = src * mat[ 0 ]; - dst.y = src * mat[ 1 ]; - dst.z = src * mat[ 2 ]; -} - -void mat3_t::UnprojectVector( const idVec3 &src, idVec3 &dst ) const { - dst = mat[ 0 ] * src.x + mat[ 1 ] * src.y + mat[ 2 ] * src.z; -} - -void mat3_t::Transpose( mat3_t &matrix ) { - int i; - int j; - - for ( i = 0; i < 3; i++ ) { - for ( j = 0; j < 3; j++ ) { - matrix[ i ][ j ] = mat[ j ][ i ]; - } - } -} - -void mat3_t::Transpose( void ) { - float temp; - int i; - int j; - - for ( i = 0; i < 3; i++ ) { - for ( j = i + 1; j < 3; j++ ) { - temp = mat[ i ][ j ]; - mat[ i ][ j ] = mat[ j ][ i ]; - mat[ j ][ i ] = temp; - } - } -} - -mat3_t mat3_t::Inverse( void ) const { - mat3_t inv( *this ); - - inv.Transpose(); - - return inv; -} - -void mat3_t::Clear( void ) { - mat[0].set( 1, 0, 0 ); - mat[1].set( 0, 1, 0 ); - mat[2].set( 0, 0, 1 ); -} diff --git a/tools/urt/libs/splines/math_matrix.h b/tools/urt/libs/splines/math_matrix.h deleted file mode 100644 index 41216ee..0000000 --- a/tools/urt/libs/splines/math_matrix.h +++ /dev/null @@ -1,223 +0,0 @@ -/* - Copyright (C) 1999-2007 id Software, Inc. and contributors. - For a list of contributors, see the accompanying CONTRIBUTORS file. - - This file is part of GtkRadiant. - - GtkRadiant is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - GtkRadiant is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with GtkRadiant; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - */ - -#ifndef __MATH_MATRIX_H__ -#define __MATH_MATRIX_H__ - -#include -#include "math_vector.h" - -#ifndef ID_INLINE -#ifdef _WIN32 -#define ID_INLINE __inline -#else -#define ID_INLINE inline -#endif -#endif - -class quat_t; -class angles_t; - -class mat3_t { -public: -idVec3 mat[ 3 ]; - -mat3_t(); -mat3_t( float src[ 3 ][ 3 ] ); -mat3_t( idVec3 const &x, idVec3 const &y, idVec3 const &z ); -mat3_t( const float xx, const float xy, const float xz, const float yx, const float yy, const float yz, const float zx, const float zy, const float zz ); - -friend void toMatrix( quat_t const &src, mat3_t &dst ); -friend void toMatrix( angles_t const &src, mat3_t &dst ); -friend void toMatrix( idVec3 const &src, mat3_t &dst ); - -idVec3 operator[]( int index ) const; -idVec3 &operator[]( int index ); - -idVec3 operator*( const idVec3 &vec ) const; -mat3_t operator*( const mat3_t &a ) const; -mat3_t operator*( float a ) const; -mat3_t operator+( mat3_t const &a ) const; -mat3_t operator-( mat3_t const &a ) const; - -friend idVec3 operator*( const idVec3 &vec, const mat3_t &mat ); -friend mat3_t operator*( float a, mat3_t const &b ); - -mat3_t &operator*=( float a ); -mat3_t &operator+=( mat3_t const &a ); -mat3_t &operator-=( mat3_t const &a ); - -void Clear( void ); - -void ProjectVector( const idVec3 &src, idVec3 &dst ) const; -void UnprojectVector( const idVec3 &src, idVec3 &dst ) const; - -void OrthoNormalize( void ); -void Transpose( mat3_t &matrix ); -void Transpose( void ); -mat3_t Inverse( void ) const; -void Identity( void ); - -friend void InverseMultiply( const mat3_t &inv, const mat3_t &b, mat3_t &dst ); -friend mat3_t SkewSymmetric( idVec3 const &src ); -}; - -ID_INLINE mat3_t::mat3_t() { -} - -ID_INLINE mat3_t::mat3_t( float src[ 3 ][ 3 ] ) { - memcpy( mat, src, sizeof( src ) ); -} - -ID_INLINE mat3_t::mat3_t( idVec3 const &x, idVec3 const &y, idVec3 const &z ) { - mat[ 0 ].x = x.x; mat[ 0 ].y = x.y; mat[ 0 ].z = x.z; - mat[ 1 ].x = y.x; mat[ 1 ].y = y.y; mat[ 1 ].z = y.z; - mat[ 2 ].x = z.x; mat[ 2 ].y = z.y; mat[ 2 ].z = z.z; -} - -ID_INLINE mat3_t::mat3_t( const float xx, const float xy, const float xz, const float yx, const float yy, const float yz, const float zx, const float zy, const float zz ) { - mat[ 0 ].x = xx; mat[ 0 ].y = xy; mat[ 0 ].z = xz; - mat[ 1 ].x = yx; mat[ 1 ].y = yy; mat[ 1 ].z = yz; - mat[ 2 ].x = zx; mat[ 2 ].y = zy; mat[ 2 ].z = zz; -} - -ID_INLINE idVec3 mat3_t::operator[]( int index ) const { - assert( ( index >= 0 ) && ( index < 3 ) ); - return mat[ index ]; -} - -ID_INLINE idVec3& mat3_t::operator[]( int index ) { - assert( ( index >= 0 ) && ( index < 3 ) ); - return mat[ index ]; -} - -ID_INLINE idVec3 mat3_t::operator*( const idVec3 &vec ) const { - return idVec3( - mat[ 0 ].x * vec.x + mat[ 1 ].x * vec.y + mat[ 2 ].x * vec.z, - mat[ 0 ].y * vec.x + mat[ 1 ].y * vec.y + mat[ 2 ].y * vec.z, - mat[ 0 ].z * vec.x + mat[ 1 ].z * vec.y + mat[ 2 ].z * vec.z ); -} - -ID_INLINE mat3_t mat3_t::operator*( const mat3_t &a ) const { - return mat3_t( - mat[0].x * a[0].x + mat[0].y * a[1].x + mat[0].z * a[2].x, - mat[0].x * a[0].y + mat[0].y * a[1].y + mat[0].z * a[2].y, - mat[0].x * a[0].z + mat[0].y * a[1].z + mat[0].z * a[2].z, - mat[1].x * a[0].x + mat[1].y * a[1].x + mat[1].z * a[2].x, - mat[1].x * a[0].y + mat[1].y * a[1].y + mat[1].z * a[2].y, - mat[1].x * a[0].z + mat[1].y * a[1].z + mat[1].z * a[2].z, - mat[2].x * a[0].x + mat[2].y * a[1].x + mat[2].z * a[2].x, - mat[2].x * a[0].y + mat[2].y * a[1].y + mat[2].z * a[2].y, - mat[2].x * a[0].z + mat[2].y * a[1].z + mat[2].z * a[2].z ); -} - -ID_INLINE mat3_t mat3_t::operator*( float a ) const { - return mat3_t( - mat[0].x * a, mat[0].y * a, mat[0].z * a, - mat[1].x * a, mat[1].y * a, mat[1].z * a, - mat[2].x * a, mat[2].y * a, mat[2].z * a ); -} - -ID_INLINE mat3_t mat3_t::operator+( mat3_t const &a ) const { - return mat3_t( - mat[0].x + a[0].x, mat[0].y + a[0].y, mat[0].z + a[0].z, - mat[1].x + a[1].x, mat[1].y + a[1].y, mat[1].z + a[1].z, - mat[2].x + a[2].x, mat[2].y + a[2].y, mat[2].z + a[2].z ); -} - -ID_INLINE mat3_t mat3_t::operator-( mat3_t const &a ) const { - return mat3_t( - mat[0].x - a[0].x, mat[0].y - a[0].y, mat[0].z - a[0].z, - mat[1].x - a[1].x, mat[1].y - a[1].y, mat[1].z - a[1].z, - mat[2].x - a[2].x, mat[2].y - a[2].y, mat[2].z - a[2].z ); -} - -ID_INLINE idVec3 operator*( const idVec3 &vec, const mat3_t &mat ) { - return idVec3( - mat[ 0 ].x * vec.x + mat[ 1 ].x * vec.y + mat[ 2 ].x * vec.z, - mat[ 0 ].y * vec.x + mat[ 1 ].y * vec.y + mat[ 2 ].y * vec.z, - mat[ 0 ].z * vec.x + mat[ 1 ].z * vec.y + mat[ 2 ].z * vec.z ); -} - -ID_INLINE mat3_t operator*( float a, mat3_t const &b ) { - return mat3_t( - b[0].x * a, b[0].y * a, b[0].z * a, - b[1].x * a, b[1].y * a, b[1].z * a, - b[2].x * a, b[2].y * a, b[2].z * a ); -} - -ID_INLINE mat3_t &mat3_t::operator*=( float a ) { - mat[0].x *= a; mat[0].y *= a; mat[0].z *= a; - mat[1].x *= a; mat[1].y *= a; mat[1].z *= a; - mat[2].x *= a; mat[2].y *= a; mat[2].z *= a; - - return *this; -} - -ID_INLINE mat3_t &mat3_t::operator+=( mat3_t const &a ) { - mat[0].x += a[0].x; mat[0].y += a[0].y; mat[0].z += a[0].z; - mat[1].x += a[1].x; mat[1].y += a[1].y; mat[1].z += a[1].z; - mat[2].x += a[2].x; mat[2].y += a[2].y; mat[2].z += a[2].z; - - return *this; -} - -ID_INLINE mat3_t &mat3_t::operator-=( mat3_t const &a ) { - mat[0].x -= a[0].x; mat[0].y -= a[0].y; mat[0].z -= a[0].z; - mat[1].x -= a[1].x; mat[1].y -= a[1].y; mat[1].z -= a[1].z; - mat[2].x -= a[2].x; mat[2].y -= a[2].y; mat[2].z -= a[2].z; - - return *this; -} - -ID_INLINE void mat3_t::OrthoNormalize( void ) { - mat[ 0 ].Normalize(); - mat[ 2 ].Cross( mat[ 0 ], mat[ 1 ] ); - mat[ 2 ].Normalize(); - mat[ 1 ].Cross( mat[ 2 ], mat[ 0 ] ); - mat[ 1 ].Normalize(); -} - -ID_INLINE void mat3_t::Identity( void ) { - mat[ 0 ].x = 1.f; mat[ 0 ].y = 0.f; mat[ 0 ].z = 0.f; - mat[ 1 ].x = 0.f; mat[ 1 ].y = 1.f; mat[ 1 ].z = 0.f; - mat[ 2 ].x = 0.f; mat[ 2 ].y = 0.f; mat[ 2 ].z = 1.f; -} - -ID_INLINE void InverseMultiply( const mat3_t &inv, const mat3_t &b, mat3_t &dst ) { - dst[0].x = inv[0].x * b[0].x + inv[1].x * b[1].x + inv[2].x * b[2].x; - dst[0].y = inv[0].x * b[0].y + inv[1].x * b[1].y + inv[2].x * b[2].y; - dst[0].z = inv[0].x * b[0].z + inv[1].x * b[1].z + inv[2].x * b[2].z; - dst[1].x = inv[0].y * b[0].x + inv[1].y * b[1].x + inv[2].y * b[2].x; - dst[1].y = inv[0].y * b[0].y + inv[1].y * b[1].y + inv[2].y * b[2].y; - dst[1].z = inv[0].y * b[0].z + inv[1].y * b[1].z + inv[2].y * b[2].z; - dst[2].x = inv[0].z * b[0].x + inv[1].z * b[1].x + inv[2].z * b[2].x; - dst[2].y = inv[0].z * b[0].y + inv[1].z * b[1].y + inv[2].z * b[2].y; - dst[2].z = inv[0].z * b[0].z + inv[1].z * b[1].z + inv[2].z * b[2].z; -} - -ID_INLINE mat3_t SkewSymmetric( idVec3 const &src ) { - return mat3_t( 0.0f, -src.z, src.y, src.z, 0.0f, -src.x, -src.y, src.x, 0.0f ); -} - -extern mat3_t mat3_default; - -#endif /* !__MATH_MATRIX_H__ */ diff --git a/tools/urt/libs/splines/math_quaternion.cpp b/tools/urt/libs/splines/math_quaternion.cpp deleted file mode 100644 index 7246432..0000000 --- a/tools/urt/libs/splines/math_quaternion.cpp +++ /dev/null @@ -1,79 +0,0 @@ -/* - Copyright (C) 1999-2007 id Software, Inc. and contributors. - For a list of contributors, see the accompanying CONTRIBUTORS file. - - This file is part of GtkRadiant. - - GtkRadiant is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - GtkRadiant is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with GtkRadiant; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - */ - -#include "math_quaternion.h" -#include "math_matrix.h" - -void toQuat( idVec3 &src, quat_t &dst ) { - dst.x = src.x; - dst.y = src.y; - dst.z = src.z; - dst.w = 0.0f; -} - -void toQuat( angles_t &src, quat_t &dst ) { - mat3_t temp; - - toMatrix( src, temp ); - toQuat( temp, dst ); -} - -void toQuat( mat3_t &src, quat_t &dst ) { - float trace; - float s; - int i; - int j; - int k; - - static int next[ 3 ] = { 1, 2, 0 }; - - trace = src[ 0 ][ 0 ] + src[ 1 ][ 1 ] + src[ 2 ][ 2 ]; - if ( trace > 0.0f ) { - s = ( float )sqrt( trace + 1.0f ); - dst.w = s * 0.5f; - s = 0.5f / s; - - dst.x = ( src[ 2 ][ 1 ] - src[ 1 ][ 2 ] ) * s; - dst.y = ( src[ 0 ][ 2 ] - src[ 2 ][ 0 ] ) * s; - dst.z = ( src[ 1 ][ 0 ] - src[ 0 ][ 1 ] ) * s; - } - else { - i = 0; - if ( src[ 1 ][ 1 ] > src[ 0 ][ 0 ] ) { - i = 1; - } - if ( src[ 2 ][ 2 ] > src[ i ][ i ] ) { - i = 2; - } - - j = next[ i ]; - k = next[ j ]; - - s = ( float )sqrt( ( src[ i ][ i ] - ( src[ j ][ j ] + src[ k ][ k ] ) ) + 1.0f ); - dst[ i ] = s * 0.5f; - - s = 0.5f / s; - - dst.w = ( src[ k ][ j ] - src[ j ][ k ] ) * s; - dst[ j ] = ( src[ j ][ i ] + src[ i ][ j ] ) * s; - dst[ k ] = ( src[ k ][ i ] + src[ i ][ k ] ) * s; - } -} diff --git a/tools/urt/libs/splines/math_quaternion.h b/tools/urt/libs/splines/math_quaternion.h deleted file mode 100644 index b7754f0..0000000 --- a/tools/urt/libs/splines/math_quaternion.h +++ /dev/null @@ -1,190 +0,0 @@ -/* - Copyright (C) 1999-2007 id Software, Inc. and contributors. - For a list of contributors, see the accompanying CONTRIBUTORS file. - - This file is part of GtkRadiant. - - GtkRadiant is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - GtkRadiant is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with GtkRadiant; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - */ - -#ifndef __MATH_QUATERNION_H__ -#define __MATH_QUATERNION_H__ - -#include -#include - -class idVec3_t; -class angles_t; -class mat3_t; - -class quat_t { -public: -float x; -float y; -float z; -float w; - -quat_t(); -quat_t( float x, float y, float z, float w ); - -friend void toQuat( idVec3_t &src, quat_t &dst ); -friend void toQuat( angles_t &src, quat_t &dst ); -friend void toQuat( mat3_t &src, quat_t &dst ); - -float *vec4( void ); - -float operator[]( int index ) const; -float &operator[]( int index ); - -void set( float x, float y, float z, float w ); - -void operator=( quat_t a ); - -friend quat_t operator+( quat_t a, quat_t b ); -quat_t &operator+=( quat_t a ); - -friend quat_t operator-( quat_t a, quat_t b ); -quat_t &operator-=( quat_t a ); - -friend quat_t operator*( quat_t a, float b ); -friend quat_t operator*( float a, quat_t b ); -quat_t &operator*=( float a ); - -friend int operator==( quat_t a, quat_t b ); -friend int operator!=( quat_t a, quat_t b ); - -float Length( void ); -quat_t &Normalize( void ); - -quat_t operator-(); -}; - -inline quat_t::quat_t() { -} - -inline quat_t::quat_t( float x, float y, float z, float w ) { - this->x = x; - this->y = y; - this->z = z; - this->w = w; -} - -inline float *quat_t::vec4( void ) { - return &x; -} - -inline float quat_t::operator[]( int index ) const { - assert( ( index >= 0 ) && ( index < 4 ) ); - return ( &x )[ index ]; -} - -inline float& quat_t::operator[]( int index ) { - assert( ( index >= 0 ) && ( index < 4 ) ); - return ( &x )[ index ]; -} - -inline void quat_t::set( float x, float y, float z, float w ) { - this->x = x; - this->y = y; - this->z = z; - this->w = w; -} - -inline void quat_t::operator=( quat_t a ) { - x = a.x; - y = a.y; - z = a.z; - w = a.w; -} - -inline quat_t operator+( quat_t a, quat_t b ) { - return quat_t( a.x + b.x, a.y + b.y, a.z + b.z, a.w + b.w ); -} - -inline quat_t& quat_t::operator+=( quat_t a ) { - x += a.x; - y += a.y; - z += a.z; - w += a.w; - - return *this; -} - -inline quat_t operator-( quat_t a, quat_t b ) { - return quat_t( a.x - b.x, a.y - b.y, a.z - b.z, a.w - b.w ); -} - -inline quat_t& quat_t::operator-=( quat_t a ) { - x -= a.x; - y -= a.y; - z -= a.z; - w -= a.w; - - return *this; -} - -inline quat_t operator*( quat_t a, float b ) { - return quat_t( a.x * b, a.y * b, a.z * b, a.w * b ); -} - -inline quat_t operator*( float a, quat_t b ) { - return b * a; -} - -inline quat_t& quat_t::operator*=( float a ) { - x *= a; - y *= a; - z *= a; - w *= a; - - return *this; -} - -inline int operator==( quat_t a, quat_t b ) { - return ( ( a.x == b.x ) && ( a.y == b.y ) && ( a.z == b.z ) && ( a.w == b.w ) ); -} - -inline int operator!=( quat_t a, quat_t b ) { - return ( ( a.x != b.x ) || ( a.y != b.y ) || ( a.z != b.z ) && ( a.w != b.w ) ); -} - -inline float quat_t::Length( void ) { - float length; - - length = x * x + y * y + z * z + w * w; - return ( float )sqrt( length ); -} - -inline quat_t& quat_t::Normalize( void ) { - float length; - float ilength; - - length = this->Length(); - if ( length ) { - ilength = 1 / length; - x *= ilength; - y *= ilength; - z *= ilength; - w *= ilength; - } - - return *this; -} - -inline quat_t quat_t::operator-() { - return quat_t( -x, -y, -z, -w ); -} - -#endif /* !__MATH_QUATERNION_H__ */ diff --git a/tools/urt/libs/splines/math_vector.cpp b/tools/urt/libs/splines/math_vector.cpp deleted file mode 100644 index a7d4367..0000000 --- a/tools/urt/libs/splines/math_vector.cpp +++ /dev/null @@ -1,147 +0,0 @@ -/* - Copyright (C) 1999-2007 id Software, Inc. and contributors. - For a list of contributors, see the accompanying CONTRIBUTORS file. - - This file is part of GtkRadiant. - - GtkRadiant is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - GtkRadiant is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with GtkRadiant; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - */ - -#include "math_vector.h" -#include -#include -#include -#include -#include -#include -#include -#include - -#define M_PI 3.14159265358979323846 // matches value in gcc v2 math.h - -#define LERP_DELTA 1e-6 - -idVec3 vec_zero( 0.0f, 0.0f, 0.0f ); - -Bounds boundsZero; - -float idVec3::toYaw( void ) { - float yaw; - - if ( ( y == 0 ) && ( x == 0 ) ) { - yaw = 0; - } - else { - yaw = atan2( y, x ) * 180 / M_PI; - if ( yaw < 0 ) { - yaw += 360; - } - } - - return yaw; -} - -float idVec3::toPitch( void ) { - float forward; - float pitch; - - if ( ( x == 0 ) && ( y == 0 ) ) { - if ( z > 0 ) { - pitch = 90; - } - else { - pitch = 270; - } - } - else { - forward = ( float )idSqrt( x * x + y * y ); - pitch = atan2( z, forward ) * 180 / M_PI; - if ( pitch < 0 ) { - pitch += 360; - } - } - - return pitch; -} - -/* - angles_t idVec3::toAngles( void ) { - float forward; - float yaw; - float pitch; - - if ( ( x == 0 ) && ( y == 0 ) ) { - yaw = 0; - if ( z > 0 ) { - pitch = 90; - } else { - pitch = 270; - } - } else { - yaw = atan2( y, x ) * 180 / M_PI; - if ( yaw < 0 ) { - yaw += 360; - } - - forward = ( float )idSqrt( x * x + y * y ); - pitch = atan2( z, forward ) * 180 / M_PI; - if ( pitch < 0 ) { - pitch += 360; - } - } - - return angles_t( -pitch, yaw, 0 ); - } - */ - -idVec3 LerpVector( idVec3 &w1, idVec3 &w2, const float t ) { - float omega, cosom, sinom, scale0, scale1; - - cosom = w1 * w2; - if ( ( 1.0 - cosom ) > LERP_DELTA ) { - omega = acos( cosom ); - sinom = sin( omega ); - scale0 = sin( ( 1.0 - t ) * omega ) / sinom; - scale1 = sin( t * omega ) / sinom; - } - else { - scale0 = 1.0 - t; - scale1 = t; - } - - return ( w1 * scale0 + w2 * scale1 ); -} - -/* - ============= - idVec3::string - - This is just a convenience function - for printing vectors - ============= - */ -char *idVec3::string( void ) { - static int index = 0; - static char str[ 8 ][ 36 ]; - char *s; - - // use an array so that multiple toString's won't collide - s = str[ index ]; - index = ( index + 1 ) & 7; - - sprintf( s, "%.2f %.2f %.2f", x, y, z ); - - return s; -} diff --git a/tools/urt/libs/splines/math_vector.h b/tools/urt/libs/splines/math_vector.h deleted file mode 100644 index f85ba9c..0000000 --- a/tools/urt/libs/splines/math_vector.h +++ /dev/null @@ -1,578 +0,0 @@ -/* - Copyright (C) 1999-2007 id Software, Inc. and contributors. - For a list of contributors, see the accompanying CONTRIBUTORS file. - - This file is part of GtkRadiant. - - GtkRadiant is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - GtkRadiant is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with GtkRadiant; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - */ - -#ifndef __MATH_VECTOR_H__ -#define __MATH_VECTOR_H__ - -#ifdef WIN32 -#pragma warning(disable : 4244) -#endif - -#include -#include - -//#define DotProduct(a,b) ((a)[0]*(b)[0]+(a)[1]*(b)[1]+(a)[2]*(b)[2]) -//#define VectorSubtract(a,b,c) ((c)[0]=(a)[0]-(b)[0],(c)[1]=(a)[1]-(b)[1],(c)[2]=(a)[2]-(b)[2]) -//#define VectorAdd(a,b,c) ((c)[0]=(a)[0]+(b)[0],(c)[1]=(a)[1]+(b)[1],(c)[2]=(a)[2]+(b)[2]) -//#define VectorCopy(a,b) ((b)[0]=(a)[0],(b)[1]=(a)[1],(b)[2]=(a)[2]) -//#define VectorCopy(a,b) ((b).x=(a).x,(b).y=(a).y,(b).z=(a).z]) - -//#define VectorScale(v, s, o) ((o)[0]=(v)[0]*(s),(o)[1]=(v)[1]*(s),(o)[2]=(v)[2]*(s)) -#define __VectorMA( v, s, b, o ) ( ( o )[0] = ( v )[0] + ( b )[0] * ( s ),( o )[1] = ( v )[1] + ( b )[1] * ( s ),( o )[2] = ( v )[2] + ( b )[2] * ( s ) ) -//#define CrossProduct(a,b,c) ((c)[0]=(a)[1]*(b)[2]-(a)[2]*(b)[1],(c)[1]=(a)[2]*(b)[0]-(a)[0]*(b)[2],(c)[2]=(a)[0]*(b)[1]-(a)[1]*(b)[0]) - -#define DotProduct4( x,y ) ( ( x )[0] * ( y )[0] + ( x )[1] * ( y )[1] + ( x )[2] * ( y )[2] + ( x )[3] * ( y )[3] ) -#define VectorSubtract4( a,b,c ) ( ( c )[0] = ( a )[0] - ( b )[0],( c )[1] = ( a )[1] - ( b )[1],( c )[2] = ( a )[2] - ( b )[2],( c )[3] = ( a )[3] - ( b )[3] ) -#define VectorAdd4( a,b,c ) ( ( c )[0] = ( a )[0] + ( b )[0],( c )[1] = ( a )[1] + ( b )[1],( c )[2] = ( a )[2] + ( b )[2],( c )[3] = ( a )[3] + ( b )[3] ) -#define VectorCopy4( a,b ) ( ( b )[0] = ( a )[0],( b )[1] = ( a )[1],( b )[2] = ( a )[2],( b )[3] = ( a )[3] ) -#define VectorScale4( v, s, o ) ( ( o )[0] = ( v )[0] * ( s ),( o )[1] = ( v )[1] * ( s ),( o )[2] = ( v )[2] * ( s ),( o )[3] = ( v )[3] * ( s ) ) -#define VectorMA4( v, s, b, o ) ( ( o )[0] = ( v )[0] + ( b )[0] * ( s ),( o )[1] = ( v )[1] + ( b )[1] * ( s ),( o )[2] = ( v )[2] + ( b )[2] * ( s ),( o )[3] = ( v )[3] + ( b )[3] * ( s ) ) - - -//#define VectorClear(a) ((a)[0]=(a)[1]=(a)[2]=0) -#define VectorNegate( a,b ) ( ( b )[0] = -( a )[0],( b )[1] = -( a )[1],( b )[2] = -( a )[2] ) -//#define VectorSet(v, x, y, z) ((v)[0]=(x), (v)[1]=(y), (v)[2]=(z)) -#define Vector4Copy( a,b ) ( ( b )[0] = ( a )[0],( b )[1] = ( a )[1],( b )[2] = ( a )[2],( b )[3] = ( a )[3] ) - -#define SnapVector( v ) {v[0] = (int)v[0]; v[1] = (int)v[1]; v[2] = (int)v[2]; } - - -//#include "util_heap.h" - -#ifndef EQUAL_EPSILON -#define EQUAL_EPSILON 0.001 -#endif - -float Q_fabs( float f ); - -#ifndef ID_INLINE -#ifdef _WIN32 -#define ID_INLINE __inline -#else -#define ID_INLINE inline -#endif -#endif - -// if this is defined, vec3 will take four elements, which may allow -// easier SIMD optimizations -//#define FAT_VEC3 -//#ifdef __ppc__ -//#pragma align(16) -//#endif - -class angles_t; -#ifdef __ppc__ -// Vanilla PPC code, but since PPC has a reciprocal square root estimate instruction, -// runs *much* faster than calling sqrt(). We'll use two Newton-Raphson -// refinement steps to get bunch more precision in the 1/sqrt() value for very little cost. -// We'll then multiply 1/sqrt times the original value to get the sqrt. -// This is about 12.4 times faster than sqrt() and according to my testing (not exhaustive) -// it returns fairly accurate results (error below 1.0e-5 up to 100000.0 in 0.1 increments). - -static inline float idSqrt( float x ) { - const float half = 0.5; - const float one = 1.0; - float B, y0, y1; - - // This'll NaN if it hits frsqrte. Handle both +0.0 and -0.0 - if ( fabs( x ) == 0.0 ) { - return x; - } - B = x; - -#ifdef __GNUC__ - asm ( "frsqrte %0,%1" : "=f" ( y0 ) : "f" ( B ) ); -#else - y0 = __frsqrte( B ); -#endif - /* First refinement step */ - - y1 = y0 + half * y0 * ( one - B * y0 * y0 ); - - /* Second refinement step -- copy the output of the last step to the input of this step */ - - y0 = y1; - y1 = y0 + half * y0 * ( one - B * y0 * y0 ); - - /* Get sqrt(x) from x * 1/sqrt(x) */ - return x * y1; -} -#else -static inline double idSqrt( double x ) { - return sqrt( x ); -} -#endif - - -//class idVec3 : public idHeap { -class idVec3 { -public: -#ifndef FAT_VEC3 -float x,y,z; -#else -float x,y,z,dist; -#endif - -#ifndef FAT_VEC3 -idVec3() {}; -#else -idVec3() {dist = 0.0f; }; -#endif -idVec3( const float x, const float y, const float z ); - -operator float *(); - -float operator[]( const int index ) const; -float &operator[]( const int index ); - -void set( const float x, const float y, const float z ); - -idVec3 operator-() const; - -idVec3 &operator=( const idVec3 &a ); - -float operator*( const idVec3 &a ) const; -idVec3 operator*( const float a ) const; -friend idVec3 operator*( float a, idVec3 b ); - -idVec3 operator+( const idVec3 &a ) const; -idVec3 operator-( const idVec3 &a ) const; - -idVec3 &operator+=( const idVec3 &a ); -idVec3 &operator-=( const idVec3 &a ); -idVec3 &operator*=( const float a ); - -int operator==( const idVec3 &a ) const; -int operator!=( const idVec3 &a ) const; - -idVec3 Cross( const idVec3 &a ) const; -idVec3 &Cross( const idVec3 &a, const idVec3 &b ); - -float Length( void ) const; -float Normalize( void ); - -void Zero( void ); -void Snap( void ); -void SnapTowards( const idVec3 &to ); - -float toYaw( void ); -float toPitch( void ); -angles_t toAngles( void ); -friend idVec3 LerpVector( const idVec3 &w1, const idVec3 &w2, const float t ); - -char *string( void ); -}; - -extern idVec3 vec_zero; - -ID_INLINE idVec3::idVec3( const float x, const float y, const float z ) { - this->x = x; - this->y = y; - this->z = z; -#ifdef FAT_VEC3 - this->dist = 0.0f; -#endif -} - -ID_INLINE float idVec3::operator[]( const int index ) const { - return ( &x )[ index ]; -} - -ID_INLINE float &idVec3::operator[]( const int index ) { - return ( &x )[ index ]; -} - -ID_INLINE idVec3::operator float *( void ) { - return &x; -} - -ID_INLINE idVec3 idVec3::operator-() const { - return idVec3( -x, -y, -z ); -} - -ID_INLINE idVec3 &idVec3::operator=( const idVec3 &a ) { - x = a.x; - y = a.y; - z = a.z; - - return *this; -} - -ID_INLINE void idVec3::set( const float x, const float y, const float z ) { - this->x = x; - this->y = y; - this->z = z; -} - -ID_INLINE idVec3 idVec3::operator-( const idVec3 &a ) const { - return idVec3( x - a.x, y - a.y, z - a.z ); -} - -ID_INLINE float idVec3::operator*( const idVec3 &a ) const { - return x * a.x + y * a.y + z * a.z; -} - -ID_INLINE idVec3 idVec3::operator*( const float a ) const { - return idVec3( x * a, y * a, z * a ); -} - -ID_INLINE idVec3 operator*( const float a, const idVec3 b ) { - return idVec3( b.x * a, b.y * a, b.z * a ); -} - -ID_INLINE idVec3 idVec3::operator+( const idVec3 &a ) const { - return idVec3( x + a.x, y + a.y, z + a.z ); -} - -ID_INLINE idVec3 &idVec3::operator+=( const idVec3 &a ) { - x += a.x; - y += a.y; - z += a.z; - - return *this; -} - -ID_INLINE idVec3 &idVec3::operator-=( const idVec3 &a ) { - x -= a.x; - y -= a.y; - z -= a.z; - - return *this; -} - -ID_INLINE idVec3 &idVec3::operator*=( const float a ) { - x *= a; - y *= a; - z *= a; - - return *this; -} - -ID_INLINE int idVec3::operator==( const idVec3 &a ) const { - if ( Q_fabs( x - a.x ) > EQUAL_EPSILON ) { - return false; - } - - if ( Q_fabs( y - a.y ) > EQUAL_EPSILON ) { - return false; - } - - if ( Q_fabs( z - a.z ) > EQUAL_EPSILON ) { - return false; - } - - return true; -} - -ID_INLINE int idVec3::operator!=( const idVec3 &a ) const { - if ( Q_fabs( x - a.x ) > EQUAL_EPSILON ) { - return true; - } - - if ( Q_fabs( y - a.y ) > EQUAL_EPSILON ) { - return true; - } - - if ( Q_fabs( z - a.z ) > EQUAL_EPSILON ) { - return true; - } - - return false; -} - -ID_INLINE idVec3 idVec3::Cross( const idVec3 &a ) const { - return idVec3( y * a.z - z * a.y, z * a.x - x * a.z, x * a.y - y * a.x ); -} - -ID_INLINE idVec3 &idVec3::Cross( const idVec3 &a, const idVec3 &b ) { - x = a.y * b.z - a.z * b.y; - y = a.z * b.x - a.x * b.z; - z = a.x * b.y - a.y * b.x; - - return *this; -} - -ID_INLINE float idVec3::Length( void ) const { - float length; - - length = x * x + y * y + z * z; - return ( float )idSqrt( length ); -} - -ID_INLINE float idVec3::Normalize( void ) { - float length; - float ilength; - - length = this->Length(); - if ( length ) { - ilength = 1.0f / length; - x *= ilength; - y *= ilength; - z *= ilength; - } - - return length; -} - -ID_INLINE void idVec3::Zero( void ) { - x = 0.0f; - y = 0.0f; - z = 0.0f; -} - -ID_INLINE void idVec3::Snap( void ) { - x = float( int( x ) ); - y = float( int( y ) ); - z = float( int( z ) ); -} - -/* - ====================== - SnapTowards - - Round a vector to integers for more efficient network - transmission, but make sure that it rounds towards a given point - rather than blindly truncating. This prevents it from truncating - into a wall. - ====================== - */ -ID_INLINE void idVec3::SnapTowards( const idVec3 &to ) { - if ( to.x <= x ) { - x = float( int( x ) ); - } - else { - x = float( int( x ) + 1 ); - } - - if ( to.y <= y ) { - y = float( int( y ) ); - } - else { - y = float( int( y ) + 1 ); - } - - if ( to.z <= z ) { - z = float( int( z ) ); - } - else { - z = float( int( z ) + 1 ); - } -} - -//=============================================================== - -class Bounds { -public: -idVec3 b[2]; - -Bounds(); -Bounds( const idVec3 &mins, const idVec3 &maxs ); - -void Clear(); -void Zero(); -float Radius(); // radius from origin, not from center -idVec3 Center(); -void AddPoint( const idVec3 &v ); -void AddBounds( const Bounds &bb ); -bool IsCleared(); -bool ContainsPoint( const idVec3 &p ); -bool IntersectsBounds( const Bounds &b2 ); // touching is NOT intersecting -}; - -extern Bounds boundsZero; - -ID_INLINE Bounds::Bounds(){ -} - -ID_INLINE bool Bounds::IsCleared() { - return b[0][0] > b[1][0]; -} - -ID_INLINE bool Bounds::ContainsPoint( const idVec3 &p ) { - if ( p[0] < b[0][0] || p[1] < b[0][1] || p[2] < b[0][2] - || p[0] > b[1][0] || p[1] > b[1][1] || p[2] > b[1][2] ) { - return false; - } - return true; -} - -ID_INLINE bool Bounds::IntersectsBounds( const Bounds &b2 ) { - if ( b2.b[1][0] < b[0][0] || b2.b[1][1] < b[0][1] || b2.b[1][2] < b[0][2] - || b2.b[0][0] > b[1][0] || b2.b[0][1] > b[1][1] || b2.b[0][2] > b[1][2] ) { - return false; - } - return true; -} - -ID_INLINE Bounds::Bounds( const idVec3 &mins, const idVec3 &maxs ) { - b[0] = mins; - b[1] = maxs; -} - -ID_INLINE idVec3 Bounds::Center() { - return idVec3( ( b[1][0] + b[0][0] ) * 0.5f, ( b[1][1] + b[0][1] ) * 0.5f, ( b[1][2] + b[0][2] ) * 0.5f ); -} - -ID_INLINE void Bounds::Clear() { - b[0][0] = b[0][1] = b[0][2] = 99999; - b[1][0] = b[1][1] = b[1][2] = -99999; -} - -ID_INLINE void Bounds::Zero() { - b[0][0] = b[0][1] = b[0][2] = - b[1][0] = b[1][1] = b[1][2] = 0; -} - -ID_INLINE void Bounds::AddPoint( const idVec3 &v ) { - if ( v[0] < b[0][0] ) { - b[0][0] = v[0]; - } - if ( v[0] > b[1][0] ) { - b[1][0] = v[0]; - } - if ( v[1] < b[0][1] ) { - b[0][1] = v[1]; - } - if ( v[1] > b[1][1] ) { - b[1][1] = v[1]; - } - if ( v[2] < b[0][2] ) { - b[0][2] = v[2]; - } - if ( v[2] > b[1][2] ) { - b[1][2] = v[2]; - } -} - - -ID_INLINE void Bounds::AddBounds( const Bounds &bb ) { - if ( bb.b[0][0] < b[0][0] ) { - b[0][0] = bb.b[0][0]; - } - if ( bb.b[0][1] < b[0][1] ) { - b[0][1] = bb.b[0][1]; - } - if ( bb.b[0][2] < b[0][2] ) { - b[0][2] = bb.b[0][2]; - } - - if ( bb.b[1][0] > b[1][0] ) { - b[1][0] = bb.b[1][0]; - } - if ( bb.b[1][1] > b[1][1] ) { - b[1][1] = bb.b[1][1]; - } - if ( bb.b[1][2] > b[1][2] ) { - b[1][2] = bb.b[1][2]; - } -} - -ID_INLINE float Bounds::Radius() { - int i; - float total; - float a, aa; - - total = 0; - for ( i = 0 ; i < 3 ; i++ ) { - a = (float)fabs( b[0][i] ); - aa = (float)fabs( b[1][i] ); - if ( aa > a ) { - a = aa; - } - total += a * a; - } - - return (float)idSqrt( total ); -} - -//=============================================================== - - -class idVec2 { -public: -float x; -float y; - -operator float *(); -float operator[]( int index ) const; -float &operator[]( int index ); -}; - -ID_INLINE float idVec2::operator[]( int index ) const { - return ( &x )[ index ]; -} - -ID_INLINE float& idVec2::operator[]( int index ) { - return ( &x )[ index ]; -} - -ID_INLINE idVec2::operator float *( void ) { - return &x; -} - -class idVec4 : public idVec3 { -public: -#ifndef FAT_VEC3 -float dist; -#endif -idVec4(); -~idVec4() {}; - -idVec4( float x, float y, float z, float dist ); -float operator[]( int index ) const; -float &operator[]( int index ); -}; - -ID_INLINE idVec4::idVec4() {} -ID_INLINE idVec4::idVec4( float x, float y, float z, float dist ) { - this->x = x; - this->y = y; - this->z = z; - this->dist = dist; -} - -ID_INLINE float idVec4::operator[]( int index ) const { - return ( &x )[ index ]; -} - -ID_INLINE float& idVec4::operator[]( int index ) { - return ( &x )[ index ]; -} - - -class idVec5_t : public idVec3 { -public: -float s; -float t; -float operator[]( int index ) const; -float &operator[]( int index ); -}; - - -ID_INLINE float idVec5_t::operator[]( int index ) const { - return ( &x )[ index ]; -} - -ID_INLINE float& idVec5_t::operator[]( int index ) { - return ( &x )[ index ]; -} - -#endif /* !__MATH_VECTOR_H__ */ diff --git a/tools/urt/libs/splines/q_parse.cpp b/tools/urt/libs/splines/q_parse.cpp deleted file mode 100644 index 324cd29..0000000 --- a/tools/urt/libs/splines/q_parse.cpp +++ /dev/null @@ -1,537 +0,0 @@ -/* - Copyright (C) 1999-2007 id Software, Inc. and contributors. - For a list of contributors, see the accompanying CONTRIBUTORS file. - - This file is part of GtkRadiant. - - GtkRadiant is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - GtkRadiant is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with GtkRadiant; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - */ - -// q_parse.c -- support for parsing text files - -#include "q_shared.h" - -/* - ============================================================================ - - PARSING - - ============================================================================ - */ - -// multiple character punctuation tokens -static const char *punctuation[] = { - "+=", "-=", "*=", "/=", "&=", "|=", "++", "--", - "&&", "||", "<=", ">=", "==", "!=", - NULL -}; - -typedef struct { - char token[MAX_TOKEN_CHARS]; - int lines; - qboolean ungetToken; - char parseFile[MAX_QPATH]; -} parseInfo_t; - -#define MAX_PARSE_INFO 16 -static parseInfo_t parseInfo[MAX_PARSE_INFO]; -static int parseInfoNum; -static parseInfo_t *pi = &parseInfo[0]; - -/* - =================== - Com_BeginParseSession - =================== - */ -void Com_BeginParseSession( const char *filename ) { - if ( parseInfoNum == MAX_PARSE_INFO - 1 ) { - Com_Error( ERR_FATAL, "Com_BeginParseSession: session overflow" ); - } - parseInfoNum++; - pi = &parseInfo[parseInfoNum]; - - pi->lines = 1; - Q_strncpyz( pi->parseFile, filename, sizeof( pi->parseFile ) ); -} - -/* - =================== - Com_EndParseSession - =================== - */ -void Com_EndParseSession( void ) { - if ( parseInfoNum == 0 ) { - Com_Error( ERR_FATAL, "Com_EndParseSession: session underflow" ); - } - parseInfoNum--; - pi = &parseInfo[parseInfoNum]; -} - -/* - =================== - Com_GetCurrentParseLine - =================== - */ -int Com_GetCurrentParseLine( void ) { - return pi->lines; -} - -/* - =================== - Com_ScriptError - - Prints the script name and line number in the message - =================== - */ -void Com_ScriptError( const char *msg, ... ) { - va_list argptr; - char string[32000]; - - va_start( argptr, msg ); - vsprintf( string, msg,argptr ); - va_end( argptr ); - - Com_Error( ERR_DROP, "File %s, line %i: %s", pi->parseFile, pi->lines, string ); -} - -void Com_ScriptWarning( const char *msg, ... ) { - va_list argptr; - char string[32000]; - - va_start( argptr, msg ); - vsprintf( string, msg,argptr ); - va_end( argptr ); - - Com_Printf( "File %s, line %i: %s", pi->parseFile, pi->lines, string ); -} - - -/* - =================== - Com_UngetToken - - Calling this will make the next Com_Parse return - the current token instead of advancing the pointer - =================== - */ -void Com_UngetToken( void ) { - if ( pi->ungetToken ) { - Com_ScriptError( "UngetToken called twice" ); - } - pi->ungetToken = qtrue; -} - - -static const char *SkipWhitespace( const char (*data), qboolean *hasNewLines ) { - int c; - - while ( ( c = *data ) <= ' ' ) { - if ( !c ) { - return NULL; - } - if ( c == '\n' ) { - pi->lines++; - *hasNewLines = qtrue; - } - data++; - } - - return data; -} - -/* - ============== - Com_ParseExt - - Parse a token out of a string - Will never return NULL, just empty strings. - An empty string will only be returned at end of file. - - If "allowLineBreaks" is qtrue then an empty - string will be returned if the next token is - a newline. - ============== - */ -static char *Com_ParseExt( const char *( *data_p ), qboolean allowLineBreaks ) { - int c = 0, len; - qboolean hasNewLines = qfalse; - const char *data; - const char **punc; - - if ( !data_p ) { - Com_Error( ERR_FATAL, "Com_ParseExt: NULL data_p" ); - } - - data = *data_p; - len = 0; - pi->token[0] = 0; - - // make sure incoming data is valid - if ( !data ) { - *data_p = NULL; - return pi->token; - } - - // skip any leading whitespace - while ( 1 ) { - // skip whitespace - data = SkipWhitespace( data, &hasNewLines ); - if ( !data ) { - *data_p = NULL; - return pi->token; - } - if ( hasNewLines && !allowLineBreaks ) { - *data_p = data; - return pi->token; - } - - c = *data; - - // skip double slash comments - if ( c == '/' && data[1] == '/' ) { - while ( *data && *data != '\n' ) { - data++; - } - continue; - } - - // skip /* */ comments - if ( c == '/' && data[1] == '*' ) { - while ( *data && ( *data != '*' || data[1] != '/' ) ) { - if ( *data == '\n' ) { - pi->lines++; - } - data++; - } - if ( *data ) { - data += 2; - } - continue; - } - - // a real token to parse - break; - } - - // handle quoted strings - if ( c == '\"' ) { - data++; - while ( 1 ) { - c = *data++; - if ( ( c == '\\' ) && ( *data == '\"' ) ) { - // allow quoted strings to use \" to indicate the " character - data++; - } - else if ( c == '\"' || !c ) { - pi->token[len] = 0; - *data_p = ( char * ) data; - return pi->token; - } - else if ( *data == '\n' ) { - pi->lines++; - } - if ( len < MAX_TOKEN_CHARS - 1 ) { - pi->token[len] = c; - len++; - } - } - } - - // check for a number - // is this parsing of negative numbers going to cause expression problems - if ( ( c >= '0' && c <= '9' ) || ( c == '-' && data[ 1 ] >= '0' && data[ 1 ] <= '9' ) || - ( c == '.' && data[ 1 ] >= '0' && data[ 1 ] <= '9' ) ) { - do { - - if ( len < MAX_TOKEN_CHARS - 1 ) { - pi->token[len] = c; - len++; - } - data++; - - c = *data; - } while ( ( c >= '0' && c <= '9' ) || c == '.' ); - - // parse the exponent - if ( c == 'e' || c == 'E' ) { - if ( len < MAX_TOKEN_CHARS - 1 ) { - pi->token[len] = c; - len++; - } - data++; - c = *data; - - if ( c == '-' || c == '+' ) { - if ( len < MAX_TOKEN_CHARS - 1 ) { - pi->token[len] = c; - len++; - } - data++; - c = *data; - } - - do { - if ( len < MAX_TOKEN_CHARS - 1 ) { - pi->token[len] = c; - len++; - } - data++; - - c = *data; - } while ( c >= '0' && c <= '9' ); - } - - if ( len == MAX_TOKEN_CHARS ) { - len = 0; - } - pi->token[len] = 0; - - *data_p = ( char * ) data; - return pi->token; - } - - // check for a regular word - // we still allow forward and back slashes in name tokens for pathnames - // and also colons for drive letters - if ( ( c >= 'a' && c <= 'z' ) || ( c >= 'A' && c <= 'Z' ) || c == '_' || c == '/' || c == '\\' ) { - do { - if ( len < MAX_TOKEN_CHARS - 1 ) { - pi->token[len] = c; - len++; - } - data++; - - c = *data; - } while ( ( c >= 'a' && c <= 'z' ) || ( c >= 'A' && c <= 'Z' ) || c == '_' - || ( c >= '0' && c <= '9' ) || c == '/' || c == '\\' || c == ':' || c == '.' ); - - if ( len == MAX_TOKEN_CHARS ) { - len = 0; - } - pi->token[len] = 0; - - *data_p = ( char * ) data; - return pi->token; - } - - // check for multi-character punctuation token - for ( punc = punctuation ; *punc ; punc++ ) { - int l; - int j; - - l = strlen( *punc ); - for ( j = 0 ; j < l ; j++ ) { - if ( data[j] != ( *punc )[j] ) { - break; - } - } - if ( j == l ) { - // a valid multi-character punctuation - memcpy( pi->token, *punc, l ); - pi->token[l] = 0; - data += l; - *data_p = (char *)data; - return pi->token; - } - } - - // single character punctuation - pi->token[0] = *data; - pi->token[1] = 0; - data++; - *data_p = (char *)data; - - return pi->token; -} - -/* - =================== - Com_Parse - =================== - */ -const char *Com_Parse( const char *( *data_p ) ) { - if ( pi->ungetToken ) { - pi->ungetToken = qfalse; - return pi->token; - } - return Com_ParseExt( data_p, qtrue ); -} - -/* - =================== - Com_ParseOnLine - =================== - */ -const char *Com_ParseOnLine( const char *( *data_p ) ) { - if ( pi->ungetToken ) { - pi->ungetToken = qfalse; - return pi->token; - } - return Com_ParseExt( data_p, qfalse ); -} - - - -/* - ================== - Com_MatchToken - ================== - */ -void Com_MatchToken( const char *( *buf_p ), const char *match, qboolean warning ) { - const char *token; - - token = Com_Parse( buf_p ); - if ( strcmp( token, match ) ) { - if ( warning ) { - Com_ScriptWarning( "MatchToken: %s != %s", token, match ); - } - else { - Com_ScriptError( "MatchToken: %s != %s", token, match ); - } - } -} - - -/* - ================= - Com_SkipBracedSection - - The next token should be an open brace. - Skips until a matching close brace is found. - Internal brace depths are properly skipped. - ================= - */ -void Com_SkipBracedSection( const char *( *program ) ) { - const char *token; - int depth; - - depth = 0; - do { - token = Com_Parse( program ); - if ( token[1] == 0 ) { - if ( token[0] == '{' ) { - depth++; - } - else if ( token[0] == '}' ) { - depth--; - } - } - } while ( depth && *program ); -} - -/* - ================= - Com_SkipRestOfLine - ================= - */ -void Com_SkipRestOfLine( const char *( *data ) ) { - const char *p; - int c; - - p = *data; - while ( ( c = *p++ ) != 0 ) { - if ( c == '\n' ) { - pi->lines++; - break; - } - } - - *data = p; -} - -/* - ==================== - Com_ParseRestOfLine - ==================== - */ -const char *Com_ParseRestOfLine( const char *( *data_p ) ) { - static char line[MAX_TOKEN_CHARS]; - const char *token; - - line[0] = 0; - while ( 1 ) { - token = Com_ParseOnLine( data_p ); - if ( !token[0] ) { - break; - } - if ( line[0] ) { - Q_strcat( line, sizeof( line ), " " ); - } - Q_strcat( line, sizeof( line ), token ); - } - - return line; -} - - -float Com_ParseFloat( const char *( *buf_p ) ) { - const char *token; - - token = Com_Parse( buf_p ); - if ( !token[0] ) { - return 0; - } - return atof( token ); -} - -int Com_ParseInt( const char *( *buf_p ) ) { - const char *token; - - token = Com_Parse( buf_p ); - if ( !token[0] ) { - return 0; - } - return (int)atof( token ); -} - - - -void Com_Parse1DMatrix( const char *( *buf_p ), int x, float *m ) { - const char *token; - int i; - - Com_MatchToken( buf_p, "(" ); - - for ( i = 0 ; i < x ; i++ ) { - token = Com_Parse( buf_p ); - m[i] = atof( token ); - } - - Com_MatchToken( buf_p, ")" ); -} - -void Com_Parse2DMatrix( const char *( *buf_p ), int y, int x, float *m ) { - int i; - - Com_MatchToken( buf_p, "(" ); - - for ( i = 0 ; i < y ; i++ ) { - Com_Parse1DMatrix( buf_p, x, m + i * x ); - } - - Com_MatchToken( buf_p, ")" ); -} - -void Com_Parse3DMatrix( const char *( *buf_p ), int z, int y, int x, float *m ) { - int i; - - Com_MatchToken( buf_p, "(" ); - - for ( i = 0 ; i < z ; i++ ) { - Com_Parse2DMatrix( buf_p, y, x, m + i * x * y ); - } - - Com_MatchToken( buf_p, ")" ); -} diff --git a/tools/urt/libs/splines/q_shared.cpp b/tools/urt/libs/splines/q_shared.cpp deleted file mode 100644 index 8a93df1..0000000 --- a/tools/urt/libs/splines/q_shared.cpp +++ /dev/null @@ -1,998 +0,0 @@ -/* - Copyright (C) 1999-2007 id Software, Inc. and contributors. - For a list of contributors, see the accompanying CONTRIBUTORS file. - - This file is part of GtkRadiant. - - GtkRadiant is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - GtkRadiant is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with GtkRadiant; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - */ - -// q_shared.c -- stateless support routines that are included in each code dll -#include "q_shared.h" - -/* - ============================================================================ - - GROWLISTS - - ============================================================================ - */ - -// malloc / free all in one place for debugging -extern "C" void *Com_Allocate( int bytes ); -extern "C" void Com_Dealloc( void *ptr ); - -void Com_InitGrowList( growList_t *list, int maxElements ) { - list->maxElements = maxElements; - list->currentElements = 0; - list->elements = (void **)Com_Allocate( list->maxElements * sizeof( void * ) ); -} - -int Com_AddToGrowList( growList_t *list, void *data ) { - void **old; - - if ( list->currentElements != list->maxElements ) { - list->elements[list->currentElements] = data; - return list->currentElements++; - } - - // grow, reallocate and move - old = list->elements; - - if ( list->maxElements < 0 ) { - Com_Error( ERR_FATAL, "Com_AddToGrowList: maxElements = %i", list->maxElements ); - } - - if ( list->maxElements == 0 ) { - // initialize the list to hold 100 elements - Com_InitGrowList( list, 100 ); - return Com_AddToGrowList( list, data ); - } - - list->maxElements *= 2; - - Com_DPrintf( "Resizing growlist to %i maxElements\n", list->maxElements ); - - list->elements = (void **)Com_Allocate( list->maxElements * sizeof( void * ) ); - - if ( !list->elements ) { - Com_Error( ERR_DROP, "Growlist alloc failed" ); - } - - memcpy( list->elements, old, list->currentElements * sizeof( void * ) ); - - Com_Dealloc( old ); - - return Com_AddToGrowList( list, data ); -} - -void *Com_GrowListElement( const growList_t *list, int index ) { - if ( index < 0 || index >= list->currentElements ) { - Com_Error( ERR_DROP, "Com_GrowListElement: %i out of range of %i", - index, list->currentElements ); - } - return list->elements[index]; -} - -int Com_IndexForGrowListElement( const growList_t *list, const void *element ) { - int i; - - for ( i = 0 ; i < list->currentElements ; i++ ) { - if ( list->elements[i] == element ) { - return i; - } - } - return -1; -} - -//============================================================================ - - -float Com_Clamp( float min, float max, float value ) { - if ( value < min ) { - return min; - } - if ( value > max ) { - return max; - } - return value; -} - -/* - ============ - Com_StringContains - ============ - */ -const char *Com_StringContains( const char *str1, const char *str2, int casesensitive ) { - int len, i, j; - - len = strlen( str1 ) - strlen( str2 ); - for ( i = 0; i <= len; i++, str1++ ) { - for ( j = 0; str2[j]; j++ ) { - if ( casesensitive ) { - if ( str1[j] != str2[j] ) { - break; - } - } - else { - if ( toupper( str1[j] ) != toupper( str2[j] ) ) { - break; - } - } - } - if ( !str2[j] ) { - return str1; - } - } - return NULL; -} - -/* - ============ - Com_Filter - ============ - */ -int Com_Filter( const char *filter, const char *name, int casesensitive ){ - char buf[MAX_TOKEN_CHARS]; - const char *ptr; - int i, found; - - while ( *filter ) { - if ( *filter == '*' ) { - filter++; - for ( i = 0; *filter; i++ ) { - if ( *filter == '*' || *filter == '?' ) { - break; - } - buf[i] = *filter; - filter++; - } - buf[i] = '\0'; - if ( strlen( buf ) ) { - ptr = Com_StringContains( name, buf, casesensitive ); - if ( !ptr ) { - return qfalse; - } - name = ptr + strlen( buf ); - } - } - else if ( *filter == '?' ) { - filter++; - name++; - } - else if ( *filter == '[' && *( filter + 1 ) == '[' ) { - filter++; - } - else if ( *filter == '[' ) { - filter++; - found = qfalse; - while ( *filter && !found ) { - if ( *filter == ']' && *( filter + 1 ) != ']' ) { - break; - } - if ( *( filter + 1 ) == '-' && *( filter + 2 ) && ( *( filter + 2 ) != ']' || *( filter + 3 ) == ']' ) ) { - if ( casesensitive ) { - if ( *name >= *filter && *name <= *( filter + 2 ) ) { - found = qtrue; - } - } - else { - if ( toupper( *name ) >= toupper( *filter ) && - toupper( *name ) <= toupper( *( filter + 2 ) ) ) { - found = qtrue; - } - } - filter += 3; - } - else { - if ( casesensitive ) { - if ( *filter == *name ) { - found = qtrue; - } - } - else { - if ( toupper( *filter ) == toupper( *name ) ) { - found = qtrue; - } - } - filter++; - } - } - if ( !found ) { - return qfalse; - } - while ( *filter ) { - if ( *filter == ']' && *( filter + 1 ) != ']' ) { - break; - } - filter++; - } - filter++; - name++; - } - else { - if ( casesensitive ) { - if ( *filter != *name ) { - return qfalse; - } - } - else { - if ( toupper( *filter ) != toupper( *name ) ) { - return qfalse; - } - } - filter++; - name++; - } - } - return qtrue; -} - - -/* - ================ - Com_HashString - - ================ - */ -int Com_HashString( const char *fname ) { - int i; - long hash; - char letter; - - hash = 0; - i = 0; - while ( fname[i] != '\0' ) { - letter = tolower( fname[i] ); - if ( letter == '.' ) { - break; // don't include extension - } - if ( letter == '\\' ) { - letter = '/'; // damn path names - } - hash += (long)( letter ) * ( i + 119 ); - i++; - } - hash &= ( FILE_HASH_SIZE - 1 ); - return hash; -} - - -/* - ============ - Com_SkipPath - ============ - */ -char *Com_SkipPath( char *pathname ){ - char *last; - - last = pathname; - while ( *pathname ) - { - if ( *pathname == '/' ) { - last = pathname + 1; - } - pathname++; - } - return last; -} - -/* - ============ - Com_StripExtension - ============ - */ -void Com_StripExtension( const char *in, char *out ) { - while ( *in && *in != '.' ) { - *out++ = *in++; - } - *out = 0; -} - - -/* - ================== - Com_DefaultExtension - ================== - */ -void Com_DefaultExtension( char *path, int maxSize, const char *extension ) { - char oldPath[MAX_QPATH]; - char *src; - -// -// if path doesn't have a .EXT, append extension -// (extension should include the .) -// - src = path + strlen( path ) - 1; - - while ( *src != '/' && src != path ) { - if ( *src == '.' ) { - return; // it has an extension - } - src--; - } - - Q_strncpyz( oldPath, path, sizeof( oldPath ) ); - Com_sprintf( path, maxSize, "%s%s", oldPath, extension ); -} - -/* - ============================================================================ - - BYTE ORDER FUNCTIONS - - ============================================================================ - */ - -// can't just use function pointers, or dll linkage can -// mess up when qcommon is included in multiple places -static short ( *_BigShort )( short l ); -static short ( *_LittleShort )( short l ); -static int ( *_BigLong )( int l ); -static int ( *_LittleLong )( int l ); -static float ( *_BigFloat )( float l ); -static float ( *_LittleFloat )( float l ); - -short BigShort( short l ){return _BigShort( l ); } -short LittleShort( short l ) {return _LittleShort( l ); } -int BigLong( int l ) {return _BigLong( l ); } -int LittleLong( int l ) {return _LittleLong( l ); } -float BigFloat( float l ) {return _BigFloat( l ); } -float LittleFloat( float l ) {return _LittleFloat( l ); } - -short ShortSwap( short l ){ - byte b1,b2; - - b1 = l & 255; - b2 = ( l >> 8 ) & 255; - - return ( b1 << 8 ) + b2; -} - -short ShortNoSwap( short l ){ - return l; -} - -int LongSwap( int l ){ - byte b1,b2,b3,b4; - - b1 = l & 255; - b2 = ( l >> 8 ) & 255; - b3 = ( l >> 16 ) & 255; - b4 = ( l >> 24 ) & 255; - - return ( (int)b1 << 24 ) + ( (int)b2 << 16 ) + ( (int)b3 << 8 ) + b4; -} - -int LongNoSwap( int l ){ - return l; -} - -float FloatSwap( float f ){ - union - { - float f; - byte b[4]; - } dat1, dat2; - - - dat1.f = f; - dat2.b[0] = dat1.b[3]; - dat2.b[1] = dat1.b[2]; - dat2.b[2] = dat1.b[1]; - dat2.b[3] = dat1.b[0]; - return dat2.f; -} - -float FloatNoSwap( float f ){ - return f; -} - -/* - ================ - Swap_Init - ================ - */ -void Swap_Init( void ){ - byte swaptest[2] = {1,0}; - -// set the byte swapping variables in a portable manner - if ( *(short *)swaptest == 1 ) { - _BigShort = ShortSwap; - _LittleShort = ShortNoSwap; - _BigLong = LongSwap; - _LittleLong = LongNoSwap; - _BigFloat = FloatSwap; - _LittleFloat = FloatNoSwap; - } - else - { - _BigShort = ShortNoSwap; - _LittleShort = ShortSwap; - _BigLong = LongNoSwap; - _LittleLong = LongSwap; - _BigFloat = FloatNoSwap; - _LittleFloat = FloatSwap; - } - -} - -/* - =============== - Com_ParseInfos - =============== - */ -int Com_ParseInfos( const char *buf, int max, char infos[][MAX_INFO_STRING] ) { - const char *token; - int count; - char key[MAX_TOKEN_CHARS]; - - count = 0; - - while ( 1 ) { - token = Com_Parse( &buf ); - if ( !token[0] ) { - break; - } - if ( strcmp( token, "{" ) ) { - Com_Printf( "Missing { in info file\n" ); - break; - } - - if ( count == max ) { - Com_Printf( "Max infos exceeded\n" ); - break; - } - - infos[count][0] = 0; - while ( 1 ) { - token = Com_Parse( &buf ); - if ( !token[0] ) { - Com_Printf( "Unexpected end of info file\n" ); - break; - } - if ( !strcmp( token, "}" ) ) { - break; - } - Q_strncpyz( key, token, sizeof( key ) ); - - token = Com_ParseOnLine( &buf ); - if ( !token[0] ) { - token = ""; - } - Info_SetValueForKey( infos[count], key, token ); - } - count++; - } - - return count; -} - - - -/* - ============================================================================ - - LIBRARY REPLACEMENT FUNCTIONS - - ============================================================================ - */ - -int Q_isprint( int c ){ - if ( c >= 0x20 && c <= 0x7E ) { - return ( 1 ); - } - return ( 0 ); -} - -int Q_islower( int c ){ - if ( c >= 'a' && c <= 'z' ) { - return ( 1 ); - } - return ( 0 ); -} - -int Q_isupper( int c ){ - if ( c >= 'A' && c <= 'Z' ) { - return ( 1 ); - } - return ( 0 ); -} - -int Q_isalpha( int c ){ - if ( ( c >= 'a' && c <= 'z' ) || ( c >= 'A' && c <= 'Z' ) ) { - return ( 1 ); - } - return ( 0 ); -} - -char* Q_strrchr( const char* string, int c ){ - char cc = c; - char *s; - char *sp = (char *)0; - - s = (char*)string; - - while ( *s ) - { - if ( *s == cc ) { - sp = s; - } - s++; - } - if ( cc == 0 ) { - sp = s; - } - - return sp; -} - -/* - ============= - Q_strncpyz - - Safe strncpy that ensures a trailing zero - ============= - */ -void Q_strncpyz( char *dest, const char *src, int destsize ) { - if ( !src ) { - Com_Error( ERR_FATAL, "Q_strncpyz: NULL src" ); - } - if ( destsize < 1 ) { - Com_Error( ERR_FATAL,"Q_strncpyz: destsize < 1" ); - } - - strncpy( dest, src, destsize - 1 ); - dest[destsize - 1] = 0; -} - -int Q_stricmpn( const char *s1, const char *s2, int n ) { - int c1, c2; - - do { - c1 = *s1++; - c2 = *s2++; - - if ( !n-- ) { - return 0; // strings are equal until end point - } - - if ( c1 != c2 ) { - if ( c1 >= 'a' && c1 <= 'z' ) { - c1 -= ( 'a' - 'A' ); - } - if ( c2 >= 'a' && c2 <= 'z' ) { - c2 -= ( 'a' - 'A' ); - } - if ( c1 != c2 ) { - return c1 < c2 ? -1 : 1; - } - } - } while ( c1 ); - - return 0; // strings are equal -} - -int Q_strncmp( const char *s1, const char *s2, int n ) { - int c1, c2; - - do { - c1 = *s1++; - c2 = *s2++; - - if ( !n-- ) { - return 0; // strings are equal until end point - } - - if ( c1 != c2 ) { - return c1 < c2 ? -1 : 1; - } - } while ( c1 ); - - return 0; // strings are equal -} - -int Q_stricmp( const char *s1, const char *s2 ) { - return Q_stricmpn( s1, s2, 99999 ); -} - - -char *Q_strlwr( char *s1 ) { - char *s; - - s = s1; - while ( *s ) { - *s = tolower( *s ); - s++; - } - return s1; -} - -char *Q_strupr( char *s1 ) { - char *s; - - s = s1; - while ( *s ) { - *s = toupper( *s ); - s++; - } - return s1; -} - - -// never goes past bounds or leaves without a terminating 0 -void Q_strcat( char *dest, int size, const char *src ) { - int l1; - - l1 = strlen( dest ); - if ( l1 >= size ) { - Com_Error( ERR_FATAL, "Q_strcat: already overflowed" ); - } - Q_strncpyz( dest + l1, src, size - l1 ); -} - - -int Q_PrintStrlen( const char *string ) { - int len; - const char *p; - - if ( !string ) { - return 0; - } - - len = 0; - p = string; - while ( *p ) { - if ( Q_IsColorString( p ) ) { - p += 2; - continue; - } - p++; - len++; - } - - return len; -} - - -char *Q_CleanStr( char *string ) { - char* d; - char* s; - int c; - - s = string; - d = string; - while ( ( c = *s ) != 0 ) { - if ( Q_IsColorString( s ) ) { - s++; - } - else if ( c >= 0x20 && c <= 0x7E ) { - *d++ = c; - } - s++; - } - *d = '\0'; - - return string; -} - - -void QDECL Com_sprintf( char *dest, int size, const char *fmt, ... ) { - int len; - va_list argptr; - char bigbuffer[32000]; // big, but small enough to fit in PPC stack - - va_start( argptr,fmt ); - len = vsprintf( bigbuffer,fmt,argptr ); - va_end( argptr ); - if ( len >= sizeof( bigbuffer ) ) { - Com_Error( ERR_FATAL, "Com_sprintf: overflowed bigbuffer" ); - } - if ( len >= size ) { - Com_Printf( "Com_sprintf: overflow of %i in %i\n", len, size ); - } - Q_strncpyz( dest, bigbuffer, size ); -} - - -/* - ============ - va - - does a varargs printf into a temp buffer, so I don't need to have - varargs versions of all text functions. - FIXME: make this buffer size safe someday - ============ - */ -char * QDECL va( char *format, ... ) { - va_list argptr; - static char string[2][32000]; // in case va is called by nested functions - static int index = 0; - char *buf; - - buf = string[index & 1]; - index++; - - va_start( argptr, format ); - vsprintf( buf, format,argptr ); - va_end( argptr ); - - return buf; -} - - -/* - ===================================================================== - - INFO STRINGS - - ===================================================================== - */ - -/* - =============== - Info_ValueForKey - - Searches the string for the given - key and returns the associated value, or an empty string. - FIXME: overflow check? - =============== - */ -char *Info_ValueForKey( const char *s, const char *key ) { - char pkey[MAX_INFO_KEY]; - static char value[2][MAX_INFO_VALUE]; // use two buffers so compares - // work without stomping on each other - static int valueindex = 0; - char *o; - - if ( !s || !key ) { - return ""; - } - - if ( strlen( s ) >= MAX_INFO_STRING ) { - Com_Error( ERR_DROP, "Info_ValueForKey: oversize infostring" ); - } - - valueindex ^= 1; - if ( *s == '\\' ) { - s++; - } - while ( 1 ) - { - o = pkey; - while ( *s != '\\' ) - { - if ( !*s ) { - return ""; - } - *o++ = *s++; - } - *o = 0; - s++; - - o = value[valueindex]; - - while ( *s != '\\' && *s ) - { - *o++ = *s++; - } - *o = 0; - - if ( !Q_stricmp( key, pkey ) ) { - return value[valueindex]; - } - - if ( !*s ) { - break; - } - s++; - } - - return ""; -} - - -/* - =================== - Info_NextPair - - Used to itterate through all the key/value pairs in an info string - =================== - */ -void Info_NextPair( const char *( *head ), char key[MAX_INFO_KEY], char value[MAX_INFO_VALUE] ) { - char *o; - const char *s; - - s = *head; - - if ( *s == '\\' ) { - s++; - } - key[0] = 0; - value[0] = 0; - - o = key; - while ( *s != '\\' ) { - if ( !*s ) { - *o = 0; - *head = s; - return; - } - *o++ = *s++; - } - *o = 0; - s++; - - o = value; - while ( *s != '\\' && *s ) { - *o++ = *s++; - } - *o = 0; - - *head = s; -} - - -/* - =================== - Info_RemoveKey - =================== - */ -void Info_RemoveKey( char *s, const char *key ) { - char *start; - char pkey[MAX_INFO_KEY]; - char value[MAX_INFO_VALUE]; - char *o; - - if ( strlen( s ) >= MAX_INFO_STRING ) { - Com_Error( ERR_DROP, "Info_RemoveKey: oversize infostring" ); - } - - if ( strchr( key, '\\' ) ) { - return; - } - - while ( 1 ) - { - start = s; - if ( *s == '\\' ) { - s++; - } - o = pkey; - while ( *s != '\\' ) - { - if ( !*s ) { - return; - } - *o++ = *s++; - } - *o = 0; - s++; - - o = value; - while ( *s != '\\' && *s ) - { - if ( !*s ) { - return; - } - *o++ = *s++; - } - *o = 0; - - if ( !strcmp( key, pkey ) ) { - strcpy( start, s ); // remove this part - return; - } - - if ( !*s ) { - return; - } - } - -} - - -/* - ================== - Info_Validate - - Some characters are illegal in info strings because they - can mess up the server's parsing - ================== - */ -qboolean Info_Validate( const char *s ) { - if ( strchr( s, '\"' ) ) { - return qfalse; - } - if ( strchr( s, ';' ) ) { - return qfalse; - } - return qtrue; -} - -/* - ================== - Info_SetValueForKey - - Changes or adds a key/value pair - ================== - */ -void Info_SetValueForKey( char *s, const char *key, const char *value ) { - char newi[MAX_INFO_STRING]; - - if ( strlen( s ) >= MAX_INFO_STRING ) { - Com_Error( ERR_DROP, "Info_SetValueForKey: oversize infostring" ); - } - - if ( strchr( key, '\\' ) || strchr( value, '\\' ) ) { - Com_Printf( "Can't use keys or values with a \\\n" ); - return; - } - - if ( strchr( key, ';' ) || strchr( value, ';' ) ) { - Com_Printf( "Can't use keys or values with a semicolon\n" ); - return; - } - - if ( strchr( key, '\"' ) || strchr( value, '\"' ) ) { - Com_Printf( "Can't use keys or values with a \"\n" ); - return; - } - - Info_RemoveKey( s, key ); - if ( !value || !strlen( value ) ) { - return; - } - - Com_sprintf( newi, sizeof( newi ), "\\%s\\%s", key, value ); - - if ( strlen( newi ) + strlen( s ) > MAX_INFO_STRING ) { - Com_Printf( "Info string length exceeded\n" ); - return; - } - - strcat( s, newi ); -} - -//==================================================================== - - -/* - =============== - ParseHex - =============== - */ -int ParseHex( const char *text ) { - int value; - int c; - - value = 0; - while ( ( c = *text++ ) != 0 ) { - if ( c >= '0' && c <= '9' ) { - value = value * 16 + c - '0'; - continue; - } - if ( c >= 'a' && c <= 'f' ) { - value = value * 16 + 10 + c - 'a'; - continue; - } - if ( c >= 'A' && c <= 'F' ) { - value = value * 16 + 10 + c - 'A'; - continue; - } - } - - return value; -} diff --git a/tools/urt/libs/splines/q_shared.h b/tools/urt/libs/splines/q_shared.h deleted file mode 100644 index 780ef6d..0000000 --- a/tools/urt/libs/splines/q_shared.h +++ /dev/null @@ -1,795 +0,0 @@ -/* - Copyright (C) 1999-2007 id Software, Inc. and contributors. - For a list of contributors, see the accompanying CONTRIBUTORS file. - - This file is part of GtkRadiant. - - GtkRadiant is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - GtkRadiant is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with GtkRadiant; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - */ - -#ifndef __Q_SHARED_H -#define __Q_SHARED_H - -// q_shared.h -- included first by ALL program modules. -// these are the definitions that have no dependance on -// central system services, and can be used by any part -// of the program without any state issues. - -// A user mod should never modify this file - -#define Q3_VERSION "DOOM 0.01" - -// alignment macros for SIMD -#define ALIGN_ON -#define ALIGN_OFF - -#ifdef _WIN32 - -#pragma warning(disable : 4018) // signed/unsigned mismatch -#pragma warning(disable : 4032) -#pragma warning(disable : 4051) -#pragma warning(disable : 4057) // slightly different base types -#pragma warning(disable : 4100) // unreferenced formal parameter -#pragma warning(disable : 4115) -#pragma warning(disable : 4125) // decimal digit terminates octal escape sequence -#pragma warning(disable : 4127) // conditional expression is constant -#pragma warning(disable : 4136) -#pragma warning(disable : 4201) -#pragma warning(disable : 4214) -#pragma warning(disable : 4244) -#pragma warning(disable : 4305) // truncation from const double to float -#pragma warning(disable : 4310) // cast truncates constant value -#pragma warning(disable : 4514) -#pragma warning(disable : 4711) // selected for automatic inline expansion -#pragma warning(disable : 4220) // varargs matches remaining parameters - -#endif - -#include -#include -#include -#include -#include -#include -#include -#include -#ifdef WIN32 // mac doesn't have malloc.h -#include // for _alloca() -#endif -#ifdef _WIN32 - -//#pragma intrinsic( memset, memcpy ) - -#endif - - -// this is the define for determining if we have an asm version of a C function -#if ( defined _M_IX86 || defined __i386__ ) && !defined __sun__ && !defined __LCC__ -#define id386 1 -#else -#define id386 0 -#endif - -// for windows fastcall option - -#define QDECL - -//======================= WIN32 DEFINES ================================= - -#ifdef WIN32 - -#define MAC_STATIC - -#undef QDECL -#define QDECL __cdecl - -// buildstring will be incorporated into the version string -#ifdef NDEBUG -#ifdef _M_IX86 -#define CPUSTRING "win-x86" -#elif defined _M_ALPHA -#define CPUSTRING "win-AXP" -#endif -#else -#ifdef _M_IX86 -#define CPUSTRING "win-x86-debug" -#elif defined _M_ALPHA -#define CPUSTRING "win-AXP-debug" -#endif -#endif - - -#define PATH_SEP '\\' - -#endif - -//======================= MAC OS X SERVER DEFINES ===================== - -#if defined( __MACH__ ) && defined( __APPLE__ ) - -#define MAC_STATIC - -#ifdef __ppc__ -#define CPUSTRING "MacOSXS-ppc" -#elif defined __i386__ -#define CPUSTRING "MacOSXS-i386" -#else -#define CPUSTRING "MacOSXS-other" -#endif - -#define PATH_SEP '/' - -#define GAME_HARD_LINKED -#define CGAME_HARD_LINKED -#define UI_HARD_LINKED -#define _alloca alloca - -#undef ALIGN_ON -#undef ALIGN_OFF -#define ALIGN_ON # pragma align( 16 ) -#define ALIGN_OFF # pragma align() - -#ifdef __cplusplus -extern "C" { -#endif - -void *osxAllocateMemory( long size ); -void osxFreeMemory( void *pointer ); - -#ifdef __cplusplus -} -#endif - -#endif - -//======================= MAC DEFINES ================================= - -#ifdef __MACOS__ - -#define MAC_STATIC static - -#define CPUSTRING "MacOS-PPC" - -#define PATH_SEP ':' - -void Sys_PumpEvents( void ); - -#endif - -#ifdef __MRC__ - -#define MAC_STATIC - -#define CPUSTRING "MacOS-PPC" - -#define PATH_SEP ':' - -void Sys_PumpEvents( void ); - -#undef QDECL -#define QDECL __cdecl - -#define _alloca alloca -#endif - -//======================= LINUX DEFINES ================================= - -// the mac compiler can't handle >32k of locals, so we -// just waste space and make big arrays static... -#ifdef __linux__ - -#define MAC_STATIC - -#ifdef __i386__ -#define CPUSTRING "linux-i386" -#elif defined __axp__ -#define CPUSTRING "linux-alpha" -#else -#define CPUSTRING "linux-other" -#endif - -#define PATH_SEP '/' - -#endif - -//============================================================= - -typedef enum {qfalse, qtrue} qboolean; - -typedef unsigned char byte; - -#define EQUAL_EPSILON 0.001 - -typedef int qhandle_t; -typedef int sfxHandle_t; -typedef int fileHandle_t; -typedef int clipHandle_t; - -typedef enum { - INVALID_JOINT = -1 -} jointHandle_t; - -#ifndef NULL -#define NULL ( (void *)0 ) -#endif - -#define MAX_QINT 0x7fffffff -#define MIN_QINT ( -MAX_QINT - 1 ) - -#ifndef max -#define max( x, y ) ( ( ( x ) > ( y ) ) ? ( x ) : ( y ) ) -#define min( x, y ) ( ( ( x ) < ( y ) ) ? ( x ) : ( y ) ) -#endif - -#ifndef sign -#define sign( f ) ( ( f > 0 ) ? 1 : ( ( f < 0 ) ? -1 : 0 ) ) -#endif - -// angle indexes -#define PITCH 0 // up / down -#define YAW 1 // left / right -#define ROLL 2 // fall over - -// the game guarantees that no string from the network will ever -// exceed MAX_STRING_CHARS -#define MAX_STRING_CHARS 1024 // max length of a string passed to Cmd_TokenizeString -#define MAX_STRING_TOKENS 256 // max tokens resulting from Cmd_TokenizeString -#define MAX_TOKEN_CHARS 1024 // max length of an individual token - -#define MAX_INFO_STRING 1024 -#define MAX_INFO_KEY 1024 -#define MAX_INFO_VALUE 1024 - - -#define MAX_QPATH 64 // max length of a quake game pathname -#define MAX_OSPATH 128 // max length of a filesystem pathname - -#define MAX_NAME_LENGTH 32 // max length of a client name - -// paramters for command buffer stuffing -typedef enum { - EXEC_NOW, // don't return until completed, a VM should NEVER use this, - // because some commands might cause the VM to be unloaded... - EXEC_INSERT, // insert at current position, but don't run yet - EXEC_APPEND // add to end of the command buffer (normal case) -} cbufExec_t; - - -// -// these aren't needed by any of the VMs. put in another header? -// -#define MAX_MAP_AREA_BYTES 32 // bit vector of area visibility - -#undef ERR_FATAL // malloc.h on unix - -// parameters to the main Error routine -typedef enum { - ERR_NONE, - ERR_FATAL, // exit the entire game with a popup window - ERR_DROP, // print to console and disconnect from game - ERR_DISCONNECT, // don't kill server - ERR_NEED_CD // pop up the need-cd dialog -} errorParm_t; - - -// font rendering values used by ui and cgame - -#define PROP_GAP_WIDTH 3 -#define PROP_SPACE_WIDTH 8 -#define PROP_HEIGHT 27 -#define PROP_SMALL_SIZE_SCALE 0.75 - -#define BLINK_DIVISOR 200 -#define PULSE_DIVISOR 75 - -#define UI_LEFT 0x00000000 // default -#define UI_CENTER 0x00000001 -#define UI_RIGHT 0x00000002 -#define UI_FORMATMASK 0x00000007 -#define UI_SMALLFONT 0x00000010 -#define UI_BIGFONT 0x00000020 // default -#define UI_GIANTFONT 0x00000040 -#define UI_DROPSHADOW 0x00000800 -#define UI_BLINK 0x00001000 -#define UI_INVERSE 0x00002000 -#define UI_PULSE 0x00004000 - - -/* - ============================================================== - - MATHLIB - - ============================================================== - */ -#ifdef __cplusplus // so we can include this in C code -#define SIDE_FRONT 0 -#define SIDE_BACK 1 -#define SIDE_ON 2 -#define SIDE_CROSS 3 - -#define Q_PI 3.14159265358979323846 -#ifndef M_PI -#define M_PI 3.14159265358979323846 // matches value in gcc v2 math.h -#endif - -#include "math_vector.h" -#include "math_angles.h" -#include "math_matrix.h" -#include "math_quaternion.h" - -class idVec3; // for defining vectors -typedef idVec3 &vec3_p; // for passing vectors as function arguments -typedef const idVec3 &vec3_c; // for passing vectors as const function arguments - -class angles_t; // for defining angle vectors -typedef angles_t &angles_p; // for passing angles as function arguments -typedef const angles_t &angles_c; // for passing angles as const function arguments - -class mat3_t; // for defining matrices -typedef mat3_t &mat3_p; // for passing matrices as function arguments -typedef const mat3_t &mat3_c; // for passing matrices as const function arguments - - - -#define NUMVERTEXNORMALS 162 -extern idVec3 bytedirs[NUMVERTEXNORMALS]; - -// all drawing is done to a 640*480 virtual screen size -// and will be automatically scaled to the real resolution -#define SCREEN_WIDTH 640 -#define SCREEN_HEIGHT 480 - -#define TINYCHAR_WIDTH ( SMALLCHAR_WIDTH ) -#define TINYCHAR_HEIGHT ( SMALLCHAR_HEIGHT / 2 ) - -#define SMALLCHAR_WIDTH 8 -#define SMALLCHAR_HEIGHT 16 - -#define BIGCHAR_WIDTH 16 -#define BIGCHAR_HEIGHT 16 - -#define GIANTCHAR_WIDTH 32 -#define GIANTCHAR_HEIGHT 48 - -extern idVec4 colorBlack; -extern idVec4 colorRed; -extern idVec4 colorGreen; -extern idVec4 colorBlue; -extern idVec4 colorYellow; -extern idVec4 colorMagenta; -extern idVec4 colorCyan; -extern idVec4 colorWhite; -extern idVec4 colorLtGrey; -extern idVec4 colorMdGrey; -extern idVec4 colorDkGrey; - -#define Q_COLOR_ESCAPE '^' -#define Q_IsColorString( p ) ( p && *( p ) == Q_COLOR_ESCAPE && *( ( p ) + 1 ) && *( ( p ) + 1 ) != Q_COLOR_ESCAPE ) - -#define COLOR_BLACK '0' -#define COLOR_RED '1' -#define COLOR_GREEN '2' -#define COLOR_YELLOW '3' -#define COLOR_BLUE '4' -#define COLOR_CYAN '5' -#define COLOR_MAGENTA '6' -#define COLOR_WHITE '7' -#define ColorIndex( c ) ( ( ( c ) - '0' ) & 7 ) - -#define S_COLOR_BLACK "^0" -#define S_COLOR_RED "^1" -#define S_COLOR_GREEN "^2" -#define S_COLOR_YELLOW "^3" -#define S_COLOR_BLUE "^4" -#define S_COLOR_CYAN "^5" -#define S_COLOR_MAGENTA "^6" -#define S_COLOR_WHITE "^7" - -extern idVec4 g_color_table[8]; - -#define MAKERGB( v, r, g, b ) v[0] = r; v[1] = g; v[2] = b -#define MAKERGBA( v, r, g, b, a ) v[0] = r; v[1] = g; v[2] = b; v[3] = a - -#define DEG2RAD( a ) ( ( ( a ) * M_PI ) / 180.0F ) -#define RAD2DEG( a ) ( ( ( a ) * 180.0f ) / M_PI ) - -struct cplane_s; - -extern idVec3 vec3_origin; -extern idVec4 vec4_origin; -extern mat3_t axisDefault; - -#define nanmask ( 255 << 23 ) - -#define IS_NAN( x ) ( ( ( *(int *)&x ) & nanmask ) == nanmask ) - -float Q_fabs( float f ); -float Q_rsqrt( float f ); // reciprocal square root - -#define SQRTFAST( x ) ( 1.0f / Q_rsqrt( x ) ) - -signed char ClampChar( int i ); -signed short ClampShort( int i ); - -// this isn't a real cheap function to call! -int DirToByte( const idVec3 &dir ); -void ByteToDir( int b, vec3_p dir ); - -#define DotProduct( a,b ) ( ( a )[0] * ( b )[0] + ( a )[1] * ( b )[1] + ( a )[2] * ( b )[2] ) -#define VectorSubtract( a,b,c ) ( ( c )[0] = ( a )[0] - ( b )[0],( c )[1] = ( a )[1] - ( b )[1],( c )[2] = ( a )[2] - ( b )[2] ) -#define VectorAdd( a,b,c ) ( ( c )[0] = ( a )[0] + ( b )[0],( c )[1] = ( a )[1] + ( b )[1],( c )[2] = ( a )[2] + ( b )[2] ) -#define VectorCopy( a,b ) ( ( b )[0] = ( a )[0],( b )[1] = ( a )[1],( b )[2] = ( a )[2] ) -//#define VectorCopy(a,b) ((b).x=(a).x,(b).y=(a).y,(b).z=(a).z]) - -#define VectorScale( v, s, o ) ( ( o )[0] = ( v )[0] * ( s ),( o )[1] = ( v )[1] * ( s ),( o )[2] = ( v )[2] * ( s ) ) -#define VectorMA( v, s, b, o ) ( ( o )[0] = ( v )[0] + ( b )[0] * ( s ),( o )[1] = ( v )[1] + ( b )[1] * ( s ),( o )[2] = ( v )[2] + ( b )[2] * ( s ) ) -#define CrossProduct( a,b,c ) ( ( c )[0] = ( a )[1] * ( b )[2] - ( a )[2] * ( b )[1],( c )[1] = ( a )[2] * ( b )[0] - ( a )[0] * ( b )[2],( c )[2] = ( a )[0] * ( b )[1] - ( a )[1] * ( b )[0] ) - -#define DotProduct4( x,y ) ( ( x )[0] * ( y )[0] + ( x )[1] * ( y )[1] + ( x )[2] * ( y )[2] + ( x )[3] * ( y )[3] ) -#define VectorSubtract4( a,b,c ) ( ( c )[0] = ( a )[0] - ( b )[0],( c )[1] = ( a )[1] - ( b )[1],( c )[2] = ( a )[2] - ( b )[2],( c )[3] = ( a )[3] - ( b )[3] ) -#define VectorAdd4( a,b,c ) ( ( c )[0] = ( a )[0] + ( b )[0],( c )[1] = ( a )[1] + ( b )[1],( c )[2] = ( a )[2] + ( b )[2],( c )[3] = ( a )[3] + ( b )[3] ) -#define VectorCopy4( a,b ) ( ( b )[0] = ( a )[0],( b )[1] = ( a )[1],( b )[2] = ( a )[2],( b )[3] = ( a )[3] ) -#define VectorScale4( v, s, o ) ( ( o )[0] = ( v )[0] * ( s ),( o )[1] = ( v )[1] * ( s ),( o )[2] = ( v )[2] * ( s ),( o )[3] = ( v )[3] * ( s ) ) -#define VectorMA4( v, s, b, o ) ( ( o )[0] = ( v )[0] + ( b )[0] * ( s ),( o )[1] = ( v )[1] + ( b )[1] * ( s ),( o )[2] = ( v )[2] + ( b )[2] * ( s ),( o )[3] = ( v )[3] + ( b )[3] * ( s ) ) - - -#define VectorClear( a ) ( ( a )[0] = ( a )[1] = ( a )[2] = 0 ) -#define VectorNegate( a,b ) ( ( b )[0] = -( a )[0],( b )[1] = -( a )[1],( b )[2] = -( a )[2] ) -#define VectorSet( v, x, y, z ) ( ( v )[0] = ( x ), ( v )[1] = ( y ), ( v )[2] = ( z ) ) -#define Vector4Copy( a,b ) ( ( b )[0] = ( a )[0],( b )[1] = ( a )[1],( b )[2] = ( a )[2],( b )[3] = ( a )[3] ) - -#define SnapVector( v ) {v[0] = (int)v[0]; v[1] = (int)v[1]; v[2] = (int)v[2]; } - -float NormalizeColor( vec3_c in, vec3_p out ); - -int VectorCompare( vec3_c v1, vec3_c v2 ); -float VectorLength( vec3_c v ); -float Distance( vec3_c p1, vec3_c p2 ); -float DistanceSquared( vec3_c p1, vec3_c p2 ); -float VectorNormalize( vec3_p v ); // returns vector length -void VectorNormalizeFast( vec3_p v ); // does NOT return vector length, uses rsqrt approximation -float VectorNormalize2( vec3_c v, vec3_p out ); -void VectorInverse( vec3_p v ); -void VectorRotate( vec3_c in, mat3_c matrix, vec3_p out ); -void VectorPolar( vec3_p v, float radius, float theta, float phi ); -void VectorSnap( vec3_p v ); -void Vector53Copy( const idVec5_t &in, vec3_p out ); -void Vector5Scale( const idVec5_t &v, float scale, idVec5_t &out ); -void Vector5Add( const idVec5_t &va, const idVec5_t &vb, idVec5_t &out ); -void VectorRotate3( vec3_c vIn, vec3_c vRotation, vec3_p out ); -void VectorRotate3Origin( vec3_c vIn, vec3_c vRotation, vec3_c vOrigin, vec3_p out ); - - -int Q_log2( int val ); - -int Q_rand( int *seed ); -float Q_random( int *seed ); -float Q_crandom( int *seed ); - -#define random() ( ( rand() & 0x7fff ) / ( (float)0x7fff ) ) -#define crandom() ( 2.0 * ( random() - 0.5 ) ) - -float Q_rint( float in ); - -void vectoangles( vec3_c value1, angles_p angles ); -void AnglesToAxis( angles_c angles, mat3_p axis ); - -void AxisCopy( mat3_c in, mat3_p out ); -qboolean AxisRotated( mat3_c in ); // assumes a non-degenerate axis - -int SignbitsForNormal( vec3_c normal ); -int BoxOnPlaneSide( const Bounds &b, struct cplane_s *p ); - -float AngleMod( float a ); -float LerpAngle( float from, float to, float frac ); -float AngleSubtract( float a1, float a2 ); -void AnglesSubtract( angles_c v1, angles_c v2, angles_p v3 ); - -float AngleNormalize360( float angle ); -float AngleNormalize180( float angle ); -float AngleDelta( float angle1, float angle2 ); - -qboolean PlaneFromPoints( idVec4 &plane, vec3_c a, vec3_c b, vec3_c c ); -void ProjectPointOnPlane( vec3_p dst, vec3_c p, vec3_c normal ); -void RotatePointAroundVector( vec3_p dst, vec3_c dir, vec3_c point, float degrees ); -void RotateAroundDirection( mat3_p axis, float yaw ); -void MakeNormalVectors( vec3_c forward, vec3_p right, vec3_p up ); -// perpendicular vector could be replaced by this - -int PlaneTypeForNormal( vec3_c normal ); - -void MatrixMultiply( mat3_c in1, mat3_c in2, mat3_p out ); -void MatrixInverseMultiply( mat3_c in1, mat3_c in2, mat3_p out ); // in2 is transposed during multiply -void MatrixTransformVector( vec3_c in, mat3_c matrix, vec3_p out ); -void MatrixProjectVector( vec3_c in, mat3_c matrix, vec3_p out ); // Places the vector into a new coordinate system. -void AngleVectors( angles_c angles, vec3_p forward, vec3_p right, vec3_p up ); -void PerpendicularVector( vec3_p dst, vec3_c src ); - -float TriangleArea( vec3_c a, vec3_c b, vec3_c c ); -#endif // __cplusplus - -//============================================= - -float Com_Clamp( float min, float max, float value ); - -#define FILE_HASH_SIZE 1024 -int Com_HashString( const char *fname ); - -char *Com_SkipPath( char *pathname ); - -// it is ok for out == in -void Com_StripExtension( const char *in, char *out ); - -// "extension" should include the dot: ".map" -void Com_DefaultExtension( char *path, int maxSize, const char *extension ); - -int Com_ParseInfos( const char *buf, int max, char infos[][MAX_INFO_STRING] ); - -/* - ===================================================================================== - - SCRIPT PARSING - - ===================================================================================== - */ - -// this just controls the comment printing, it doesn't actually load a file -void Com_BeginParseSession( const char *filename ); -void Com_EndParseSession( void ); - -int Com_GetCurrentParseLine( void ); - -// Will never return NULL, just empty strings. -// An empty string will only be returned at end of file. -// ParseOnLine will return empty if there isn't another token on this line - -// this funny typedef just means a moving pointer into a const char * buffer -const char *Com_Parse( const char *( *data_p ) ); -const char *Com_ParseOnLine( const char *( *data_p ) ); -const char *Com_ParseRestOfLine( const char *( *data_p ) ); - -void Com_UngetToken( void ); - -#ifdef __cplusplus -void Com_MatchToken( const char *( *buf_p ), const char *match, qboolean warning = qfalse ); -#else -void Com_MatchToken( const char *( *buf_p ), const char *match, qboolean warning ); -#endif - -void Com_ScriptError( const char *msg, ... ); -void Com_ScriptWarning( const char *msg, ... ); - -void Com_SkipBracedSection( const char *( *program ) ); -void Com_SkipRestOfLine( const char *( *data ) ); - -float Com_ParseFloat( const char *( *buf_p ) ); -int Com_ParseInt( const char *( *buf_p ) ); - -void Com_Parse1DMatrix( const char *( *buf_p ), int x, float *m ); -void Com_Parse2DMatrix( const char *( *buf_p ), int y, int x, float *m ); -void Com_Parse3DMatrix( const char *( *buf_p ), int z, int y, int x, float *m ); - -//===================================================================================== -#ifdef __cplusplus -extern "C" { -#endif - -void QDECL Com_sprintf( char *dest, int size, const char *fmt, ... ); - - -// mode parm for FS_FOpenFile -typedef enum { - FS_READ, - FS_WRITE, - FS_APPEND, - FS_APPEND_SYNC -} fsMode_t; - -typedef enum { - FS_SEEK_CUR, - FS_SEEK_END, - FS_SEEK_SET -} fsOrigin_t; - -//============================================= - -int Q_isprint( int c ); -int Q_islower( int c ); -int Q_isupper( int c ); -int Q_isalpha( int c ); - -// portable case insensitive compare -int Q_stricmp( const char *s1, const char *s2 ); -int Q_strncmp( const char *s1, const char *s2, int n ); -int Q_stricmpn( const char *s1, const char *s2, int n ); -char *Q_strlwr( char *s1 ); -char *Q_strupr( char *s1 ); -char *Q_strrchr( const char* string, int c ); - -// buffer size safe library replacements -void Q_strncpyz( char *dest, const char *src, int destsize ); -void Q_strcat( char *dest, int size, const char *src ); - -// strlen that discounts Quake color sequences -int Q_PrintStrlen( const char *string ); -// removes color sequences from string -char *Q_CleanStr( char *string ); - -int Com_Filter( const char *filter, const char *name, int casesensitive ); -const char *Com_StringContains( const char *str1, const char *str2, int casesensitive ); - - -//============================================= - -short BigShort( short l ); -short LittleShort( short l ); -int BigLong( int l ); -int LittleLong( int l ); -float BigFloat( float l ); -float LittleFloat( float l ); - -void Swap_Init( void ); -char * QDECL va( char *format, ... ); - -#ifdef __cplusplus -} -#endif - - -//============================================= -#ifdef __cplusplus -// -// mapfile parsing -// -typedef struct ePair_s { - char *key; - char *value; -} ePair_t; - -typedef struct mapSide_s { - char material[MAX_QPATH]; - idVec4 plane; - idVec4 textureVectors[2]; -} mapSide_t; - -typedef struct { - int numSides; - mapSide_t **sides; -} mapBrush_t; - -typedef struct { - idVec3 xyz; - float st[2]; -} patchVertex_t; - -typedef struct { - char material[MAX_QPATH]; - int width, height; - patchVertex_t *patchVerts; -} mapPatch_t; - -typedef struct { - char modelName[MAX_QPATH]; - float matrix[16]; -} mapModel_t; - -typedef struct mapPrimitive_s { - int numEpairs; - ePair_t **ePairs; - - // only one of these will be non-NULL - mapBrush_t *brush; - mapPatch_t *patch; - mapModel_t *model; -} mapPrimitive_t; - -typedef struct mapEntity_s { - int numPrimitives; - mapPrimitive_t **primitives; - - int numEpairs; - ePair_t **ePairs; -} mapEntity_t; - -typedef struct { - int numEntities; - mapEntity_t **entities; -} mapFile_t; - - -// the order of entities, brushes, and sides will be maintained, the -// lists won't be swapped on each load or save -mapFile_t *ParseMapFile( const char *text ); -void FreeMapFile( mapFile_t *mapFile ); -void WriteMapFile( const mapFile_t *mapFile, FILE *f ); - -// key names are case-insensitive -const char *ValueForMapEntityKey( const mapEntity_t *ent, const char *key ); -float FloatForMapEntityKey( const mapEntity_t *ent, const char *key ); -qboolean GetVectorForMapEntityKey( const mapEntity_t *ent, const char *key, idVec3 &vec ); - -typedef struct { - idVec3 xyz; - idVec2 st; - idVec3 normal; - idVec3 tangents[2]; - byte smoothing[4]; // colors for silhouette smoothing -} drawVert_t; - -typedef struct { - int width, height; - drawVert_t *verts; -} drawVertMesh_t; - -// Tesselate a map patch into smoothed, drawable vertexes -// MaxError of around 4 is reasonable -drawVertMesh_t *SubdivideMapPatch( const mapPatch_t *patch, float maxError ); -#endif // __cplusplus - -//========================================= - -#ifdef __cplusplus -extern "C" { -#endif - -void QDECL Com_Error( int level, const char *error, ... ); -void QDECL Com_Printf( const char *msg, ... ); -void QDECL Com_DPrintf( const char *msg, ... ); - -#ifdef __cplusplus -} -#endif - - -typedef struct { - qboolean frameMemory; - int currentElements; - int maxElements; // will reallocate and move when exceeded - void **elements; -} growList_t; - -// you don't need to init the growlist if you don't mind it growing and moving -// the list as it expands -void Com_InitGrowList( growList_t *list, int maxElements ); -int Com_AddToGrowList( growList_t *list, void *data ); -void *Com_GrowListElement( const growList_t *list, int index ); -int Com_IndexForGrowListElement( const growList_t *list, const void *element ); - - -// -// key / value info strings -// -char *Info_ValueForKey( const char *s, const char *key ); -void Info_RemoveKey( char *s, const char *key ); -void Info_SetValueForKey( char *s, const char *key, const char *value ); -qboolean Info_Validate( const char *s ); -void Info_NextPair( const char *( *s ), char key[MAX_INFO_KEY], char value[MAX_INFO_VALUE] ); - -// get cvar defs, collision defs, etc -//#include "../shared/interface.h" - -// get key code numbers for events -//#include "../shared/keycodes.h" - -#ifdef __cplusplus -// get the polygon winding functions -//#include "../shared/windings.h" - -// get the flags class -//#include "../shared/idflags.h" -#endif // __cplusplus - -#endif // __Q_SHARED_H diff --git a/tools/urt/libs/splines/splines.cpp b/tools/urt/libs/splines/splines.cpp deleted file mode 100644 index 1fb51d8..0000000 --- a/tools/urt/libs/splines/splines.cpp +++ /dev/null @@ -1,1451 +0,0 @@ -/* - Copyright (C) 1999-2007 id Software, Inc. and contributors. - For a list of contributors, see the accompanying CONTRIBUTORS file. - - This file is part of GtkRadiant. - - GtkRadiant is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - GtkRadiant is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with GtkRadiant; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - */ - -#include "q_shared.h" -#include "splines.h" - -extern "C" { -int FS_Write( const void *buffer, int len, fileHandle_t h ); -int FS_ReadFile( const char *qpath, void **buffer ); -void FS_FreeFile( void *buffer ); -fileHandle_t FS_FOpenFileWrite( const char *filename ); -void FS_FCloseFile( fileHandle_t f ); -void Cbuf_AddText( const char *text ); -void Cbuf_Execute( void ); -} - -float Q_fabs( float f ) { - int tmp = *( int * ) &f; - tmp &= 0x7FFFFFFF; - return *( float * ) &tmp; -} - -// (SA) making a list of cameras so I can use -// the splines as targets for other things. -// Certainly better ways to do this, but this lets -// me get underway quickly with ents that need spline -// targets. -#define MAX_CAMERAS 64 - -idCameraDef camera[MAX_CAMERAS]; - -extern "C" { -qboolean loadCamera( int camNum, const char *name ) { - if ( camNum < 0 || camNum >= MAX_CAMERAS ) { - return qfalse; - } - camera[camNum].clear(); - return (qboolean)camera[camNum].load( name ); -} - -qboolean getCameraInfo( int camNum, int time, float *origin, float *angles, float *fov ) { - idVec3 dir, org; - if ( camNum < 0 || camNum >= MAX_CAMERAS ) { - return qfalse; - } - org[0] = origin[0]; - org[1] = origin[1]; - org[2] = origin[2]; - if ( camera[camNum].getCameraInfo( time, org, dir, fov ) ) { - origin[0] = org[0]; - origin[1] = org[1]; - origin[2] = org[2]; - angles[1] = atan2( dir[1], dir[0] ) * 180 / 3.14159; - angles[0] = asin( dir[2] ) * 180 / 3.14159; - return qtrue; - } - return qfalse; -} - -void startCamera( int camNum, int time ) { - if ( camNum < 0 || camNum >= MAX_CAMERAS ) { - return; - } - camera[camNum].startCamera( time ); -} - -} - - -//#include "../shared/windings.h" -//#include "../qcommon/qcommon.h" -//#include "../sys/sys_public.h" -//#include "../game/game_entity.h" - -idCameraDef splineList; -idCameraDef *g_splineList = &splineList; - -idVec3 idSplineList::zero( 0,0,0 ); - -void glLabeledPoint( idVec3 &color, idVec3 &point, float size, const char *label ) { - glColor3fv( color ); - glPointSize( size ); - glBegin( GL_POINTS ); - glVertex3fv( point ); - glEnd(); - idVec3 v = point; - v.x += 1; - v.y += 1; - v.z += 1; - glRasterPos3fv( v ); - glCallLists( strlen( label ), GL_UNSIGNED_BYTE, label ); -} - - -void glBox( idVec3 &color, idVec3 &point, float size ) { - idVec3 mins( point ); - idVec3 maxs( point ); - mins[0] -= size; - mins[1] += size; - mins[2] -= size; - maxs[0] += size; - maxs[1] -= size; - maxs[2] += size; - glColor3fv( color ); - glBegin( GL_LINE_LOOP ); - glVertex3f( mins[0],mins[1],mins[2] ); - glVertex3f( maxs[0],mins[1],mins[2] ); - glVertex3f( maxs[0],maxs[1],mins[2] ); - glVertex3f( mins[0],maxs[1],mins[2] ); - glEnd(); - glBegin( GL_LINE_LOOP ); - glVertex3f( mins[0],mins[1],maxs[2] ); - glVertex3f( maxs[0],mins[1],maxs[2] ); - glVertex3f( maxs[0],maxs[1],maxs[2] ); - glVertex3f( mins[0],maxs[1],maxs[2] ); - glEnd(); - - glBegin( GL_LINES ); - glVertex3f( mins[0],mins[1],mins[2] ); - glVertex3f( mins[0],mins[1],maxs[2] ); - glVertex3f( mins[0],maxs[1],maxs[2] ); - glVertex3f( mins[0],maxs[1],mins[2] ); - glVertex3f( maxs[0],mins[1],mins[2] ); - glVertex3f( maxs[0],mins[1],maxs[2] ); - glVertex3f( maxs[0],maxs[1],maxs[2] ); - glVertex3f( maxs[0],maxs[1],mins[2] ); - glEnd(); - -} - -void splineTest() { - //g_splineList->load("p:/doom/base/maps/test_base1.camera"); -} - -void splineDraw() { - //g_splineList->addToRenderer(); -} - - -//extern void D_DebugLine( const idVec3 &color, const idVec3 &start, const idVec3 &end ); - -void debugLine( idVec3 &color, float x, float y, float z, float x2, float y2, float z2 ) { - idVec3 from( x, y, z ); - idVec3 to( x2, y2, z2 ); - //D_DebugLine(color, from, to); -} - -void idSplineList::addToRenderer() { - - if ( controlPoints.Num() == 0 ) { - return; - } - - idVec3 mins, maxs; - idVec3 yellow( 1.0, 1.0, 0 ); - idVec3 white( 1.0, 1.0, 1.0 ); - int i; - - for ( i = 0; i < controlPoints.Num(); i++ ) { - VectorCopy( *controlPoints[i], mins ); - VectorCopy( mins, maxs ); - mins[0] -= 8; - mins[1] += 8; - mins[2] -= 8; - maxs[0] += 8; - maxs[1] -= 8; - maxs[2] += 8; - debugLine( yellow, mins[0], mins[1], mins[2], maxs[0], mins[1], mins[2] ); - debugLine( yellow, maxs[0], mins[1], mins[2], maxs[0], maxs[1], mins[2] ); - debugLine( yellow, maxs[0], maxs[1], mins[2], mins[0], maxs[1], mins[2] ); - debugLine( yellow, mins[0], maxs[1], mins[2], mins[0], mins[1], mins[2] ); - - debugLine( yellow, mins[0], mins[1], maxs[2], maxs[0], mins[1], maxs[2] ); - debugLine( yellow, maxs[0], mins[1], maxs[2], maxs[0], maxs[1], maxs[2] ); - debugLine( yellow, maxs[0], maxs[1], maxs[2], mins[0], maxs[1], maxs[2] ); - debugLine( yellow, mins[0], maxs[1], maxs[2], mins[0], mins[1], maxs[2] ); - - } - - int step = 0; - idVec3 step1; - for ( i = 3; i < controlPoints.Num(); i++ ) { - for ( float tension = 0.0f; tension < 1.001f; tension += 0.1f ) { - float x = 0; - float y = 0; - float z = 0; - for ( int j = 0; j < 4; j++ ) { - x += controlPoints[i - ( 3 - j )]->x * calcSpline( j, tension ); - y += controlPoints[i - ( 3 - j )]->y * calcSpline( j, tension ); - z += controlPoints[i - ( 3 - j )]->z * calcSpline( j, tension ); - } - if ( step == 0 ) { - step1[0] = x; - step1[1] = y; - step1[2] = z; - step = 1; - } - else { - debugLine( white, step1[0], step1[1], step1[2], x, y, z ); - step = 0; - } - - } - } -} - -void idSplineList::buildSpline() { - //int start = Sys_Milliseconds(); - clearSpline(); - for ( int i = 3; i < controlPoints.Num(); i++ ) { - for ( float tension = 0.0f; tension < 1.001f; tension += granularity ) { - float x = 0; - float y = 0; - float z = 0; - for ( int j = 0; j < 4; j++ ) { - x += controlPoints[i - ( 3 - j )]->x * calcSpline( j, tension ); - y += controlPoints[i - ( 3 - j )]->y * calcSpline( j, tension ); - z += controlPoints[i - ( 3 - j )]->z * calcSpline( j, tension ); - } - splinePoints.Append( new idVec3( x, y, z ) ); - } - } - dirty = false; - //Com_Printf("Spline build took %f seconds\n", (float)(Sys_Milliseconds() - start) / 1000); -} - - -void idSplineList::draw( bool editMode ) { - int i; - idVec4 yellow( 1, 1, 0, 1 ); - - if ( controlPoints.Num() == 0 ) { - return; - } - - if ( dirty ) { - buildSpline(); - } - - - glColor3fv( controlColor ); - glPointSize( 5 ); - - glBegin( GL_POINTS ); - for ( i = 0; i < controlPoints.Num(); i++ ) { - glVertex3fv( *controlPoints[i] ); - } - glEnd(); - - if ( editMode ) { - for ( i = 0; i < controlPoints.Num(); i++ ) { - glBox( activeColor, *controlPoints[i], 4 ); - } - } - - //Draw the curve - glColor3fv( pathColor ); - glBegin( GL_LINE_STRIP ); - int count = splinePoints.Num(); - for ( i = 0; i < count; i++ ) { - glVertex3fv( *splinePoints[i] ); - } - glEnd(); - - if ( editMode ) { - glColor3fv( segmentColor ); - glPointSize( 3 ); - glBegin( GL_POINTS ); - for ( i = 0; i < count; i++ ) { - glVertex3fv( *splinePoints[i] ); - } - glEnd(); - } - if ( count > 0 ) { - //assert(activeSegment >=0 && activeSegment < count); - if ( activeSegment >= 0 && activeSegment < count ) { - glBox( activeColor, *splinePoints[activeSegment], 6 ); - glBox( yellow, *splinePoints[activeSegment], 8 ); - } - } - -} - -float idSplineList::totalDistance() { - - // FIXME: save dist and return - // - if ( controlPoints.Num() == 0 ) { - return 0.0; - } - - if ( dirty ) { - buildSpline(); - } - - float dist = 0.0; - idVec3 temp; - int count = splinePoints.Num(); - for ( int i = 1; i < count; i++ ) { - temp = *splinePoints[i - 1]; - temp -= *splinePoints[i]; - dist += temp.Length(); - } - return dist; -} - -void idSplineList::initPosition( long bt, long totalTime ) { - - if ( dirty ) { - buildSpline(); - } - - if ( splinePoints.Num() == 0 ) { - return; - } - - baseTime = bt; - time = totalTime; - - // calc distance to travel ( this will soon be broken into time segments ) - splineTime.Clear(); - splineTime.Append( bt ); - double dist = totalDistance(); - double distSoFar = 0.0; - idVec3 temp; - int count = splinePoints.Num(); - //for(int i = 2; i < count - 1; i++) { - for ( int i = 1; i < count; i++ ) { - temp = *splinePoints[i - 1]; - temp -= *splinePoints[i]; - distSoFar += temp.Length(); - double percent = distSoFar / dist; - percent *= totalTime; - splineTime.Append( percent + bt ); - } - assert( splineTime.Num() == splinePoints.Num() ); - activeSegment = 0; -} - - - -float idSplineList::calcSpline( int step, float tension ) { - switch ( step ) { - case 0: return ( pow( 1 - tension, 3 ) ) / 6; - case 1: return ( 3 * pow( tension, 3 ) - 6 * pow( tension, 2 ) + 4 ) / 6; - case 2: return ( -3 * pow( tension, 3 ) + 3 * pow( tension, 2 ) + 3 * tension + 1 ) / 6; - case 3: return pow( tension, 3 ) / 6; - } - return 0.0; -} - - - -void idSplineList::updateSelection( const idVec3 &move ) { - if ( selected ) { - dirty = true; - VectorAdd( *selected, move, *selected ); - } -} - - -void idSplineList::setSelectedPoint( idVec3 *p ) { - if ( p ) { - p->Snap(); - for ( int i = 0; i < controlPoints.Num(); i++ ) { - if ( *p == *controlPoints[i] ) { - selected = controlPoints[i]; - } - } - } - else { - selected = NULL; - } -} - -const idVec3 *idSplineList::getPosition( long t ) { - static idVec3 interpolatedPos; - static long lastTime = -1; - - int count = splineTime.Num(); - if ( count == 0 ) { - return &zero; - } - -// Com_Printf("Time: %d\n", t); - assert( splineTime.Num() == splinePoints.Num() ); - - while ( activeSegment < count ) { - if ( splineTime[activeSegment] >= t ) { - if ( activeSegment > 0 && activeSegment < count - 1 ) { - double timeHi = splineTime[activeSegment + 1]; - double timeLo = splineTime[activeSegment - 1]; - double percent = ( timeHi - t ) / ( timeHi - timeLo ); - // pick two bounding points - idVec3 v1 = *splinePoints[activeSegment - 1]; - idVec3 v2 = *splinePoints[activeSegment + 1]; - v2 *= ( 1.0 - percent ); - v1 *= percent; - v2 += v1; - interpolatedPos = v2; - return &interpolatedPos; - } - return splinePoints[activeSegment]; - } - else { - activeSegment++; - } - } - return splinePoints[count - 1]; -} - -void idSplineList::parse( const char *( *text ) ) { - const char *token; - //Com_MatchToken( text, "{" ); - do { - token = Com_Parse( text ); - - if ( !token[0] ) { - break; - } - if ( !Q_stricmp( token, "}" ) ) { - break; - } - - do { - // if token is not a brace, it is a key for a key/value pair - if ( !token[0] || !Q_stricmp( token, "(" ) || !Q_stricmp( token, "}" ) ) { - break; - } - - Com_UngetToken(); - idStr key = Com_ParseOnLine( text ); - const char *token = Com_Parse( text ); - if ( Q_stricmp( key.c_str(), "granularity" ) == 0 ) { - granularity = atof( token ); - } - else if ( Q_stricmp( key.c_str(), "name" ) == 0 ) { - name = token; - } - token = Com_Parse( text ); - - } while ( 1 ); - - if ( !Q_stricmp( token, "}" ) ) { - break; - } - - Com_UngetToken(); - // read the control point - idVec3 point; - Com_Parse1DMatrix( text, 3, point ); - addPoint( point.x, point.y, point.z ); - } while ( 1 ); - - //Com_UngetToken(); - //Com_MatchToken( text, "}" ); - dirty = true; -} - -void idSplineList::write( fileHandle_t file, const char *p ) { - idStr s = va( "\t\t%s {\n", p ); - FS_Write( s.c_str(), s.length(), file ); - //s = va("\t\tname %s\n", name.c_str()); - //FS_Write(s.c_str(), s.length(), file); - s = va( "\t\t\tgranularity %f\n", granularity ); - FS_Write( s.c_str(), s.length(), file ); - int count = controlPoints.Num(); - for ( int i = 0; i < count; i++ ) { - s = va( "\t\t\t( %f %f %f )\n", controlPoints[i]->x, controlPoints[i]->y, controlPoints[i]->z ); - FS_Write( s.c_str(), s.length(), file ); - } - s = "\t\t}\n"; - FS_Write( s.c_str(), s.length(), file ); -} - - -void idCameraDef::getActiveSegmentInfo( int segment, idVec3 &origin, idVec3 &direction, float *fov ) { -#if 0 - if ( !cameraSpline.validTime() ) { - buildCamera(); - } - double d = (double)segment / numSegments(); - getCameraInfo( d * totalTime * 1000, origin, direction, fov ); -#endif -/* - if (!cameraSpline.validTime()) { - buildCamera(); - } - origin = *cameraSpline.getSegmentPoint(segment); - - - idVec3 temp; - - int numTargets = getTargetSpline()->controlPoints.Num(); - int count = cameraSpline.splineTime.Num(); - if (numTargets == 0) { - // follow the path - if (cameraSpline.getActiveSegment() < count - 1) { - temp = *cameraSpline.splinePoints[cameraSpline.getActiveSegment()+1]; - } - } else if (numTargets == 1) { - temp = *getTargetSpline()->controlPoints[0]; - } else { - temp = *getTargetSpline()->getSegmentPoint(segment); - } - - temp -= origin; - temp.Normalize(); - direction = temp; - */ -} - -bool idCameraDef::getCameraInfo( long time, idVec3 &origin, idVec3 &direction, float *fv ) { - - char buff[1024]; - - if ( ( time - startTime ) / 1000 > totalTime ) { - return false; - } - - - for ( int i = 0; i < events.Num(); i++ ) { - if ( time >= startTime + events[i]->getTime() && !events[i]->getTriggered() ) { - events[i]->setTriggered( true ); - if ( events[i]->getType() == idCameraEvent::EVENT_TARGET ) { - setActiveTargetByName( events[i]->getParam() ); - getActiveTarget()->start( startTime + events[i]->getTime() ); - //Com_Printf("Triggered event switch to target: %s\n",events[i]->getParam()); - } - else if ( events[i]->getType() == idCameraEvent::EVENT_TRIGGER ) { - //idEntity *ent = NULL; - //ent = level.FindTarget( ent, events[i]->getParam()); - //if (ent) { - // ent->signal( SIG_TRIGGER ); - // ent->ProcessEvent( &EV_Activate, world ); - //} - } - else if ( events[i]->getType() == idCameraEvent::EVENT_FOV ) { - memset( buff, 0, sizeof( buff ) ); - strcpy( buff, events[i]->getParam() ); - const char *param1 = strtok( buff, " \t,\0" ); - const char *param2 = strtok( NULL, " \t,\0" ); - float len = ( param2 ) ? atof( param2 ) : 0; - float newfov = ( param1 ) ? atof( param1 ) : 90; - fov.reset( fov.getFOV( time ), newfov, time, len ); - //*fv = fov = atof(events[i]->getParam()); - } - else if ( events[i]->getType() == idCameraEvent::EVENT_FADEIN ) { - float time = atof( events[i]->getParam() ); - Cbuf_AddText( va( "fade 0 0 0 0 %f", time ) ); - Cbuf_Execute(); - } - else if ( events[i]->getType() == idCameraEvent::EVENT_FADEOUT ) { - float time = atof( events[i]->getParam() ); - Cbuf_AddText( va( "fade 0 0 0 255 %f", time ) ); - Cbuf_Execute(); - } - else if ( events[i]->getType() == idCameraEvent::EVENT_CAMERA ) { - memset( buff, 0, sizeof( buff ) ); - strcpy( buff, events[i]->getParam() ); - const char *param1 = strtok( buff, " \t,\0" ); - const char *param2 = strtok( NULL, " \t,\0" ); - - if ( param2 ) { - loadCamera( atoi( param1 ), va( "cameras/%s.camera", param2 ) ); - startCamera( time ); - } - else { - loadCamera( 0, va( "cameras/%s.camera", events[i]->getParam() ) ); - startCamera( time ); - } - return true; - } - else if ( events[i]->getType() == idCameraEvent::EVENT_STOP ) { - return false; - } - } - } - - origin = *cameraPosition->getPosition( time ); - - *fv = fov.getFOV( time ); - - idVec3 temp = origin; - - int numTargets = targetPositions.Num(); - if ( numTargets == 0 ) { -/* - // follow the path - if (cameraSpline.getActiveSegment() < count - 1) { - temp = *cameraSpline.splinePoints[cameraSpline.getActiveSegment()+1]; - if (temp == origin) { - int index = cameraSpline.getActiveSegment() + 2; - while (temp == origin && index < count - 1) { - temp = *cameraSpline.splinePoints[index++]; - } - } - } - */ - } - else { - if ( getActiveTarget()->numPoints() > 0 ) { - temp = *getActiveTarget()->getPosition( time ); - } - } - - temp -= origin; - temp.Normalize(); - direction = temp; - - return true; -} - -bool idCameraDef::waitEvent( int index ) { - //for (int i = 0; i < events.Num(); i++) { - // if (events[i]->getSegment() == index && events[i]->getType() == idCameraEvent::EVENT_WAIT) { - // return true; - // } - //} - return false; -} - - -#define NUM_CCELERATION_SEGS 10 -#define CELL_AMT 5 - -void idCameraDef::buildCamera() { - int i; - int lastSwitch = 0; - idList waits; - idList targets; - - totalTime = baseTime; - cameraPosition->setTime( (long)totalTime * 1000 ); - // we have a base time layout for the path and the target path - // now we need to layer on any wait or speed changes - for ( i = 0; i < events.Num(); i++ ) { - idCameraEvent *ev = events[i]; - events[i]->setTriggered( false ); - switch ( events[i]->getType() ) { - case idCameraEvent::EVENT_TARGET: { - targets.Append( i ); - break; - } - case idCameraEvent::EVENT_FEATHER: { - long startTime = 0; - float speed = 0; - long loopTime = 10; - float stepGoal = cameraPosition->getBaseVelocity() / ( 1000 / loopTime ); - while ( startTime <= 1000 ) { - cameraPosition->addVelocity( startTime, loopTime, speed ); - speed += stepGoal; - if ( speed > cameraPosition->getBaseVelocity() ) { - speed = cameraPosition->getBaseVelocity(); - } - startTime += loopTime; - } - - startTime = (long)( totalTime * 1000 - 1000 ); - long endTime = startTime + 1000; - speed = cameraPosition->getBaseVelocity(); - while ( startTime < endTime ) { - speed -= stepGoal; - if ( speed < 0 ) { - speed = 0; - } - cameraPosition->addVelocity( startTime, loopTime, speed ); - startTime += loopTime; - } - break; - - } - case idCameraEvent::EVENT_WAIT: { - waits.Append( atof( events[i]->getParam() ) ); - - //FIXME: this is quite hacky for Wolf E3, accel and decel needs - // do be parameter based etc.. - long startTime = events[i]->getTime() - 1000; - if ( startTime < 0 ) { - startTime = 0; - } - float speed = cameraPosition->getBaseVelocity(); - long loopTime = 10; - float steps = speed / ( ( events[i]->getTime() - startTime ) / loopTime ); - while ( startTime <= events[i]->getTime() - loopTime ) { - cameraPosition->addVelocity( startTime, loopTime, speed ); - speed -= steps; - startTime += loopTime; - } - cameraPosition->addVelocity( events[i]->getTime(), (long)atof( events[i]->getParam() ) * 1000, 0 ); - - startTime = (long)( events[i]->getTime() + atof( events[i]->getParam() ) * 1000 ); - long endTime = startTime + 1000; - speed = 0; - while ( startTime <= endTime ) { - cameraPosition->addVelocity( startTime, loopTime, speed ); - speed += steps; - startTime += loopTime; - } - break; - } - case idCameraEvent::EVENT_TARGETWAIT: { - //targetWaits.Append(i); - break; - } - case idCameraEvent::EVENT_SPEED: { -/* - // take the average delay between up to the next five segments - float adjust = atof(events[i]->getParam()); - int index = events[i]->getSegment(); - total = 0; - count = 0; - - // get total amount of time over the remainder of the segment - for (j = index; j < cameraSpline.numSegments() - 1; j++) { - total += cameraSpline.getSegmentTime(j + 1) - cameraSpline.getSegmentTime(j); - count++; - } - - // multiply that by the adjustment - double newTotal = total * adjust; - // what is the difference.. - newTotal -= total; - totalTime += newTotal / 1000; - - // per segment difference - newTotal /= count; - int additive = newTotal; - - // now propogate that difference out to each segment - for (j = index; j < cameraSpline.numSegments(); j++) { - cameraSpline.addSegmentTime(j, additive); - additive += newTotal; - } - break; - */ - } - } - } - - - for ( i = 0; i < waits.Num(); i++ ) { - totalTime += waits[i]; - } - - // on a new target switch, we need to take time to this point ( since last target switch ) - // and allocate it across the active target, then reset time to this point - long timeSoFar = 0; - long total = (long)( totalTime * 1000 ); - for ( i = 0; i < targets.Num(); i++ ) { - long t; - if ( i < targets.Num() - 1 ) { - t = events[targets[i + 1]]->getTime(); - } - else { - t = total - timeSoFar; - } - // t is how much time to use for this target - setActiveTargetByName( events[targets[i]]->getParam() ); - getActiveTarget()->setTime( t ); - timeSoFar += t; - } - - -} - -void idCameraDef::startCamera( long t ) { - cameraPosition->clearVelocities(); - cameraPosition->start( t ); - buildCamera(); - fov.reset( 90, 90, t, 0 ); - //for (int i = 0; i < targetPositions.Num(); i++) { - // targetPositions[i]-> - //} - startTime = t; - cameraRunning = true; -} - - -void idCameraDef::parse( const char *( *text ) ) { - - const char *token; - do { - token = Com_Parse( text ); - - if ( !token[0] ) { - break; - } - if ( !Q_stricmp( token, "}" ) ) { - break; - } - - if ( Q_stricmp( token, "time" ) == 0 ) { - baseTime = Com_ParseFloat( text ); - } - else if ( Q_stricmp( token, "camera_fixed" ) == 0 ) { - cameraPosition = new idFixedPosition(); - cameraPosition->parse( text ); - } - else if ( Q_stricmp( token, "camera_interpolated" ) == 0 ) { - cameraPosition = new idInterpolatedPosition(); - cameraPosition->parse( text ); - } - else if ( Q_stricmp( token, "camera_spline" ) == 0 ) { - cameraPosition = new idSplinePosition(); - cameraPosition->parse( text ); - } - else if ( Q_stricmp( token, "target_fixed" ) == 0 ) { - idFixedPosition *pos = new idFixedPosition(); - pos->parse( text ); - targetPositions.Append( pos ); - } - else if ( Q_stricmp( token, "target_interpolated" ) == 0 ) { - idInterpolatedPosition *pos = new idInterpolatedPosition(); - pos->parse( text ); - targetPositions.Append( pos ); - } - else if ( Q_stricmp( token, "target_spline" ) == 0 ) { - idSplinePosition *pos = new idSplinePosition(); - pos->parse( text ); - targetPositions.Append( pos ); - } - else if ( Q_stricmp( token, "fov" ) == 0 ) { - fov.parse( text ); - } - else if ( Q_stricmp( token, "event" ) == 0 ) { - idCameraEvent *event = new idCameraEvent(); - event->parse( text ); - addEvent( event ); - } - - - } while ( 1 ); - - if ( !cameraPosition ) { - Com_Printf( "no camera position specified\n" ); - // prevent a crash later on - cameraPosition = new idFixedPosition(); - } - - Com_UngetToken(); - Com_MatchToken( text, "}" ); - -} - -bool idCameraDef::load( const char *filename ) { - char *buf; - const char *buf_p; - int length = FS_ReadFile( filename, (void **)&buf ); - if ( !buf ) { - return false; - } - - clear(); - Com_BeginParseSession( filename ); - buf_p = buf; - parse( &buf_p ); - Com_EndParseSession(); - FS_FreeFile( buf ); - - return true; -} - -void idCameraDef::save( const char *filename ) { - fileHandle_t file = FS_FOpenFileWrite( filename ); - if ( file ) { - int i; - idStr s = "cameraPathDef { \n"; - FS_Write( s.c_str(), s.length(), file ); - s = va( "\ttime %f\n", baseTime ); - FS_Write( s.c_str(), s.length(), file ); - - cameraPosition->write( file, va( "camera_%s",cameraPosition->typeStr() ) ); - - for ( i = 0; i < numTargets(); i++ ) { - targetPositions[i]->write( file, va( "target_%s", targetPositions[i]->typeStr() ) ); - } - - for ( i = 0; i < events.Num(); i++ ) { - events[i]->write( file, "event" ); - } - - fov.write( file, "fov" ); - - s = "}\n"; - FS_Write( s.c_str(), s.length(), file ); - } - FS_FCloseFile( file ); -} - -int idCameraDef::sortEvents( const void *p1, const void *p2 ) { - idCameraEvent *ev1 = (idCameraEvent*)( p1 ); - idCameraEvent *ev2 = (idCameraEvent*)( p2 ); - - if ( ev1->getTime() > ev2->getTime() ) { - return -1; - } - if ( ev1->getTime() < ev2->getTime() ) { - return 1; - } - return 0; -} - -void idCameraDef::addEvent( idCameraEvent *event ) { - events.Append( event ); - //events.Sort(&sortEvents); - -} -void idCameraDef::addEvent( idCameraEvent::eventType t, const char *param, long time ) { - addEvent( new idCameraEvent( t, param, time ) ); - buildCamera(); -} - -void idCameraDef::removeEvent( int index ) { - events.RemoveIndex( index ); - buildCamera(); -} - - -const char *idCameraEvent::eventStr[] = { - "NA", - "WAIT", - "TARGETWAIT", - "SPEED", - "TARGET", - "SNAPTARGET", - "FOV", - "CMD", - "TRIGGER", - "STOP", - "CAMERA", - "FADEOUT", - "FADEIN", - "FEATHER" -}; - -void idCameraEvent::parse( const char *( *text ) ) { - const char *token; - Com_MatchToken( text, "{" ); - do { - token = Com_Parse( text ); - - if ( !token[0] ) { - break; - } - if ( !strcmp( token, "}" ) ) { - break; - } - - // here we may have to jump over brush epairs ( only used in editor ) - do { - // if token is not a brace, it is a key for a key/value pair - if ( !token[0] || !strcmp( token, "(" ) || !strcmp( token, "}" ) ) { - break; - } - - Com_UngetToken(); - idStr key = Com_ParseOnLine( text ); - const char *token = Com_Parse( text ); - if ( Q_stricmp( key.c_str(), "type" ) == 0 ) { - type = static_cast( atoi( token ) ); - } - else if ( Q_stricmp( key.c_str(), "param" ) == 0 ) { - paramStr = token; - } - else if ( Q_stricmp( key.c_str(), "time" ) == 0 ) { - time = atoi( token ); - } - token = Com_Parse( text ); - - } while ( 1 ); - - if ( !strcmp( token, "}" ) ) { - break; - } - - } while ( 1 ); - - Com_UngetToken(); - Com_MatchToken( text, "}" ); -} - -void idCameraEvent::write( fileHandle_t file, const char *name ) { - idStr s = va( "\t%s {\n", name ); - FS_Write( s.c_str(), s.length(), file ); - s = va( "\t\ttype %d\n", static_cast( type ) ); - FS_Write( s.c_str(), s.length(), file ); - s = va( "\t\tparam \"%s\"\n", paramStr.c_str() ); - FS_Write( s.c_str(), s.length(), file ); - s = va( "\t\ttime %d\n", time ); - FS_Write( s.c_str(), s.length(), file ); - s = "\t}\n"; - FS_Write( s.c_str(), s.length(), file ); -} - - -const char *idCameraPosition::positionStr[] = { - "Fixed", - "Interpolated", - "Spline", -}; - - - -const idVec3 *idInterpolatedPosition::getPosition( long t ) { - static idVec3 interpolatedPos; - - float velocity = getVelocity( t ); - float timePassed = t - lastTime; - lastTime = t; - - // convert to seconds - timePassed /= 1000; - - float distToTravel = timePassed * velocity; - - idVec3 temp = startPos; - temp -= endPos; - float distance = temp.Length(); - - distSoFar += distToTravel; - float percent = (float)( distSoFar ) / distance; - - if ( percent > 1.0 ) { - percent = 1.0; - } - else if ( percent < 0.0 ) { - percent = 0.0; - } - - // the following line does a straigt calc on percentage of time - // float percent = (float)(startTime + time - t) / time; - - idVec3 v1 = startPos; - idVec3 v2 = endPos; - v1 *= ( 1.0 - percent ); - v2 *= percent; - v1 += v2; - interpolatedPos = v1; - return &interpolatedPos; -} - - -void idCameraFOV::parse( const char *( *text ) ) { - const char *token; - Com_MatchToken( text, "{" ); - do { - token = Com_Parse( text ); - - if ( !token[0] ) { - break; - } - if ( !strcmp( token, "}" ) ) { - break; - } - - // here we may have to jump over brush epairs ( only used in editor ) - do { - // if token is not a brace, it is a key for a key/value pair - if ( !token[0] || !strcmp( token, "(" ) || !strcmp( token, "}" ) ) { - break; - } - - Com_UngetToken(); - idStr key = Com_ParseOnLine( text ); - const char *token = Com_Parse( text ); - if ( Q_stricmp( key.c_str(), "fov" ) == 0 ) { - fov = atof( token ); - } - else if ( Q_stricmp( key.c_str(), "startFOV" ) == 0 ) { - startFOV = atof( token ); - } - else if ( Q_stricmp( key.c_str(), "endFOV" ) == 0 ) { - endFOV = atof( token ); - } - else if ( Q_stricmp( key.c_str(), "time" ) == 0 ) { - time = atoi( token ); - } - token = Com_Parse( text ); - - } while ( 1 ); - - if ( !strcmp( token, "}" ) ) { - break; - } - - } while ( 1 ); - - Com_UngetToken(); - Com_MatchToken( text, "}" ); -} - -bool idCameraPosition::parseToken( const char *key, const char *( *text ) ) { - const char *token = Com_Parse( text ); - if ( Q_stricmp( key, "time" ) == 0 ) { - time = atol( token ); - return true; - } - else if ( Q_stricmp( key, "type" ) == 0 ) { - type = static_cast( atoi( token ) ); - return true; - } - else if ( Q_stricmp( key, "velocity" ) == 0 ) { - long t = atol( token ); - token = Com_Parse( text ); - long d = atol( token ); - token = Com_Parse( text ); - float s = atof( token ); - addVelocity( t, d, s ); - return true; - } - else if ( Q_stricmp( key, "baseVelocity" ) == 0 ) { - baseVelocity = atof( token ); - return true; - } - else if ( Q_stricmp( key, "name" ) == 0 ) { - name = token; - return true; - } - else if ( Q_stricmp( key, "time" ) == 0 ) { - time = atoi( token ); - return true; - } - Com_UngetToken(); - return false; -} - - - -void idFixedPosition::parse( const char *( *text ) ) { - const char *token; - Com_MatchToken( text, "{" ); - do { - token = Com_Parse( text ); - - if ( !token[0] ) { - break; - } - if ( !strcmp( token, "}" ) ) { - break; - } - - // here we may have to jump over brush epairs ( only used in editor ) - do { - // if token is not a brace, it is a key for a key/value pair - if ( !token[0] || !strcmp( token, "(" ) || !strcmp( token, "}" ) ) { - break; - } - - Com_UngetToken(); - idStr key = Com_ParseOnLine( text ); - - const char *token = Com_Parse( text ); - if ( Q_stricmp( key.c_str(), "pos" ) == 0 ) { - Com_UngetToken(); - Com_Parse1DMatrix( text, 3, pos ); - } - else { - Com_UngetToken(); - idCameraPosition::parseToken( key.c_str(), text ); - } - token = Com_Parse( text ); - - } while ( 1 ); - - if ( !strcmp( token, "}" ) ) { - break; - } - - } while ( 1 ); - - Com_UngetToken(); - Com_MatchToken( text, "}" ); -} - -void idInterpolatedPosition::parse( const char *( *text ) ) { - const char *token; - Com_MatchToken( text, "{" ); - do { - token = Com_Parse( text ); - - if ( !token[0] ) { - break; - } - if ( !strcmp( token, "}" ) ) { - break; - } - - // here we may have to jump over brush epairs ( only used in editor ) - do { - // if token is not a brace, it is a key for a key/value pair - if ( !token[0] || !strcmp( token, "(" ) || !strcmp( token, "}" ) ) { - break; - } - - Com_UngetToken(); - idStr key = Com_ParseOnLine( text ); - - const char *token = Com_Parse( text ); - if ( Q_stricmp( key.c_str(), "startPos" ) == 0 ) { - Com_UngetToken(); - Com_Parse1DMatrix( text, 3, startPos ); - } - else if ( Q_stricmp( key.c_str(), "endPos" ) == 0 ) { - Com_UngetToken(); - Com_Parse1DMatrix( text, 3, endPos ); - } - else { - Com_UngetToken(); - idCameraPosition::parseToken( key.c_str(), text ); - } - token = Com_Parse( text ); - - } while ( 1 ); - - if ( !strcmp( token, "}" ) ) { - break; - } - - } while ( 1 ); - - Com_UngetToken(); - Com_MatchToken( text, "}" ); -} - - -void idSplinePosition::parse( const char *( *text ) ) { - const char *token; - Com_MatchToken( text, "{" ); - do { - token = Com_Parse( text ); - - if ( !token[0] ) { - break; - } - if ( !strcmp( token, "}" ) ) { - break; - } - - // here we may have to jump over brush epairs ( only used in editor ) - do { - // if token is not a brace, it is a key for a key/value pair - if ( !token[0] || !strcmp( token, "(" ) || !strcmp( token, "}" ) ) { - break; - } - - Com_UngetToken(); - idStr key = Com_ParseOnLine( text ); - - const char *token = Com_Parse( text ); - if ( Q_stricmp( key.c_str(), "target" ) == 0 ) { - target.parse( text ); - } - else { - Com_UngetToken(); - idCameraPosition::parseToken( key.c_str(), text ); - } - token = Com_Parse( text ); - - } while ( 1 ); - - if ( !strcmp( token, "}" ) ) { - break; - } - - } while ( 1 ); - - Com_UngetToken(); - Com_MatchToken( text, "}" ); -} - - - -void idCameraFOV::write( fileHandle_t file, const char *p ) { - idStr s = va( "\t%s {\n", p ); - FS_Write( s.c_str(), s.length(), file ); - - s = va( "\t\tfov %f\n", fov ); - FS_Write( s.c_str(), s.length(), file ); - - s = va( "\t\tstartFOV %f\n", startFOV ); - FS_Write( s.c_str(), s.length(), file ); - - s = va( "\t\tendFOV %f\n", endFOV ); - FS_Write( s.c_str(), s.length(), file ); - - s = va( "\t\ttime %i\n", time ); - FS_Write( s.c_str(), s.length(), file ); - - s = "\t}\n"; - FS_Write( s.c_str(), s.length(), file ); -} - - -void idCameraPosition::write( fileHandle_t file, const char *p ) { - - idStr s = va( "\t\ttime %i\n", time ); - FS_Write( s.c_str(), s.length(), file ); - - s = va( "\t\ttype %i\n", static_cast( type ) ); - FS_Write( s.c_str(), s.length(), file ); - - s = va( "\t\tname %s\n", name.c_str() ); - FS_Write( s.c_str(), s.length(), file ); - - s = va( "\t\tbaseVelocity %f\n", baseVelocity ); - FS_Write( s.c_str(), s.length(), file ); - - for ( int i = 0; i < velocities.Num(); i++ ) { - s = va( "\t\tvelocity %i %i %f\n", velocities[i]->startTime, velocities[i]->time, velocities[i]->speed ); - FS_Write( s.c_str(), s.length(), file ); - } - -} - -void idFixedPosition::write( fileHandle_t file, const char *p ) { - idStr s = va( "\t%s {\n", p ); - FS_Write( s.c_str(), s.length(), file ); - idCameraPosition::write( file, p ); - s = va( "\t\tpos ( %f %f %f )\n", pos.x, pos.y, pos.z ); - FS_Write( s.c_str(), s.length(), file ); - s = "\t}\n"; - FS_Write( s.c_str(), s.length(), file ); -} - -void idInterpolatedPosition::write( fileHandle_t file, const char *p ) { - idStr s = va( "\t%s {\n", p ); - FS_Write( s.c_str(), s.length(), file ); - idCameraPosition::write( file, p ); - s = va( "\t\tstartPos ( %f %f %f )\n", startPos.x, startPos.y, startPos.z ); - FS_Write( s.c_str(), s.length(), file ); - s = va( "\t\tendPos ( %f %f %f )\n", endPos.x, endPos.y, endPos.z ); - FS_Write( s.c_str(), s.length(), file ); - s = "\t}\n"; - FS_Write( s.c_str(), s.length(), file ); -} - -void idSplinePosition::write( fileHandle_t file, const char *p ) { - idStr s = va( "\t%s {\n", p ); - FS_Write( s.c_str(), s.length(), file ); - idCameraPosition::write( file, p ); - target.write( file, "target" ); - s = "\t}\n"; - FS_Write( s.c_str(), s.length(), file ); -} - -void idCameraDef::addTarget( const char *name, idCameraPosition::positionType type ) { - const char *text = ( name == NULL ) ? va( "target0%d", numTargets() + 1 ) : name; - idCameraPosition *pos = newFromType( type ); - if ( pos ) { - pos->setName( name ); - targetPositions.Append( pos ); - activeTarget = numTargets() - 1; - if ( activeTarget == 0 ) { - // first one - addEvent( idCameraEvent::EVENT_TARGET, name, 0 ); - } - } -} - -const idVec3 *idSplinePosition::getPosition( long t ) { - static idVec3 interpolatedPos; - - float velocity = getVelocity( t ); - float timePassed = t - lastTime; - lastTime = t; - - // convert to seconds - timePassed /= 1000; - - float distToTravel = timePassed * velocity; - - distSoFar += distToTravel; - double tempDistance = target.totalDistance(); - - double percent = (double)( distSoFar ) / tempDistance; - - double targetDistance = percent * tempDistance; - tempDistance = 0; - - double lastDistance1,lastDistance2; - lastDistance1 = lastDistance2 = 0; - idVec3 temp; - int count = target.numSegments(); - int i; - for ( i = 1; i < count; i++ ) { - temp = *target.getSegmentPoint( i - 1 ); - temp -= *target.getSegmentPoint( i ); - tempDistance += temp.Length(); - if ( i & 1 ) { - lastDistance1 = tempDistance; - } - else { - lastDistance2 = tempDistance; - } - if ( tempDistance >= targetDistance ) { - break; - } - } - - if ( i >= count - 1 ) { - interpolatedPos = *target.getSegmentPoint( i - 1 ); - } - else { -#if 0 - double timeHi = target.getSegmentTime( i + 1 ); - double timeLo = target.getSegmentTime( i - 1 ); - double percent = ( timeHi - t ) / ( timeHi - timeLo ); - idVec3 v1 = *target.getSegmentPoint( i - 1 ); - idVec3 v2 = *target.getSegmentPoint( i + 1 ); - v2 *= ( 1.0 - percent ); - v1 *= percent; - v2 += v1; - interpolatedPos = v2; -#else - if ( lastDistance1 > lastDistance2 ) { - double d = lastDistance2; - lastDistance2 = lastDistance1; - lastDistance1 = d; - } - - idVec3 v1 = *target.getSegmentPoint( i - 1 ); - idVec3 v2 = *target.getSegmentPoint( i ); - double percent = ( lastDistance2 - targetDistance ) / ( lastDistance2 - lastDistance1 ); - v2 *= ( 1.0 - percent ); - v1 *= percent; - v2 += v1; - interpolatedPos = v2; -#endif - } - return &interpolatedPos; - -} diff --git a/tools/urt/libs/splines/splines.h b/tools/urt/libs/splines/splines.h deleted file mode 100644 index 18b535b..0000000 --- a/tools/urt/libs/splines/splines.h +++ /dev/null @@ -1,1108 +0,0 @@ -#ifndef __SPLINES_H -#define __SPLINES_H - -#define GTKRADIANT - -#ifdef GTKRADIANT -#include "igl.h" -#endif - -#include "util_list.h" -#include "util_str.h" -#include "math_vector.h" - -typedef int fileHandle_t; - -extern void glBox( idVec3 &color, idVec3 &point, float size ); -extern void glLabeledPoint( idVec3 &color, idVec3 &point, float size, const char *label ); - -static idVec4 blue( 0, 0, 1, 1 ); -static idVec4 red( 1, 0, 0, 1 ); - -class idPointListInterface { -public: -idPointListInterface() { - selectedPoints.Clear(); -}; -virtual ~idPointListInterface() {}; - -virtual int numPoints() { - return 0; -} - -virtual void addPoint( const float x, const float y, const float z ) {} -virtual void addPoint( const idVec3 &v ) {} -virtual void removePoint( int index ) {} -virtual idVec3 *getPoint( int index ) { return NULL; } - -int selectPointByRay( float ox, float oy, float oz, float dx, float dy, float dz, bool single ) { - idVec3 origin( ox, oy, oz ); - idVec3 dir( dx, dy, dz ); - return selectPointByRay( origin, dir, single ); -} - -int selectPointByRay( const idVec3 origin, const idVec3 direction, bool single ) { - int i, besti, count; - float d, bestd; - idVec3 temp, temp2; - - // find the point closest to the ray - besti = -1; - bestd = 8; - count = numPoints(); - - for ( i = 0; i < count; i++ ) { - temp = *getPoint( i ); - temp2 = temp; - temp -= origin; - d = DotProduct( temp, direction ); - __VectorMA( origin, d, direction, temp ); - temp2 -= temp; - d = temp2.Length(); - if ( d <= bestd ) { - bestd = d; - besti = i; - } - } - - if ( besti >= 0 ) { - selectPoint( besti, single ); - } - - return besti; -} - -int isPointSelected( int index ) { - int count = selectedPoints.Num(); - for ( int i = 0; i < count; i++ ) { - if ( selectedPoints[i] == index ) { - return i; - } - } - return -1; -} - -int selectPoint( int index, bool single ) { - if ( index >= 0 && index < numPoints() ) { - if ( single ) { - deselectAll(); - } - else { - if ( isPointSelected( index ) >= 0 ) { - selectedPoints.Remove( index ); - } - } - return selectedPoints.Append( index ); - } - return -1; -} - -void selectAll() { - selectedPoints.Clear(); - for ( int i = 0; i < numPoints(); i++ ) { - selectedPoints.Append( i ); - } -} - -void deselectAll() { - selectedPoints.Clear(); -} - -int numSelectedPoints(); - -idVec3 *getSelectedPoint( int index ) { - assert( index >= 0 && index < numSelectedPoints() ); - return getPoint( selectedPoints[index] ); -} - -virtual void updateSelection( float x, float y, float z ) { - idVec3 move( x, y, z ); - updateSelection( move ); -} - -virtual void updateSelection( const idVec3 &move ) { - int count = selectedPoints.Num(); - for ( int i = 0; i < count; i++ ) { - *getPoint( selectedPoints[i] ) += move; - } -} - -void drawSelection() { - int count = selectedPoints.Num(); - for ( int i = 0; i < count; i++ ) { - glBox( red, *getPoint( selectedPoints[i] ), 4 ); - } -} - -protected: -idList selectedPoints; - -}; - - -class idSplineList { - -public: - -idSplineList() { - clear(); -} - -idSplineList( const char *p ) { - clear(); - name = p; -}; - -~idSplineList() { - clear(); -}; - -void clearControl() { - for ( int i = 0; i < controlPoints.Num(); i++ ) { - delete controlPoints[i]; - } - controlPoints.Clear(); -} - -void clearSpline() { - for ( int i = 0; i < splinePoints.Num(); i++ ) { - delete splinePoints[i]; - } - splinePoints.Clear(); -} - -void parse( const char *( *text ) ); -void write( fileHandle_t file, const char *name ); - -void clear() { - clearControl(); - clearSpline(); - splineTime.Clear(); - selected = NULL; - dirty = true; - activeSegment = 0; - granularity = 0.025f; - pathColor.set( 1.0f, 0.5f, 0.0f ); - controlColor.set( 0.7f, 0.0f, 1.0f ); - segmentColor.set( 0.0f, 0.0f, 1.0f ); - activeColor.set( 1.0f, 0.0f, 0.0f ); -} - -void initPosition( long startTime, long totalTime ); -const idVec3 *getPosition( long time ); - - -void draw( bool editMode ); -void addToRenderer(); - -void setSelectedPoint( idVec3 *p ); -idVec3 *getSelectedPoint() { - return selected; -} - -void addPoint( const idVec3 &v ) { - controlPoints.Append( new idVec3( v ) ); - dirty = true; -} - -void addPoint( float x, float y, float z ) { - controlPoints.Append( new idVec3( x, y, z ) ); - dirty = true; -} - -void updateSelection( const idVec3 &move ); - -void startEdit() { - editMode = true; -} - -void stopEdit() { - editMode = false; -} - -void buildSpline(); - -void setGranularity( float f ) { - granularity = f; -} - -float getGranularity() { - return granularity; -} - -int numPoints() { - return controlPoints.Num(); -} - -idVec3 *getPoint( int index ) { - assert( index >= 0 && index < controlPoints.Num() ); - return controlPoints[index]; -} - -idVec3 *getSegmentPoint( int index ) { - assert( index >= 0 && index < splinePoints.Num() ); - return splinePoints[index]; -} - - -void setSegmentTime( int index, int time ) { - assert( index >= 0 && index < splinePoints.Num() ); - splineTime[index] = time; -} - -int getSegmentTime( int index ) { - assert( index >= 0 && index < splinePoints.Num() ); - return (int)splineTime[index]; -} -void addSegmentTime( int index, int time ) { - assert( index >= 0 && index < splinePoints.Num() ); - splineTime[index] += time; -} - -float totalDistance(); - -static idVec3 zero; - -int getActiveSegment() { - return activeSegment; -} - -void setActiveSegment( int i ) { - //assert(i >= 0 && (splinePoints.Num() > 0 && i < splinePoints.Num())); - activeSegment = i; -} - -int numSegments() { - return splinePoints.Num(); -} - -void setColors( idVec3 &path, idVec3 &segment, idVec3 &control, idVec3 &active ) { - pathColor = path; - segmentColor = segment; - controlColor = control; - activeColor = active; -} - -const char *getName() { - return name.c_str(); -} - -void setName( const char *p ) { - name = p; -} - -bool validTime() { - if ( dirty ) { - buildSpline(); - } - // gcc doesn't allow static casting away from bools - // why? I've no idea... - return (bool)( splineTime.Num() > 0 && splineTime.Num() == splinePoints.Num() ); -} - -void setTime( long t ) { - time = t; -} - -void setBaseTime( long t ) { - baseTime = t; -} - -protected: -idStr name; -float calcSpline( int step, float tension ); -idList controlPoints; -idList splinePoints; -idList splineTime; -idVec3 *selected; -idVec3 pathColor, segmentColor, controlColor, activeColor; -float granularity; -bool editMode; -bool dirty; -int activeSegment; -long baseTime; -long time; -friend class idCamera; -}; - -// time in milliseconds -// velocity where 1.0 equal rough walking speed -struct idVelocity { - idVelocity( long start, long duration, float s ) { - startTime = start; - time = duration; - speed = s; - } - long startTime; - long time; - float speed; -}; - -// can either be a look at or origin position for a camera -// -class idCameraPosition : public idPointListInterface { -public: - -virtual void clearVelocities() { - for ( int i = 0; i < velocities.Num(); i++ ) { - delete velocities[i]; - velocities[i] = NULL; - } - velocities.Clear(); -} - -virtual void clear() { - editMode = false; - clearVelocities(); -} - -idCameraPosition( const char *p ) { - name = p; -} - -idCameraPosition() { - time = 0; - name = "position"; -} - -idCameraPosition( long t ) { - time = t; -} - -virtual ~idCameraPosition() { - clear(); -} - - -// this can be done with RTTI syntax but i like the derived classes setting a type -// makes serialization a bit easier to see -// -enum positionType { - FIXED = 0x00, - INTERPOLATED, - SPLINE, - POSITION_COUNT -}; - - -virtual void start( long t ) { - startTime = t; -} - -long getTime() { - return time; -} - -virtual void setTime( long t ) { - time = t; -} - -float getBaseVelocity() { - return baseVelocity; -} - -float getVelocity( long t ) { - long check = t - startTime; - for ( int i = 0; i < velocities.Num(); i++ ) { - if ( check >= velocities[i]->startTime && check <= velocities[i]->startTime + velocities[i]->time ) { - return velocities[i]->speed; - } - } - return baseVelocity; -} - -void addVelocity( long start, long duration, float speed ) { - velocities.Append( new idVelocity( start, duration, speed ) ); -} - -virtual const idVec3 *getPosition( long t ) { - assert( true ); - return NULL; -} - -virtual void draw( bool editMode ) {}; - -virtual void parse( const char *( *text ) ) {}; -virtual void write( fileHandle_t file, const char *name ); -virtual bool parseToken( const char *key, const char *( *text ) ); - -const char *getName() { - return name.c_str(); -} - -void setName( const char *p ) { - name = p; -} - -virtual void startEdit() { - editMode = true; -} - -virtual void stopEdit() { - editMode = false; -} - -virtual void draw() {}; - -const char *typeStr() { - return positionStr[static_cast( type )]; -} - -void calcVelocity( float distance ) { - float secs = (float)time / 1000; - baseVelocity = distance / secs; -} - -protected: -static const char* positionStr[POSITION_COUNT]; -long startTime; -long time; -idCameraPosition::positionType type; -idStr name; -bool editMode; -idList velocities; -float baseVelocity; -}; - -class idFixedPosition : public idCameraPosition { -public: - -void init() { - pos.Zero(); - type = idCameraPosition::FIXED; -} - -idFixedPosition() : idCameraPosition() { - init(); -} - -idFixedPosition( idVec3 p ) : idCameraPosition() { - init(); - pos = p; -} - -virtual void addPoint( const idVec3 &v ) { - pos = v; -} - -virtual void addPoint( const float x, const float y, const float z ) { - pos.set( x, y, z ); -} - - -~idFixedPosition() { -} - -virtual const idVec3 *getPosition( long t ) { - return &pos; -} - -void parse( const char *( *text ) ); -void write( fileHandle_t file, const char *name ); - -virtual int numPoints() { - return 1; -} - -virtual idVec3 *getPoint( int index ) { - if ( index != 0 ) { - assert( true ); - } - ; - return &pos; -} - -virtual void draw( bool editMode ) { - glLabeledPoint( blue, pos, ( editMode ) ? 5 : 3, "Fixed point" ); -} - -protected: -idVec3 pos; -}; - -class idInterpolatedPosition : public idCameraPosition { -public: - -void init() { - type = idCameraPosition::INTERPOLATED; - first = true; - startPos.Zero(); - endPos.Zero(); -} - -idInterpolatedPosition() : idCameraPosition() { - init(); -} - -idInterpolatedPosition( idVec3 start, idVec3 end, long time ) : idCameraPosition( time ) { - init(); - startPos = start; - endPos = end; -} - -~idInterpolatedPosition() { -} - -virtual const idVec3 *getPosition( long t ); - -void parse( const char *( *text ) ); -void write( fileHandle_t file, const char *name ); - -virtual int numPoints() { - return 2; -} - -virtual idVec3 *getPoint( int index ) { - assert( index >= 0 && index < 2 ); - if ( index == 0 ) { - return &startPos; - } - return &endPos; -} - -virtual void addPoint( const float x, const float y, const float z ) { - if ( first ) { - startPos.set( x, y, z ); - first = false; - } - else { - endPos.set( x, y, z ); - first = true; - } -} - -virtual void addPoint( const idVec3 &v ) { - if ( first ) { - startPos = v; - first = false; - } - else { - endPos = v; - first = true; - } -} - -virtual void draw( bool editMode ) { - glLabeledPoint( blue, startPos, ( editMode ) ? 5 : 3, "Start interpolated" ); - glLabeledPoint( blue, endPos, ( editMode ) ? 5 : 3, "End interpolated" ); - glBegin( GL_LINES ); - glVertex3fv( startPos ); - glVertex3fv( endPos ); - glEnd(); -} - -virtual void start( long t ) { - idCameraPosition::start( t ); - lastTime = startTime; - distSoFar = 0.0; - idVec3 temp = startPos; - temp -= endPos; - calcVelocity( temp.Length() ); -} - -protected: -bool first; -idVec3 startPos; -idVec3 endPos; -long lastTime; -float distSoFar; -}; - -class idSplinePosition : public idCameraPosition { -public: - -void init() { - type = idCameraPosition::SPLINE; -} - -idSplinePosition() : idCameraPosition() { - init(); -} - -idSplinePosition( long time ) : idCameraPosition( time ) { - init(); -} - -~idSplinePosition() { -} - -virtual void start( long t ) { - idCameraPosition::start( t ); - target.initPosition( t, time ); - lastTime = startTime; - distSoFar = 0.0; - calcVelocity( target.totalDistance() ); -} - -//virtual const idVec3 *getPosition(long t) { -// return target.getPosition(t); -//} -virtual const idVec3 *getPosition( long t ); - - -//virtual const idVec3 *getPosition(long t) const { - -void addControlPoint( idVec3 &v ) { - target.addPoint( v ); -} - -void parse( const char *( *text ) ); -void write( fileHandle_t file, const char *name ); - -virtual int numPoints() { - return target.numPoints(); -} - -virtual idVec3 *getPoint( int index ) { - return target.getPoint( index ); -} - -virtual void addPoint( const idVec3 &v ) { - target.addPoint( v ); -} - -virtual void addPoint( const float x, const float y, const float z ) { - target.addPoint( x, y, z ); -} - -virtual void draw( bool editMode ) { - target.draw( editMode ); -} - -virtual void updateSelection( const idVec3 &move ) { - idCameraPosition::updateSelection( move ); - target.buildSpline(); -} - -protected: -idSplineList target; -long lastTime; -float distSoFar; -}; - -class idCameraFOV { -public: - -idCameraFOV() { - time = 0; - length = 0; - fov = 90; -} - -idCameraFOV( int v ) { - time = 0; - length = 0; - fov = v; -} - -idCameraFOV( int s, int e, long t ) { - startFOV = s; - endFOV = e; - length = t; -} - - -~idCameraFOV(){} - -void setFOV( float f ) { - fov = f; -} - -float getFOV( long t ) { - if ( length ) { - float percent = ( t - startTime ) / length; - if ( percent < 0.0 ) { - percent = 0.0; - } - else if ( percent > 1.0 ) { - percent = 1.0; - } - float temp = endFOV - startFOV; - temp *= percent; - fov = startFOV + temp; - - if ( percent == 1.0 ) { - length = 0.0; - } - } - return fov; -} - -void start( long t ) { - startTime = t; -} - -void reset( float startfov, float endfov, int start, float len ) { - startFOV = startfov; - endFOV = endfov; - startTime = start; - length = len * 1000; -} - -void parse( const char *( *text ) ); -void write( fileHandle_t file, const char *name ); - -protected: -float fov; -float startFOV; -float endFOV; -int startTime; -int time; -float length; -}; - - - - -class idCameraEvent { -public: // parameters -enum eventType { - EVENT_NA = 0x00, - EVENT_WAIT, // - EVENT_TARGETWAIT, // - EVENT_SPEED, // - EVENT_TARGET, // char(name) - EVENT_SNAPTARGET, // - EVENT_FOV, // int(time), int(targetfov) - EVENT_CMD, // - EVENT_TRIGGER, // - EVENT_STOP, // - EVENT_CAMERA, // - EVENT_FADEOUT, // int(time) - EVENT_FADEIN, // int(time) - EVENT_FEATHER, // - EVENT_COUNT -}; - -static const char* eventStr[EVENT_COUNT]; - -idCameraEvent() { - paramStr = ""; - type = EVENT_NA; - time = 0; -} - -idCameraEvent( eventType t, const char *param, long n ) { - type = t; - paramStr = param; - time = n; -} - -~idCameraEvent() {}; - -eventType getType() { - return type; -} - -const char *typeStr() { - return eventStr[static_cast( type )]; -} - -const char *getParam() { - return paramStr.c_str(); -} - -long getTime() { - return time; -} - -void setTime( long n ) { - time = n; -} - -void parse( const char *( *text ) ); -void write( fileHandle_t file, const char *name ); - -void setTriggered( bool b ) { - triggered = b; -} - -bool getTriggered() { - return triggered; -} - -protected: -eventType type; -idStr paramStr; -long time; -bool triggered; - -}; - -class idCameraDef { -public: - -void clear() { - currentCameraPosition = 0; - cameraRunning = false; - lastDirection.Zero(); - baseTime = 30; - activeTarget = 0; - name = "camera01"; - fov.setFOV( 90 ); - int i; - for ( i = 0; i < targetPositions.Num(); i++ ) { - delete targetPositions[i]; - } - for ( i = 0; i < events.Num(); i++ ) { - delete events[i]; - } - delete cameraPosition; - cameraPosition = NULL; - events.Clear(); - targetPositions.Clear(); -} - -idCameraPosition *startNewCamera( idCameraPosition::positionType type ) { - clear(); - if ( type == idCameraPosition::SPLINE ) { - cameraPosition = new idSplinePosition(); - } - else if ( type == idCameraPosition::INTERPOLATED ) { - cameraPosition = new idInterpolatedPosition(); - } - else { - cameraPosition = new idFixedPosition(); - } - return cameraPosition; -} - -idCameraDef() { - cameraPosition = NULL; - clear(); -} - -~idCameraDef() { - clear(); -} - -void addEvent( idCameraEvent::eventType t, const char *param, long time ); - -void addEvent( idCameraEvent *event ); - -void removeEvent( int index ); - -static int sortEvents( const void *p1, const void *p2 ); - -int numEvents() { - return events.Num(); -} - -idCameraEvent *getEvent( int index ) { - assert( index >= 0 && index < events.Num() ); - return events[index]; -} - -void parse( const char *( *text ) ); -bool load( const char *filename ); -void save( const char *filename ); - -void buildCamera(); - -//idSplineList *getcameraPosition() { -// return &cameraPosition; -//} - -static idCameraPosition *newFromType( idCameraPosition::positionType t ) { - switch ( t ) { - case idCameraPosition::FIXED: return new idFixedPosition(); - case idCameraPosition::INTERPOLATED: return new idInterpolatedPosition(); - case idCameraPosition::SPLINE: return new idSplinePosition(); - default: - break; - }; - return NULL; -} - -void addTarget( const char *name, idCameraPosition::positionType type ); - -idCameraPosition *getActiveTarget() { - if ( targetPositions.Num() == 0 ) { - addTarget( NULL, idCameraPosition::FIXED ); - } - return targetPositions[activeTarget]; -} - -idCameraPosition *getActiveTarget( int index ) { - if ( targetPositions.Num() == 0 ) { - addTarget( NULL, idCameraPosition::FIXED ); - return targetPositions[0]; - } - return targetPositions[index]; -} - -int numTargets() { - return targetPositions.Num(); -} - - -void setActiveTargetByName( const char *name ) { - for ( int i = 0; i < targetPositions.Num(); i++ ) { - if ( Q_stricmp( name, targetPositions[i]->getName() ) == 0 ) { - setActiveTarget( i ); - return; - } - } -} - -void setActiveTarget( int index ) { - assert( index >= 0 && index < targetPositions.Num() ); - activeTarget = index; -} - -void setRunning( bool b ) { - cameraRunning = b; -} - -void setBaseTime( float f ) { - baseTime = f; -} - -float getBaseTime() { - return baseTime; -} - -float getTotalTime() { - return totalTime; -} - -void startCamera( long t ); -void stopCamera() { - cameraRunning = true; -} -void getActiveSegmentInfo( int segment, idVec3 &origin, idVec3 &direction, float *fv ); - -bool getCameraInfo( long time, idVec3 &origin, idVec3 &direction, float *fv ); -bool getCameraInfo( long time, float *origin, float *direction, float *fv ) { - idVec3 org, dir; - org[0] = origin[0]; - org[1] = origin[1]; - org[2] = origin[2]; - dir[0] = direction[0]; - dir[1] = direction[1]; - dir[2] = direction[2]; - bool b = getCameraInfo( time, org, dir, fv ); - origin[0] = org[0]; - origin[1] = org[1]; - origin[2] = org[2]; - direction[0] = dir[0]; - direction[1] = dir[1]; - direction[2] = dir[2]; - return b; -} - -void draw( bool editMode ) { - // gcc doesn't allow casting away from bools - // why? I've no idea... - if ( cameraPosition ) { - cameraPosition->draw( (bool)( ( editMode || cameraRunning ) && cameraEdit ) ); - int count = targetPositions.Num(); - for ( int i = 0; i < count; i++ ) { - targetPositions[i]->draw( (bool)( ( editMode || cameraRunning ) && i == activeTarget && !cameraEdit ) ); - } - } -} - -/* - int numSegments() { - if (cameraEdit) { - return cameraPosition.numSegments(); - } - return getTargetSpline()->numSegments(); - } - - int getActiveSegment() { - if (cameraEdit) { - return cameraPosition.getActiveSegment(); - } - return getTargetSpline()->getActiveSegment(); - } - - void setActiveSegment(int i) { - if (cameraEdit) { - cameraPosition.setActiveSegment(i); - } else { - getTargetSpline()->setActiveSegment(i); - } - } - */ -int numPoints() { - if ( cameraEdit ) { - return cameraPosition->numPoints(); - } - return getActiveTarget()->numPoints(); -} - -const idVec3 *getPoint( int index ) { - if ( cameraEdit ) { - return cameraPosition->getPoint( index ); - } - return getActiveTarget()->getPoint( index ); -} - -void stopEdit() { - editMode = false; - if ( cameraEdit ) { - cameraPosition->stopEdit(); - } - else { - getActiveTarget()->stopEdit(); - } -} - -void startEdit( bool camera ) { - cameraEdit = camera; - if ( camera ) { - cameraPosition->startEdit(); - for ( int i = 0; i < targetPositions.Num(); i++ ) { - targetPositions[i]->stopEdit(); - } - } - else { - getActiveTarget()->startEdit(); - cameraPosition->stopEdit(); - } - editMode = true; -} - -bool waitEvent( int index ); - -const char *getName() { - return name.c_str(); -} - -void setName( const char *p ) { - name = p; -} - -idCameraPosition *getPositionObj() { - if ( cameraPosition == NULL ) { - cameraPosition = new idFixedPosition(); - } - return cameraPosition; -} - -protected: -idStr name; -int currentCameraPosition; -idVec3 lastDirection; -bool cameraRunning; -idCameraPosition *cameraPosition; -idList targetPositions; -idList events; -idCameraFOV fov; -int activeTarget; -float totalTime; -float baseTime; -long startTime; - -bool cameraEdit; -bool editMode; -}; - -extern bool g_splineMode; - -extern idCameraDef *g_splineList; - - -#endif diff --git a/tools/urt/libs/splines/util_list.h b/tools/urt/libs/splines/util_list.h deleted file mode 100644 index 1cce850..0000000 --- a/tools/urt/libs/splines/util_list.h +++ /dev/null @@ -1,347 +0,0 @@ -/* - Copyright (C) 1999-2007 id Software, Inc. and contributors. - For a list of contributors, see the accompanying CONTRIBUTORS file. - - This file is part of GtkRadiant. - - GtkRadiant is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - GtkRadiant is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with GtkRadiant; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - */ - -#ifndef __UTIL_LIST_H__ -#define __UTIL_LIST_H__ - -#include -#include - -template< class type > -class idList { -private: -int m_num; -int m_size; -int m_granularity; -type *m_list; - -public: -idList( int granularity = 16 ); -~idList(); -void Clear( void ); -int Num( void ); -void SetNum( int num ); -void SetGranularity( int granularity ); -void Condense( void ); -int Size( void ); -void Resize( int size ); -type operator[]( int index ) const; -type &operator[]( int index ); -int Append( type const & obj ); -int AddUnique( type const & obj ); -type *Find( type const & obj, int *index = NULL ); -bool RemoveIndex( int index ); -bool Remove( type const & obj ); -typedef int cmp_t ( const void *, const void * ); -void Sort( cmp_t *compare ); -}; - -/* - ================ - idList::idList( int ) - ================ - */ -template< class type > -inline idList::idList( int granularity ) { - assert( granularity > 0 ); - - m_list = NULL; - m_granularity = granularity; - Clear(); -} - -/* - ================ - idList::~idList - ================ - */ -template< class type > -inline idList::~idList() { - Clear(); -} - -/* - ================ - idList::Clear - ================ - */ -template< class type > -inline void idList::Clear( void ) { - if ( m_list ) { - delete[] m_list; - } - - m_list = NULL; - m_num = 0; - m_size = 0; -} - -/* - ================ - idList::Num - ================ - */ -template< class type > -inline int idList::Num( void ) { - return m_num; -} - -/* - ================ - idList::SetNum - ================ - */ -template< class type > -inline void idList::SetNum( int num ) { - assert( num >= 0 ); - if ( num > m_size ) { - // resize it up to the closest level of granularity - Resize( ( ( num + m_granularity - 1 ) / m_granularity ) * m_granularity ); - } - m_num = num; -} - -/* - ================ - idList::SetGranularity - ================ - */ -template< class type > -inline void idList::SetGranularity( int granularity ) { - int newsize; - - assert( granularity > 0 ); - m_granularity = granularity; - - if ( m_list ) { - // resize it to the closest level of granularity - newsize = ( ( m_num + m_granularity - 1 ) / m_granularity ) * m_granularity; - if ( newsize != m_size ) { - Resize( newsize ); - } - } -} - -/* - ================ - idList::Condense - - Resizes the array to exactly the number of elements it contains - ================ - */ -template< class type > -inline void idList::Condense( void ) { - if ( m_list ) { - if ( m_num ) { - Resize( m_num ); - } - else { - Clear(); - } - } -} - -/* - ================ - idList::Size - ================ - */ -template< class type > -inline int idList::Size( void ) { - return m_size; -} - -/* - ================ - idList::Resize - ================ - */ -template< class type > -inline void idList::Resize( int size ) { - type *temp; - int i; - - assert( size > 0 ); - - if ( size <= 0 ) { - Clear(); - return; - } - - temp = m_list; - m_size = size; - if ( m_size < m_num ) { - m_num = m_size; - } - - m_list = new type[ m_size ]; - for ( i = 0; i < m_num; i++ ) { - m_list[ i ] = temp[ i ]; - } - - if ( temp ) { - delete[] temp; - } -} - -/* - ================ - idList::operator[] const - ================ - */ -template< class type > -inline type idList::operator[]( int index ) const { - assert( index >= 0 ); - assert( index < m_num ); - - return m_list[ index ]; -} - -/* - ================ - idList::operator[] - ================ - */ -template< class type > -inline type &idList::operator[]( int index ) { - assert( index >= 0 ); - assert( index < m_num ); - - return m_list[ index ]; -} - -/* - ================ - idList::Append - ================ - */ -template< class type > -inline int idList::Append( type const & obj ) { - if ( !m_list ) { - Resize( m_granularity ); - } - - if ( m_num == m_size ) { - Resize( m_size + m_granularity ); - } - - m_list[ m_num ] = obj; - m_num++; - - return m_num - 1; -} - -/* - ================ - idList::AddUnique - ================ - */ -template< class type > -inline int idList::AddUnique( type const & obj ) { - int index; - - if ( !Find( obj, &index ) ) { - index = Append( obj ); - } - - return index; -} - -/* - ================ - idList::Find - ================ - */ -template< class type > -inline type *idList::Find( type const & obj, int *index ) { - int i; - - for ( i = 0; i < m_num; i++ ) { - if ( m_list[ i ] == obj ) { - if ( index ) { - *index = i; - } - return &m_list[ i ]; - } - } - - return NULL; -} - -/* - ================ - idList::RemoveIndex - ================ - */ -template< class type > -inline bool idList::RemoveIndex( int index ) { - int i; - - if ( !m_list || !m_num ) { - return false; - } - - assert( index >= 0 ); - assert( index < m_num ); - - if ( ( index < 0 ) || ( index >= m_num ) ) { - return false; - } - - m_num--; - for ( i = index; i < m_num; i++ ) { - m_list[ i ] = m_list[ i + 1 ]; - } - - return true; -} - -/* - ================ - idList::Remove - ================ - */ -template< class type > -inline bool idList::Remove( type const & obj ) { - int index; - - if ( Find( obj, &index ) ) { - return RemoveIndex( index ); - } - - return false; -} - -/* - ================ - idList::Sort - ================ - */ -template< class type > -inline void idList::Sort( cmp_t *compare ) { - if ( !m_list ) { - return; - } - - qsort( ( void * )m_list, ( size_t )m_num, sizeof( type ), compare ); -} - -#endif /* !__UTIL_LIST_H__ */ diff --git a/tools/urt/libs/splines/util_str.cpp b/tools/urt/libs/splines/util_str.cpp deleted file mode 100644 index eb51533..0000000 --- a/tools/urt/libs/splines/util_str.cpp +++ /dev/null @@ -1,578 +0,0 @@ -/* - Copyright (C) 1999-2007 id Software, Inc. and contributors. - For a list of contributors, see the accompanying CONTRIBUTORS file. - - This file is part of GtkRadiant. - - GtkRadiant is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - GtkRadiant is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with GtkRadiant; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - */ - -//need to rewrite this - -#include "util_str.h" -#include -#include -#include -#include - -#ifdef _WIN32 -#pragma warning(disable : 4244) // 'conversion' conversion from 'type1' to 'type2', possible loss of data -#pragma warning(disable : 4710) // function 'blah' not inlined -#endif - -static const int STR_ALLOC_GRAN = 20; - -// screwy but intentional -#ifdef __APPLE_BUG__ -char *idStr::__tolower -#else -char *idStr::tolower -#endif -( - char *s1 -){ - char *s; - - s = s1; - while ( *s ) - { - *s = ::tolower( *s ); - s++; - } - - return s1; -} - -// screwy but intentional -#ifdef __APPLE_BUG__ -char *idStr::__toupper -#else -char *idStr::toupper -#endif -( - char *s1 -){ - char *s; - - s = s1; - while ( *s ) - { - *s = ::toupper( *s ); - s++; - } - - return s1; -} - -int idStr::icmpn -( - const char *s1, - const char *s2, - int n -){ - int c1; - int c2; - - do - { - c1 = *s1++; - c2 = *s2++; - - if ( !n-- ) { - // idStrings are equal until end point - return 0; - } - - if ( c1 != c2 ) { - if ( c1 >= 'a' && c1 <= 'z' ) { - c1 -= ( 'a' - 'A' ); - } - - if ( c2 >= 'a' && c2 <= 'z' ) { - c2 -= ( 'a' - 'A' ); - } - - if ( c1 < c2 ) { - // strings less than - return -1; - } - else if ( c1 > c2 ) { - // strings greater than - return 1; - } - } - } - while ( c1 ); - - // strings are equal - return 0; -} - -int idStr::icmp -( - const char *s1, - const char *s2 -){ - int c1; - int c2; - - do - { - c1 = *s1++; - c2 = *s2++; - - if ( c1 != c2 ) { - if ( c1 >= 'a' && c1 <= 'z' ) { - c1 -= ( 'a' - 'A' ); - } - - if ( c2 >= 'a' && c2 <= 'z' ) { - c2 -= ( 'a' - 'A' ); - } - - if ( c1 < c2 ) { - // strings less than - return -1; - } - else if ( c1 > c2 ) { - // strings greater than - return 1; - } - } - } - while ( c1 ); - - // strings are equal - return 0; -} - -int idStr::cmpn -( - const char *s1, - const char *s2, - int n -){ - int c1; - int c2; - - do - { - c1 = *s1++; - c2 = *s2++; - - if ( !n-- ) { - // strings are equal until end point - return 0; - } - - if ( c1 < c2 ) { - // strings less than - return -1; - } - else if ( c1 > c2 ) { - // strings greater than - return 1; - } - } - while ( c1 ); - - // strings are equal - return 0; -} - -int idStr::cmp -( - const char *s1, - const char *s2 -){ - int c1; - int c2; - - do - { - c1 = *s1++; - c2 = *s2++; - - if ( c1 < c2 ) { - // strings less than - return -1; - } - else if ( c1 > c2 ) { - // strings greater than - return 1; - } - } - while ( c1 ); - - // strings are equal - return 0; -} - -/* - ============ - IsNumeric - - Checks a string to see if it contains only numerical values. - ============ - */ -bool idStr::isNumeric -( - const char *str -){ - int len; - int i; - bool dot; - - if ( *str == '-' ) { - str++; - } - - dot = false; - len = strlen( str ); - for ( i = 0; i < len; i++ ) - { - if ( !isdigit( str[ i ] ) ) { - if ( ( str[ i ] == '.' ) && !dot ) { - dot = true; - continue; - } - return false; - } - } - - return true; -} - -idStr operator+ -( - const idStr& a, - const float b -){ - char text[ 20 ]; - - idStr result( a ); - - sprintf( text, "%f", b ); - result.append( text ); - - return result; -} - -idStr operator+ -( - const idStr& a, - const int b -){ - char text[ 20 ]; - - idStr result( a ); - - sprintf( text, "%d", b ); - result.append( text ); - - return result; -} - -idStr operator+ -( - const idStr& a, - const unsigned b -){ - char text[ 20 ]; - - idStr result( a ); - - sprintf( text, "%u", b ); - result.append( text ); - - return result; -} - -idStr& idStr::operator+= -( - const float a -){ - char text[ 20 ]; - - sprintf( text, "%f", a ); - append( text ); - - return *this; -} - -idStr& idStr::operator+= -( - const int a -){ - char text[ 20 ]; - - sprintf( text, "%d", a ); - append( text ); - - return *this; -} - -idStr& idStr::operator+= -( - const unsigned a -){ - char text[ 20 ]; - - sprintf( text, "%u", a ); - append( text ); - - return *this; -} - -void idStr::CapLength -( - int newlen -){ - assert( m_data ); - - if ( length() <= newlen ) { - return; - } - - EnsureDataWritable(); - - m_data->data[newlen] = 0; - m_data->len = newlen; -} - -void idStr::EnsureDataWritable -( - void -){ - assert( m_data ); - strdata *olddata; - int len; - - if ( !m_data->refcount ) { - return; - } - - olddata = m_data; - len = length(); - - m_data = new strdata; - - EnsureAlloced( len + 1, false ); - strncpy( m_data->data, olddata->data, len + 1 ); - m_data->len = len; - - olddata->DelRef(); -} - -void idStr::EnsureAlloced( int amount, bool keepold ) { - - if ( !m_data ) { - m_data = new strdata(); - } - - // Now, let's make sure it's writable - EnsureDataWritable(); - - char *newbuffer; - bool wasalloced = ( m_data->alloced != 0 ); - - if ( amount < m_data->alloced ) { - return; - } - - assert( amount ); - if ( amount == 1 ) { - m_data->alloced = 1; - } - else { - int newsize, mod; - mod = amount % STR_ALLOC_GRAN; - if ( !mod ) { - newsize = amount; - } - else { - newsize = amount + STR_ALLOC_GRAN - mod; - } - m_data->alloced = newsize; - } - - newbuffer = new char[m_data->alloced]; - if ( wasalloced && keepold ) { - strcpy( newbuffer, m_data->data ); - } - - if ( m_data->data ) { - delete [] m_data->data; - } - m_data->data = newbuffer; -} - -void idStr::BackSlashesToSlashes -( - void -){ - int i; - - EnsureDataWritable(); - - for ( i = 0; i < m_data->len; i++ ) - { - if ( m_data->data[i] == '\\' ) { - m_data->data[i] = '/'; - } - } -} - -void idStr::snprintf -( - char *dst, - int size, - const char *fmt, - ... -){ - char buffer[0x10000]; - int len; - va_list argptr; - - va_start( argptr,fmt ); - len = vsprintf( buffer,fmt,argptr ); - va_end( argptr ); - - assert( len < size ); - - strncpy( dst, buffer, size - 1 ); -} - -#ifdef _WIN32 -#pragma warning(disable : 4189) // local variable is initialized but not referenced -#endif - -/* - ================= - TestStringClass - - This is a fairly rigorous test of the idStr class's functionality. - Because of the fairly global and subtle ramifications of a bug occuring - in this class, it should be run after any changes to the class. - Add more tests as functionality is changed. Tests should include - any possible bounds violation and NULL data tests. - ================= - */ -void TestStringClass -( - void -){ - char ch; // ch == ? - idStr *t; // t == ? - idStr a; // a.len == 0, a.data == "\0" - idStr b; // b.len == 0, b.data == "\0" - idStr c( "test" ); // c.len == 4, c.data == "test\0" - idStr d( c ); // d.len == 4, d.data == "test\0" - idStr e( reinterpret_cast( NULL ) ); - // e.len == 0, e.data == "\0" ASSERT! - int i; // i == ? - - i = a.length(); // i == 0 - i = c.length(); // i == 4 - - const char *s1 = a.c_str(); // s1 == "\0" - const char *s2 = c.c_str(); // s2 == "test\0" - - t = new idStr(); // t->len == 0, t->data == "\0" - delete t; // t == ? - - b = "test"; // b.len == 4, b.data == "test\0" - t = new idStr( "test" ); // t->len == 4, t->data == "test\0" - delete t; // t == ? - - a = c; // a.len == 4, a.data == "test\0" -// a = ""; - a = NULL; // a.len == 0, a.data == "\0" ASSERT! - a = c + d; // a.len == 8, a.data == "testtest\0" - a = c + "wow"; // a.len == 7, a.data == "testwow\0" - a = c + reinterpret_cast( NULL ); - // a.len == 4, a.data == "test\0" ASSERT! - a = "this" + d; // a.len == 8, a.data == "thistest\0" - a = reinterpret_cast( NULL ) + d; - // a.len == 4, a.data == "test\0" ASSERT! - a += c; // a.len == 8, a.data == "testtest\0" - a += "wow"; // a.len == 11, a.data == "testtestwow\0" - a += reinterpret_cast( NULL ); - // a.len == 11, a.data == "testtestwow\0" ASSERT! - - a = "test"; // a.len == 4, a.data == "test\0" - ch = a[ 0 ]; // ch == 't' - ch = a[ -1 ]; // ch == 0 ASSERT! - ch = a[ 1000 ]; // ch == 0 ASSERT! - ch = a[ 0 ]; // ch == 't' - ch = a[ 1 ]; // ch == 'e' - ch = a[ 2 ]; // ch == 's' - ch = a[ 3 ]; // ch == 't' - ch = a[ 4 ]; // ch == '\0' ASSERT! - ch = a[ 5 ]; // ch == '\0' ASSERT! - - a[ 1 ] = 'b'; // a.len == 4, a.data == "tbst\0" - a[ -1 ] = 'b'; // a.len == 4, a.data == "tbst\0" ASSERT! - a[ 0 ] = '0'; // a.len == 4, a.data == "0bst\0" - a[ 1 ] = '1'; // a.len == 4, a.data == "01st\0" - a[ 2 ] = '2'; // a.len == 4, a.data == "012t\0" - a[ 3 ] = '3'; // a.len == 4, a.data == "0123\0" - a[ 4 ] = '4'; // a.len == 4, a.data == "0123\0" ASSERT! - a[ 5 ] = '5'; // a.len == 4, a.data == "0123\0" ASSERT! - a[ 7 ] = '7'; // a.len == 4, a.data == "0123\0" ASSERT! - - a = "test"; // a.len == 4, a.data == "test\0" - b = "no"; // b.len == 2, b.data == "no\0" - - i = ( a == b ); // i == 0 - i = ( a == c ); // i == 1 - - i = ( a == "blow" ); // i == 0 - i = ( a == "test" ); // i == 1 - i = ( a == NULL ); // i == 0 ASSERT! - - i = ( "test" == b ); // i == 0 - i = ( "test" == a ); // i == 1 - i = ( NULL == a ); // i == 0 ASSERT! - - i = ( a != b ); // i == 1 - i = ( a != c ); // i == 0 - - i = ( a != "blow" ); // i == 1 - i = ( a != "test" ); // i == 0 - i = ( a != NULL ); // i == 1 ASSERT! - - i = ( "test" != b ); // i == 1 - i = ( "test" != a ); // i == 0 - i = ( NULL != a ); // i == 1 ASSERT! - - a = "test"; // a.data == "test" - b = a; // b.data == "test" - - a = "not"; // a.data == "not", b.data == "test" - - a = b; // a.data == b.data == "test" - - a += b; // a.data == "testtest", b.data = "test" - - a = b; - - a[1] = '1'; // a.data = "t1st", b.data = "test" -} - -#ifdef _WIN32 -#pragma warning(default : 4189) // local variable is initialized but not referenced -#pragma warning(disable : 4514) // unreferenced inline function has been removed -#endif diff --git a/tools/urt/libs/splines/util_str.h b/tools/urt/libs/splines/util_str.h deleted file mode 100644 index c8c90f2..0000000 --- a/tools/urt/libs/splines/util_str.h +++ /dev/null @@ -1,721 +0,0 @@ -/* - Copyright (C) 1999-2007 id Software, Inc. and contributors. - For a list of contributors, see the accompanying CONTRIBUTORS file. - - This file is part of GtkRadiant. - - GtkRadiant is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - GtkRadiant is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with GtkRadiant; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - */ - -//need to rewrite this - -#ifndef __UTIL_STR_H__ -#define __UTIL_STR_H__ - -#include -#include -#include - -#ifdef _WIN32 -#pragma warning(disable : 4710) // function 'blah' not inlined -#endif - -void TestStringClass(); - -class strdata -{ -public: -strdata () : len( 0 ), refcount( 0 ), data( NULL ), alloced( 0 ) {} -~strdata (){ - if ( data ) { - delete [] data; - } -} - -void AddRef() { refcount++; } -bool DelRef(){ // True if killed - refcount--; - if ( refcount < 0 ) { - delete this; - return true; - } - - return false; -} - -int len; -int refcount; -char *data; -int alloced; -}; - -class idStr { -protected: -strdata *m_data; -void EnsureAlloced( int, bool keepold = true ); -void EnsureDataWritable(); - -public: -~idStr(); -idStr(); -idStr( const char *text ); -idStr( const idStr& string ); -idStr( const idStr string, int start, int end ); -idStr( const char ch ); -idStr( const int num ); -idStr( const float num ); -idStr( const unsigned num ); -int length( void ) const; -int allocated( void ) const; -const char * c_str( void ) const; - -void append( const char *text ); -void append( const idStr& text ); -char operator[]( int index ) const; -char& operator[]( int index ); - -void operator=( const idStr& text ); -void operator=( const char *text ); - -friend idStr operator+( const idStr& a, const idStr& b ); -friend idStr operator+( const idStr& a, const char *b ); -friend idStr operator+( const char *a, const idStr& b ); - -friend idStr operator+( const idStr& a, const float b ); -friend idStr operator+( const idStr& a, const int b ); -friend idStr operator+( const idStr& a, const unsigned b ); -friend idStr operator+( const idStr& a, const bool b ); -friend idStr operator+( const idStr& a, const char b ); - -idStr& operator+=( const idStr& a ); -idStr& operator+=( const char *a ); -idStr& operator+=( const float a ); -idStr& operator+=( const char a ); -idStr& operator+=( const int a ); -idStr& operator+=( const unsigned a ); -idStr& operator+=( const bool a ); - -friend bool operator==( const idStr& a, const idStr& b ); -friend bool operator==( const idStr& a, const char *b ); -friend bool operator==( const char *a, const idStr& b ); - -friend bool operator!=( const idStr& a, const idStr& b ); -friend bool operator!=( const idStr& a, const char *b ); -friend bool operator!=( const char *a, const idStr& b ); - -operator const char *() const; -operator const char *(); - -int icmpn( const char *text, int n ) const; -int icmpn( const idStr& text, int n ) const; -int icmp( const char *text ) const; -int icmp( const idStr& text ) const; -int cmpn( const char *text, int n ) const; -int cmpn( const idStr& text, int n ) const; -int cmp( const char *text ) const; -int cmp( const idStr& text ) const; - -void tolower( void ); -void toupper( void ); - -static char *tolower( char *s1 ); -static char *toupper( char *s1 ); - -static int icmpn( const char *s1, const char *s2, int n ); -static int icmp( const char *s1, const char *s2 ); -static int cmpn( const char *s1, const char *s2, int n ); -static int cmp( const char *s1, const char *s2 ); - -static void snprintf( char *dst, int size, const char *fmt, ... ); - -static bool isNumeric( const char *str ); -bool isNumeric( void ) const; - -void CapLength( int ); - -void BackSlashesToSlashes(); - -}; - -inline idStr::~idStr(){ - if ( m_data ) { - m_data->DelRef(); - m_data = NULL; - } -} - -inline idStr::idStr() : m_data( NULL ){ - EnsureAlloced( 1 ); - m_data->data[ 0 ] = 0; -} - -inline idStr::idStr -( - const char *text -) : m_data( NULL ){ - int len; - - assert( text ); - - if ( text ) { - len = strlen( text ); - EnsureAlloced( len + 1 ); - strcpy( m_data->data, text ); - m_data->len = len; - } - else - { - EnsureAlloced( 1 ); - m_data->data[ 0 ] = 0; - m_data->len = 0; - } -} - -inline idStr::idStr -( - const idStr& text -) : m_data( NULL ){ - m_data = text.m_data; - m_data->AddRef(); -} - -inline idStr::idStr -( - const idStr text, - int start, - int end -) : m_data( NULL ){ - int i; - int len; - - if ( end > text.length() ) { - end = text.length(); - } - - if ( start > text.length() ) { - start = text.length(); - } - - len = end - start; - if ( len < 0 ) { - len = 0; - } - - EnsureAlloced( len + 1 ); - - for ( i = 0; i < len; i++ ) - { - m_data->data[ i ] = text[ start + i ]; - } - - m_data->data[ len ] = 0; - m_data->len = len; -} - -inline idStr::idStr -( - const char ch -) : m_data( NULL ){ - EnsureAlloced( 2 ); - - m_data->data[ 0 ] = ch; - m_data->data[ 1 ] = 0; - m_data->len = 1; -} - -inline idStr::idStr -( - const float num -) : m_data( NULL ){ - char text[ 32 ]; - int len; - - sprintf( text, "%.3f", num ); - len = strlen( text ); - EnsureAlloced( len + 1 ); - strcpy( m_data->data, text ); - m_data->len = len; -} - -inline idStr::idStr -( - const int num -) : m_data( NULL ){ - char text[ 32 ]; - int len; - - sprintf( text, "%d", num ); - len = strlen( text ); - EnsureAlloced( len + 1 ); - strcpy( m_data->data, text ); - m_data->len = len; -} - -inline idStr::idStr -( - const unsigned num -) : m_data( NULL ){ - char text[ 32 ]; - int len; - - sprintf( text, "%u", num ); - len = strlen( text ); - EnsureAlloced( len + 1 ); - strcpy( m_data->data, text ); - m_data->len = len; -} - -inline int idStr::length( void ) const { - return ( m_data != NULL ) ? m_data->len : 0; -} - -inline int idStr::allocated( void ) const { - return ( m_data != NULL ) ? m_data->alloced + sizeof( *m_data ) : 0; -} - -inline const char *idStr::c_str( void ) const { - assert( m_data ); - - return m_data->data; -} - -inline void idStr::append -( - const char *text -){ - int len; - - assert( text ); - - if ( text ) { - len = length() + strlen( text ); - EnsureAlloced( len + 1 ); - - strcat( m_data->data, text ); - m_data->len = len; - } -} - -inline void idStr::append -( - const idStr& text -){ - int len; - - len = length() + text.length(); - EnsureAlloced( len + 1 ); - - strcat( m_data->data, text.c_str() ); - m_data->len = len; -} - -inline char idStr::operator[]( int index ) const { - assert( m_data ); - - if ( !m_data ) { - return 0; - } - - // don't include the '/0' in the test, because technically, it's out of bounds - assert( ( index >= 0 ) && ( index < m_data->len ) ); - - // In release mode, give them a null character - // don't include the '/0' in the test, because technically, it's out of bounds - if ( ( index < 0 ) || ( index >= m_data->len ) ) { - return 0; - } - - return m_data->data[ index ]; -} - -inline char& idStr::operator[] -( - int index -){ - // Used for result for invalid indices - static char dummy = 0; - assert( m_data ); - - // We don't know if they'll write to it or not - // if it's not a const object - EnsureDataWritable(); - - if ( !m_data ) { - return dummy; - } - - // don't include the '/0' in the test, because technically, it's out of bounds - assert( ( index >= 0 ) && ( index < m_data->len ) ); - - // In release mode, let them change a safe variable - // don't include the '/0' in the test, because technically, it's out of bounds - if ( ( index < 0 ) || ( index >= m_data->len ) ) { - return dummy; - } - - return m_data->data[ index ]; -} - -inline void idStr::operator= -( - const idStr& text -){ - // adding the reference before deleting our current reference prevents - // us from deleting our string if we are copying from ourself - text.m_data->AddRef(); - m_data->DelRef(); - m_data = text.m_data; -} - -inline void idStr::operator= -( - const char *text -){ - int len; - - assert( text ); - - if ( !text ) { - // safe behaviour if NULL - EnsureAlloced( 1, false ); - m_data->data[0] = 0; - m_data->len = 0; - return; - } - - if ( !m_data ) { - len = strlen( text ); - EnsureAlloced( len + 1, false ); - strcpy( m_data->data, text ); - m_data->len = len; - return; - } - - if ( text == m_data->data ) { - return; // Copying same thing. Punt. - - } - // If we alias and I don't do this, I could corrupt other strings... This - // will get called with EnsureAlloced anyway - EnsureDataWritable(); - - // Now we need to check if we're aliasing.. - if ( text >= m_data->data && text <= m_data->data + m_data->len ) { - // Great, we're aliasing. We're copying from inside ourselves. - // This means that I don't have to ensure that anything is alloced, - // though I'll assert just in case. - int diff = text - m_data->data; - int i; - - assert( strlen( text ) < (unsigned) m_data->len ); - - for ( i = 0; text[i]; i++ ) - { - m_data->data[i] = text[i]; - } - - m_data->data[i] = 0; - - m_data->len -= diff; - - return; - } - - len = strlen( text ); - EnsureAlloced( len + 1, false ); - strcpy( m_data->data, text ); - m_data->len = len; -} - -inline idStr operator+ -( - const idStr& a, - const idStr& b -){ - idStr result( a ); - - result.append( b ); - - return result; -} - -inline idStr operator+ -( - const idStr& a, - const char *b -){ - idStr result( a ); - - result.append( b ); - - return result; -} - -inline idStr operator+ -( - const char *a, - const idStr& b -){ - idStr result( a ); - - result.append( b ); - - return result; -} - -inline idStr operator+ -( - const idStr& a, - const bool b -){ - idStr result( a ); - - result.append( b ? "true" : "false" ); - - return result; -} - -inline idStr operator+ -( - const idStr& a, - const char b -){ - char text[ 2 ]; - - text[ 0 ] = b; - text[ 1 ] = 0; - - return a + text; -} - -inline idStr& idStr::operator+= -( - const idStr& a -){ - append( a ); - return *this; -} - -inline idStr& idStr::operator+= -( - const char *a -){ - append( a ); - return *this; -} - -inline idStr& idStr::operator+= -( - const char a -){ - char text[ 2 ]; - - text[ 0 ] = a; - text[ 1 ] = 0; - append( text ); - - return *this; -} - -inline idStr& idStr::operator+= -( - const bool a -){ - append( a ? "true" : "false" ); - return *this; -} - -inline bool operator== -( - const idStr& a, - const idStr& b -){ - return ( !strcmp( a.c_str(), b.c_str() ) ); -} - -inline bool operator== -( - const idStr& a, - const char *b -){ - assert( b ); - if ( !b ) { - return false; - } - return ( !strcmp( a.c_str(), b ) ); -} - -inline bool operator== -( - const char *a, - const idStr& b -){ - assert( a ); - if ( !a ) { - return false; - } - return ( !strcmp( a, b.c_str() ) ); -} - -inline bool operator!= -( - const idStr& a, - const idStr& b -){ - return !( a == b ); -} - -inline bool operator!= -( - const idStr& a, - const char *b -){ - return !( a == b ); -} - -inline bool operator!= -( - const char *a, - const idStr& b -){ - return !( a == b ); -} - -inline int idStr::icmpn -( - const char *text, - int n -) const { - assert( m_data ); - assert( text ); - - return idStr::icmpn( m_data->data, text, n ); -} - -inline int idStr::icmpn -( - const idStr& text, - int n -) const { - assert( m_data ); - assert( text.m_data ); - - return idStr::icmpn( m_data->data, text.m_data->data, n ); -} - -inline int idStr::icmp -( - const char *text -) const { - assert( m_data ); - assert( text ); - - return idStr::icmp( m_data->data, text ); -} - -inline int idStr::icmp -( - const idStr& text -) const { - assert( c_str() ); - assert( text.c_str() ); - - return idStr::icmp( c_str(), text.c_str() ); -} - -inline int idStr::cmp -( - const char *text -) const { - assert( m_data ); - assert( text ); - - return idStr::cmp( m_data->data, text ); -} - -inline int idStr::cmp -( - const idStr& text -) const { - assert( c_str() ); - assert( text.c_str() ); - - return idStr::cmp( c_str(), text.c_str() ); -} - -inline int idStr::cmpn -( - const char *text, - int n -) const { - assert( c_str() ); - assert( text ); - - return idStr::cmpn( c_str(), text, n ); -} - -inline int idStr::cmpn -( - const idStr& text, - int n -) const { - assert( c_str() ); - assert( text.c_str() ); - - return idStr::cmpn( c_str(), text.c_str(), n ); -} - -inline void idStr::tolower -( - void -){ - assert( m_data ); - - EnsureDataWritable(); - - idStr::tolower( m_data->data ); -} - -inline void idStr::toupper -( - void -){ - assert( m_data ); - - EnsureDataWritable(); - - idStr::toupper( m_data->data ); -} - -inline bool idStr::isNumeric -( - void -) const { - assert( m_data ); - return idStr::isNumeric( m_data->data ); -} - -inline idStr::operator const char *() { - return c_str(); -} - -inline idStr::operator const char * -( - void -) const { - return c_str(); -} - -#endif diff --git a/tools/urt/libs/str.cpp b/tools/urt/libs/str.cpp deleted file mode 100644 index c69a420..0000000 --- a/tools/urt/libs/str.cpp +++ /dev/null @@ -1,2 +0,0 @@ - -#include "str.h" diff --git a/tools/urt/libs/str.h b/tools/urt/libs/str.h deleted file mode 100644 index e05afbd..0000000 --- a/tools/urt/libs/str.h +++ /dev/null @@ -1,472 +0,0 @@ -/* - Copyright (c) 2001, Loki software, inc. - All rights reserved. - - Redistribution and use in source and binary forms, with or without modification, - are permitted provided that the following conditions are met: - - Redistributions of source code must retain the above copyright notice, this list - of conditions and the following disclaimer. - - Redistributions in binary form must reproduce the above copyright notice, this - list of conditions and the following disclaimer in the documentation and/or - other materials provided with the distribution. - - Neither the name of Loki software nor the names of its contributors may be used - to endorse or promote products derived from this software without specific prior - written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' - AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY - DIRECT,INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef __STR__ -#define __STR__ - -// -// class Str -// loose replacement for CString from MFC -// - -#include -#include - -#include -#include - -#include - -#ifdef WIN32 -#define strcasecmp strcmpi -#if _MSC_VER < 1400 -#define vsnprintf std::vsnprintf -#endif -#else -#include -#endif - -// NOTE TTimo __StrDup was initially implemented in pakstuff.cpp -// causing a bunch of issues for broader targets that use Str.h (such as plugins and modules) -// Q_StrDup should be used now, using a #define __StrDup for easy transition - -#define __StrDup Q_StrDup - -inline char* Q_StrDup( const char* pStr ){ - if ( pStr == 0 ) { - pStr = ""; - } - - return strcpy( new char[strlen( pStr ) + 1], pStr ); -} - -#if defined ( __linux__ ) || defined ( __APPLE__ ) -#define strcmpi strcasecmp -#define stricmp strcasecmp -#define strnicmp strncasecmp - -inline char* strlwr( char* string ){ - char *cp; - for ( cp = string; *cp; ++cp ) - { - if ( 'A' <= *cp && *cp <= 'Z' ) { - *cp += 'a' - 'A'; - } - } - - return string; -} - -inline char* strupr( char* string ){ - char *cp; - for ( cp = string; *cp; ++cp ) - { - if ( 'a' <= *cp && *cp <= 'z' ) { - *cp += 'A' - 'a'; - } - } - - return string; -} -#endif - -static char *g_pStrWork = 0; - -class Str -{ -protected: -bool m_bIgnoreCase; -char *m_pStr; - -public: -Str(){ - m_bIgnoreCase = true; - m_pStr = new char[1]; - m_pStr[0] = '\0'; -} - -Str( char *p ){ - m_bIgnoreCase = true; - m_pStr = __StrDup( p ); -} - -Str( const char *p ){ - m_bIgnoreCase = true; - m_pStr = __StrDup( p ); -} - -Str( const unsigned char *p ){ - m_bIgnoreCase = true; - m_pStr = __StrDup( reinterpret_cast( p ) ); -} - -Str( const char c ){ - m_bIgnoreCase = true; - m_pStr = new char[2]; - m_pStr[0] = c; - m_pStr[1] = '\0'; -} - -const char* GetBuffer() const { - return m_pStr; -} - -char* GetBuffer(){ - return m_pStr; -} - -Str( const Str &s ){ - m_bIgnoreCase = true; - m_pStr = __StrDup( s.GetBuffer() ); -} - -void Deallocate(){ - delete []m_pStr; - m_pStr = 0; -} - -void Allocate( std::size_t n ){ - Deallocate(); - m_pStr = new char[n]; -} - -void MakeEmpty(){ - Deallocate(); - m_pStr = __StrDup( "" ); -} - -~Str(){ - Deallocate(); - // NOTE TTimo: someone explain this g_pStrWork to me? - if ( g_pStrWork ) { - delete []g_pStrWork; - } - g_pStrWork = 0; -} - -void MakeLower(){ - if ( m_pStr ) { - strlwr( m_pStr ); - } -} - -void MakeUpper(){ - if ( m_pStr ) { - strupr( m_pStr ); - } -} - -void TrimRight(){ - char* lpsz = m_pStr; - char* lpszLast = 0; - while ( *lpsz != '\0' ) - { - if ( isspace( *lpsz ) ) { - if ( lpszLast == 0 ) { - lpszLast = lpsz; - } - } - else{ - lpszLast = 0; - } - lpsz++; - } - - if ( lpszLast != 0 ) { - // truncate at trailing space start - *lpszLast = '\0'; - } -} - -void TrimLeft(){ - // find first non-space character - char* lpsz = m_pStr; - while ( isspace( *lpsz ) ) - lpsz++; - - // fix up data and length - std::size_t nDataLength = GetLength() - ( lpsz - m_pStr ); - memmove( m_pStr, lpsz, ( nDataLength + 1 ) ); -} - -char* Find( const char *p ){ - return strstr( m_pStr, p ); -} - -// search starting at a given offset -char* Find( const char *p, std::size_t offset ){ - return strstr( m_pStr + offset, p ); -} - -char* Find( const char ch ){ - return strchr( m_pStr, ch ); -} - -char* ReverseFind( const char ch ){ - return strrchr( m_pStr, ch ); -} - -int Compare( const char* str ) const { - return strcmp( m_pStr, str ); -} - -int CompareNoCase( const char* str ) const { - return strcasecmp( m_pStr, str ); -} - -std::size_t GetLength(){ - return ( m_pStr ) ? strlen( m_pStr ) : 0; -} - -const char* Left( std::size_t n ){ - delete []g_pStrWork; - if ( n > 0 ) { - g_pStrWork = new char[n + 1]; - strncpy( g_pStrWork, m_pStr, n ); - g_pStrWork[n] = '\0'; - } - else - { - g_pStrWork = ""; - g_pStrWork = new char[1]; - g_pStrWork[0] = '\0'; - } - return g_pStrWork; -} - -const char* Right( std::size_t n ){ - delete []g_pStrWork; - if ( n > 0 ) { - g_pStrWork = new char[n + 1]; - std::size_t nStart = GetLength() - n; - strncpy( g_pStrWork, &m_pStr[nStart], n ); - g_pStrWork[n] = '\0'; - } - else - { - g_pStrWork = new char[1]; - g_pStrWork[0] = '\0'; - } - return g_pStrWork; -} - -const char* Mid( std::size_t nFirst ) const { - return Mid( nFirst, strlen( m_pStr ) - nFirst ); -} - -const char* Mid( std::size_t first, std::size_t n ) const { - delete []g_pStrWork; - if ( n > 0 ) { - g_pStrWork = new char[n + 1]; - strncpy( g_pStrWork, m_pStr + first, n ); - g_pStrWork[n] = '\0'; - } - else - { - g_pStrWork = ""; - g_pStrWork = new char[1]; - g_pStrWork[0] = '\0'; - } - return g_pStrWork; -} - -#if 0 // defined(__G_LIB_H__) -void Format( const char* fmt, ... ){ - va_list args; - char *buffer; - - va_start( args, fmt ); - buffer = g_strdup_vprintf( fmt, args ); - va_end( args ); - - delete[] m_pStr; - m_pStr = __StrDup( buffer ); - g_free( buffer ); -} -#else -void Format( const char* fmt, ... ){ - char buffer[1024]; - - { - va_list args; - va_start( args, fmt ); - vsnprintf( buffer, 1023, fmt, args ); - va_end( args ); - } - - delete[] m_pStr; - m_pStr = __StrDup( buffer ); -} -#endif - -void SetAt( std::size_t n, char ch ){ - if ( n < GetLength() ) { - m_pStr[n] = ch; - } -} - -// NOTE: unlike CString, this looses the pointer -void ReleaseBuffer( std::size_t n ){ - char* tmp = m_pStr; - tmp[n] = '\0'; - m_pStr = __StrDup( tmp ); - delete []tmp; -} -void ReleaseBuffer(){ - ReleaseBuffer( GetLength() ); -} - -char* GetBufferSetLength( std::size_t n ){ - char *p = new char[n + 1]; - strncpy( p, m_pStr, n ); - p[n] = '\0'; - delete []m_pStr; - m_pStr = p; - return m_pStr; -} - -// char& operator *() { return *m_pStr; } -// char& operator *() const { return *const_cast(this)->m_pStr; } -operator void*() { - return m_pStr; -} -operator char*() { - return m_pStr; -} -operator const char*() const { return reinterpret_cast( m_pStr ); } -operator unsigned char*() { - return reinterpret_cast( m_pStr ); -} -operator const unsigned char*() const { return reinterpret_cast( m_pStr ); } -Str& operator =( const Str& rhs ){ - if ( &rhs != this ) { - delete[] m_pStr; - m_pStr = __StrDup( rhs.m_pStr ); - } - return *this; -} - -Str& operator =( const char* pStr ){ - if ( m_pStr != pStr ) { - delete[] m_pStr; - m_pStr = __StrDup( pStr ); - } - return *this; -} - -Str& operator +=( const char ch ){ - std::size_t len = GetLength(); - char *p = new char[len + 1 + 1]; - - if ( m_pStr ) { - strcpy( p, m_pStr ); - delete[] m_pStr; - } - - m_pStr = p; - m_pStr[len] = ch; - m_pStr[len + 1] = '\0'; - - return *this; -} - -Str& operator +=( const char *pStr ){ - if ( pStr ) { - if ( m_pStr ) { - char *p = new char[strlen( m_pStr ) + strlen( pStr ) + 1]; - strcpy( p, m_pStr ); - strcat( p, pStr ); - delete[] m_pStr; - m_pStr = p; - } - else - { - m_pStr = __StrDup( pStr ); - } - } - return *this; -} - - -bool operator ==( const Str& rhs ) const { return ( m_bIgnoreCase ) ? stricmp( m_pStr, rhs.m_pStr ) == 0 : strcmp( m_pStr, rhs.m_pStr ) == 0; } -bool operator ==( char* pStr ) const { return ( m_bIgnoreCase ) ? stricmp( m_pStr, pStr ) == 0 : strcmp( m_pStr, pStr ) == 0; } -bool operator ==( const char* pStr ) const { return ( m_bIgnoreCase ) ? stricmp( m_pStr, pStr ) == 0 : strcmp( m_pStr, pStr ) == 0; } -bool operator !=( Str& rhs ) const { return ( m_bIgnoreCase ) ? stricmp( m_pStr, rhs.m_pStr ) != 0 : strcmp( m_pStr, rhs.m_pStr ) != 0; } -bool operator !=( char* pStr ) const { return ( m_bIgnoreCase ) ? stricmp( m_pStr, pStr ) != 0 : strcmp( m_pStr, pStr ) != 0; } -bool operator !=( const char* pStr ) const { return ( m_bIgnoreCase ) ? stricmp( m_pStr, pStr ) != 0 : strcmp( m_pStr, pStr ) != 0; } -bool operator <( const Str& rhs ) const { return ( m_bIgnoreCase ) ? stricmp( m_pStr, rhs.m_pStr ) < 0 : strcmp( m_pStr, rhs.m_pStr ) < 0; } -bool operator <( char* pStr ) const { return ( m_bIgnoreCase ) ? stricmp( m_pStr, pStr ) < 0 : strcmp( m_pStr, pStr ) < 0; } -bool operator <( const char* pStr ) const { return ( m_bIgnoreCase ) ? stricmp( m_pStr, pStr ) < 0 : strcmp( m_pStr, pStr ) < 0; } -bool operator >( const Str& rhs ) const { return ( m_bIgnoreCase ) ? stricmp( m_pStr, rhs.m_pStr ) > 0 : strcmp( m_pStr, rhs.m_pStr ) > 0; } -bool operator >( char* pStr ) const { return ( m_bIgnoreCase ) ? stricmp( m_pStr, pStr ) > 0 : strcmp( m_pStr, pStr ) > 0; } -bool operator >( const char* pStr ) const { return ( m_bIgnoreCase ) ? stricmp( m_pStr, pStr ) > 0 : strcmp( m_pStr, pStr ) > 0; } -char& operator []( std::size_t nIndex ) { return m_pStr[nIndex]; } -const char& operator []( std::size_t nIndex ) const { return m_pStr[nIndex]; } -const char GetAt( std::size_t nIndex ) { return m_pStr[nIndex]; } -}; - - -template -inline TextOutputStreamType& ostream_write( TextOutputStreamType& ostream, const Str& str ){ - return ostream << str.GetBuffer(); -} - - -inline void AddSlash( Str& strPath ){ - if ( strPath.GetLength() > 0 ) { - if ( ( strPath.GetAt( strPath.GetLength() - 1 ) != '/' ) && - ( strPath.GetAt( strPath.GetLength() - 1 ) != '\\' ) ) { - strPath += '/'; - } - } -} - -inline bool ExtractPath_and_Filename( const char* pPath, Str& strPath, Str& strFilename ){ - Str strPathName; - strPathName = pPath; - const char* substr = strPathName.ReverseFind( '\\' ); - if ( substr == 0 ) { - // TTimo: try forward slash, some are using forward - substr = strPathName.ReverseFind( '/' ); - } - if ( substr != 0 ) { - std::size_t nSlash = substr - strPathName.GetBuffer(); - strPath = strPathName.Left( nSlash + 1 ); - strFilename = strPathName.Right( strPathName.GetLength() - nSlash - 1 ); - } - else{ - strFilename = pPath; - } - return true; -} - - - -#endif diff --git a/tools/urt/libs/stream/filestream.cpp b/tools/urt/libs/stream/filestream.cpp deleted file mode 100644 index e255a34..0000000 --- a/tools/urt/libs/stream/filestream.cpp +++ /dev/null @@ -1,2 +0,0 @@ - -#include "filestream.h" diff --git a/tools/urt/libs/stream/filestream.h b/tools/urt/libs/stream/filestream.h deleted file mode 100644 index b47dea8..0000000 --- a/tools/urt/libs/stream/filestream.h +++ /dev/null @@ -1,153 +0,0 @@ - -#if !defined( INCLUDED_STREAM_FILESTREAM_H ) -#define INCLUDED_STREAM_FILESTREAM_H - -#include "idatastream.h" -#include -#include - -namespace FileStreamDetail -{ -inline int whence_for_seekdir( SeekableStream::seekdir direction ){ - switch ( direction ) - { - case SeekableStream::cur: - return SEEK_CUR; - case SeekableStream::end: - return SEEK_END; - default: - break; - } - return SEEK_SET; -} -} - - -/// \brief A wrapper around a file input stream opened for reading in binary mode. Similar to std::ifstream. -/// -/// - Maintains a valid file handle associated with a name passed to the constructor. -/// - Implements SeekableInputStream. -class FileInputStream : public SeekableInputStream -{ -std::FILE* m_file; -public: -FileInputStream( const char* name ){ - m_file = name[0] == '\0' ? 0 : fopen( name, "rb" ); -} -~FileInputStream(){ - if ( !failed() ) { - fclose( m_file ); - } -} - -bool failed() const { - return m_file == 0; -} - -size_type read( byte_type* buffer, size_type length ){ - return fread( buffer, 1, length, m_file ); -} - -size_type seek( size_type position ){ - return fseek( m_file, static_cast( position ), SEEK_SET ); -} -size_type seek( offset_type offset, seekdir direction ){ - return fseek( m_file, offset, FileStreamDetail::whence_for_seekdir( direction ) ); -} -size_type tell() const { - return ftell( m_file ); -} - -std::FILE* file(){ - return m_file; -} -}; - -/// \brief A wrapper around a FileInputStream limiting access. -/// -/// - Maintains an input stream. -/// - Provides input starting at an offset in the file for a limited range. -class SubFileInputStream : public InputStream -{ -FileInputStream& m_istream; -size_type m_remaining; -public: -typedef FileInputStream::position_type position_type; - -SubFileInputStream( FileInputStream& istream, position_type offset, size_type size ) - : m_istream( istream ), m_remaining( size ){ - m_istream.seek( offset ); -} - -size_type read( byte_type* buffer, size_type length ){ - size_type result = m_istream.read( buffer, std::min( length, m_remaining ) ); - m_remaining -= result; - return result; -} -}; - - -/// \brief A wrapper around a stdc file stream opened for writing in binary mode. Similar to std::ofstream.. -/// -/// - Maintains a valid file handle associated with a name passed to the constructor. -/// - Implements SeekableInputStream. -class FileOutputStream : public SeekableOutputStream -{ -std::FILE* m_file; -public: -FileOutputStream( const char* name ){ - m_file = name[0] == '\0' ? 0 : fopen( name, "wb" ); -} -~FileOutputStream(){ - if ( !failed() ) { - fclose( m_file ); - } -} - -bool failed() const { - return m_file == 0; -} - -size_type write( const byte_type* buffer, size_type length ){ - return fwrite( buffer, 1, length, m_file ); -} - -size_type seek( size_type position ){ - return fseek( m_file, static_cast( position ), SEEK_SET ); -} -size_type seek( offset_type offset, seekdir direction ){ - return fseek( m_file, offset, FileStreamDetail::whence_for_seekdir( direction ) ); -} -size_type tell() const { - return ftell( m_file ); -} -}; - -inline bool file_copy( const char* source, const char* target ){ - const std::size_t buffer_size = 1024; - unsigned char buffer[buffer_size]; - - FileInputStream sourceFile( source ); - if ( sourceFile.failed() ) { - return false; - } - FileOutputStream targetFile( target ); - if ( targetFile.failed() ) { - return false; - } - - for (;; ) - { - std::size_t size = sourceFile.read( buffer, buffer_size ); - if ( size == 0 ) { - break; - } - if ( targetFile.write( buffer, size ) != size ) { - return false; - } - } - return true; -} - - -#endif diff --git a/tools/urt/libs/stream/memstream.cpp b/tools/urt/libs/stream/memstream.cpp deleted file mode 100644 index 096aaf1..0000000 --- a/tools/urt/libs/stream/memstream.cpp +++ /dev/null @@ -1,2 +0,0 @@ - -#include "memstream.h" diff --git a/tools/urt/libs/stream/memstream.h b/tools/urt/libs/stream/memstream.h deleted file mode 100644 index dfd13d0..0000000 --- a/tools/urt/libs/stream/memstream.h +++ /dev/null @@ -1,54 +0,0 @@ - -#if !defined( INCLUDED_STREAM_MEMSTREAM_H ) -#define INCLUDED_STREAM_MEMSTREAM_H - -#include "itextstream.h" -#include -#include - -class BufferOutputStream : public TextOutputStream -{ -std::vector m_buffer; -public: -std::size_t write( const char* buffer, std::size_t length ){ - m_buffer.insert( m_buffer.end(), buffer, buffer + length ); - return length; -} -const char* data() const { - return &( *m_buffer.begin() ); -} -std::size_t size() const { - return m_buffer.size(); -} -void clear(){ - std::vector empty; - std::swap( empty, m_buffer ); -} -}; - -template -inline BufferOutputStream& operator<<( BufferOutputStream& ostream, const T& t ){ - return ostream_write( ostream, t ); -} - - -class BufferInputStream : public TextInputStream -{ -const char* m_read; -const char* m_end; -public: -BufferInputStream( const char* buffer, std::size_t length ) - : m_read( buffer ), m_end( buffer + length ){ -} -std::size_t read( char* buffer, std::size_t length ){ - std::size_t count = std::min( std::size_t( m_end - m_read ), length ); - const char* end = m_read + count; - while ( m_read != end ) - { - *buffer++ = *m_read++; - } - return count; -} -}; - -#endif diff --git a/tools/urt/libs/stream/stringstream.cpp b/tools/urt/libs/stream/stringstream.cpp deleted file mode 100644 index 9805a12..0000000 --- a/tools/urt/libs/stream/stringstream.cpp +++ /dev/null @@ -1,2 +0,0 @@ - -#include "stringstream.h" diff --git a/tools/urt/libs/stream/stringstream.h b/tools/urt/libs/stream/stringstream.h deleted file mode 100644 index 775dfde..0000000 --- a/tools/urt/libs/stream/stringstream.h +++ /dev/null @@ -1,128 +0,0 @@ - -#if !defined( INCLUDED_STREAM_STRINGSTREAM_H ) -#define INCLUDED_STREAM_STRINGSTREAM_H - -#include "itextstream.h" -#include "string/string.h" -#include - - -/// \brief A wrapper around a STL vector of char. -/// Maintains a null-terminated array of char. -/// Provides a limited STL-style interface to push and pop characters at the end of the string. -class StringBuffer -{ -std::vector m_string; -public: -StringBuffer(){ - m_string.push_back( '\0' ); -} -explicit StringBuffer( std::size_t capacity ){ - m_string.reserve( capacity ); - m_string.push_back( '\0' ); -} -explicit StringBuffer( const char* string ) : m_string( string, string + string_length( string ) + 1 ){ -} - -typedef std::vector::iterator iterator; -typedef std::vector::const_iterator const_iterator; - -iterator begin(){ - return m_string.begin(); -} -const_iterator begin() const { - return m_string.begin(); -} -iterator end(){ - return m_string.end() - 1; -} -const_iterator end() const { - return m_string.end() - 1; -} - -void push_back( char c ){ - m_string.insert( end(), c ); -} -void pop_back(){ - m_string.erase( end() - 1 ); -} -void push_range( const char* first, const char* last ){ - m_string.insert( end(), first, last ); -} -void push_string( const char* string ){ - push_range( string, string + string_length( string ) ); -} -char* c_str(){ - return &( *m_string.begin() ); -} -const char* c_str() const { - return &( *m_string.begin() ); -} - -char& back(){ - return *( end() - 1 ); -} -const char& back() const { - return *( end() - 1 ); -} -bool empty() const { - return m_string.size() == 1; -} -void clear(){ - m_string.clear(); - m_string.push_back( '\0' ); -} -}; - -/// \brief A TextOutputStream which writes to a StringBuffer. -/// Similar to std::stringstream. -class StringOutputStream : public TextOutputStream -{ -StringBuffer m_string; -public: -typedef StringBuffer::iterator iterator; -typedef StringBuffer::const_iterator const_iterator; - -StringOutputStream(){ -} -StringOutputStream( std::size_t capacity ) : m_string( capacity ){ -} -std::size_t write( const char* buffer, std::size_t length ){ - m_string.push_range( buffer, buffer + length ); - return length; -} - -iterator begin(){ - return m_string.begin(); -} -const_iterator begin() const { - return m_string.begin(); -} -iterator end(){ - return m_string.end(); -} -const_iterator end() const { - return m_string.end(); -} - -bool empty() const { - return m_string.empty(); -} -char* c_str(){ - return m_string.c_str(); -} -const char* c_str() const { - return m_string.c_str(); -} -void clear(){ - m_string.clear(); -} -}; - -template -inline StringOutputStream& operator<<( StringOutputStream& ostream, const T& t ){ - return ostream_write( ostream, t ); -} - - -#endif diff --git a/tools/urt/libs/stream/textfilestream.cpp b/tools/urt/libs/stream/textfilestream.cpp deleted file mode 100644 index 4d9d9c4..0000000 --- a/tools/urt/libs/stream/textfilestream.cpp +++ /dev/null @@ -1,2 +0,0 @@ - -#include "textfilestream.h" diff --git a/tools/urt/libs/stream/textfilestream.h b/tools/urt/libs/stream/textfilestream.h deleted file mode 100644 index b216c54..0000000 --- a/tools/urt/libs/stream/textfilestream.h +++ /dev/null @@ -1,60 +0,0 @@ - -#if !defined( INCLUDED_STREAM_TEXTFILESTREAM_H ) -#define INCLUDED_STREAM_TEXTFILESTREAM_H - -#include "itextstream.h" -#include - -/// \brief A wrapper around a file input stream opened for reading in text mode. Similar to std::ifstream. -class TextFileInputStream : public TextInputStream -{ -FILE* m_file; -public: -TextFileInputStream( const char* name ){ - m_file = name[0] == '\0' ? 0 : fopen( name, "rt" ); -} -~TextFileInputStream(){ - if ( !failed() ) { - fclose( m_file ); - } -} - -bool failed() const { - return m_file == 0; -} - -std::size_t read( char* buffer, std::size_t length ){ - return fread( buffer, 1, length, m_file ); -} -}; - -/// \brief A wrapper around a file input stream opened for writing in text mode. Similar to std::ofstream. -class TextFileOutputStream : public TextOutputStream -{ -FILE* m_file; -public: -TextFileOutputStream( const char* name ){ - m_file = name[0] == '\0' ? 0 : fopen( name, "wt" ); -} -~TextFileOutputStream(){ - if ( !failed() ) { - fclose( m_file ); - } -} - -bool failed() const { - return m_file == 0; -} - -std::size_t write( const char* buffer, std::size_t length ){ - return fwrite( buffer, 1, length, m_file ); -} -}; - -template -inline TextFileOutputStream& operator<<( TextFileOutputStream& ostream, const T& t ){ - return ostream_write( ostream, t ); -} - - -#endif diff --git a/tools/urt/libs/stream/textstream.cpp b/tools/urt/libs/stream/textstream.cpp deleted file mode 100644 index 521574c..0000000 --- a/tools/urt/libs/stream/textstream.cpp +++ /dev/null @@ -1,2 +0,0 @@ - -#include "textstream.h" diff --git a/tools/urt/libs/stream/textstream.h b/tools/urt/libs/stream/textstream.h deleted file mode 100644 index 084e0f5..0000000 --- a/tools/urt/libs/stream/textstream.h +++ /dev/null @@ -1,333 +0,0 @@ - -#if !defined( INCLUDED_STREAM_TEXTSTREAM_H ) -#define INCLUDED_STREAM_TEXTSTREAM_H - -/// \file -/// \brief Text-output-formatting. - -#include "itextstream.h" - -#include -#include -#include -#include -#include - -#include "generic/arrayrange.h" - -namespace TextOutputDetail -{ -inline char* write_unsigned_nonzero_decimal_backward( char* ptr, unsigned int decimal ){ - for (; decimal != 0; decimal /= 10 ) - { - *--ptr = char('0' + int(decimal % 10) ); - } - return ptr; -} - -inline char* write_signed_nonzero_decimal_backward( char* ptr, int decimal, bool show_positive ){ - const bool negative = decimal < 0 ; - ptr = write_unsigned_nonzero_decimal_backward( ptr, negative ? -decimal : decimal ); - if ( negative ) { - *--ptr = '-'; - } - else if ( show_positive ) { - *--ptr = '+'; - } - return ptr; -} - -inline char* write_unsigned_nonzero_decimal_backward( char* ptr, unsigned int decimal, bool show_positive ){ - ptr = write_unsigned_nonzero_decimal_backward( ptr, decimal ); - if ( show_positive ) { - *--ptr = '+'; - } - return ptr; -} - -inline char* write_signed_decimal_backward( char* ptr, int decimal, bool show_positive ){ - if ( decimal == 0 ) { - *--ptr = '0'; - } - else - { - ptr = write_signed_nonzero_decimal_backward( ptr, decimal, show_positive ); - } - return ptr; -} - -inline char* write_unsigned_decimal_backward( char* ptr, unsigned int decimal, bool show_positive ){ - if ( decimal == 0 ) { - *--ptr = '0'; - } - else - { - ptr = write_unsigned_nonzero_decimal_backward( ptr, decimal, show_positive ); - } - return ptr; -} -} - - -#ifdef WIN32 -#define snprintf _snprintf -#endif - -/// \brief Writes a single character \p c to \p ostream. -template -inline TextOutputStreamType& ostream_write( TextOutputStreamType& ostream, char c ){ - ostream.write( &c, 1 ); - return ostream; -} - -/// \brief Writes a double-precision floating point value \p d to \p ostream. -/// The value will be formatted either as decimal with trailing zeros removed, or with scientific 'e' notation, whichever is shorter. -template -inline TextOutputStreamType& ostream_write( TextOutputStreamType& ostream, const double d ){ - const std::size_t bufferSize = 16; - char buf[bufferSize]; - ostream.write( buf, snprintf( buf, bufferSize, "%g", d ) ); - return ostream; -} - -/// \brief Writes a single-precision floating point value \p f to \p ostream. -/// The value will be formatted either as decimal with trailing zeros removed, or with scientific 'e' notation, whichever is shorter. -template -inline TextOutputStreamType& ostream_write( TextOutputStreamType& ostream, const float f ){ - return ostream_write( ostream, static_cast( f ) ); -} - -/// \brief Writes a signed integer \p i to \p ostream in decimal form. -/// A '-' sign will be added if the value is negative. -template -inline TextOutputStreamType& ostream_write( TextOutputStreamType& ostream, const int i ){ - const std::size_t bufferSize = 16; -#if 1 - char buf[bufferSize]; - char* begin = TextOutputDetail::write_signed_decimal_backward( buf + bufferSize, i, false ); - ostream.write( begin, ( buf + bufferSize ) - begin ); -#else - char buf[bufferSize]; - ostream.write( buf, snprintf( buf, bufferSize, "%i", i ) ); -#endif - return ostream; -} - -typedef unsigned int Unsigned; - -/// \brief Writes an unsigned integer \p i to \p ostream in decimal form. -template -inline TextOutputStreamType& ostream_write( TextOutputStreamType& ostream, const Unsigned i ){ - const std::size_t bufferSize = 16; -#if 1 - char buf[bufferSize]; - char* begin = TextOutputDetail::write_unsigned_decimal_backward( buf + bufferSize, i, false ); - ostream.write( begin, ( buf + bufferSize ) - begin ); -#else - char buf[bufferSize]; - ostream.write( buf, snprintf( buf, bufferSize, "%u", i ) ); -#endif - return ostream; -} - -/// \brief Writes a null-terminated \p string to \p ostream. -template -inline TextOutputStreamType& ostream_write( TextOutputStreamType& ostream, const char* string ){ - ostream.write( string, strlen( string ) ); - return ostream; -} - -class HexChar -{ -public: -char m_value; -HexChar( char value ) : m_value( value ){ -} -}; - -/// \brief Writes a single character \p c to \p ostream in hexadecimal form. -template -inline TextOutputStreamType& ostream_write( TextOutputStreamType& ostream, const HexChar& c ){ - const std::size_t bufferSize = 16; - char buf[bufferSize]; - ostream.write( buf, snprintf( buf, bufferSize, "%X", c.m_value & 0xFF ) ); - return ostream; -} - -template -class LeftJustified -{ -public: -const T& m_t; -std::size_t m_size; -LeftJustified( const T& t, std::size_t size ) : m_t( t ), m_size( size ){ -} -}; - -template -LeftJustified makeLeftJustified( const T& t, std::size_t size ){ - return LeftJustified( t, size ); -} - -template -class CountingOutputStream -{ -TextOutputStreamType& m_ostream; -public: -std::size_t m_count; -CountingOutputStream( TextOutputStreamType& ostream ) : m_ostream( ostream ){ -} -std::size_t write( const char* buffer, std::size_t length ){ - m_count += length; - return m_ostream.write( buffer, length ); -} -}; - -template -inline CountingOutputStream& operator<<( CountingOutputStream& ostream, const T& t ){ - return ostream_write( ostream, t ); -} - - -/// \brief Writes any type to \p ostream padded with spaces afterwards. -template -inline TextOutputStreamType& ostream_write( TextOutputStreamType& ostream, const LeftJustified& justified ){ - CountingOutputStream count( ostream ); - count << justified.m_t; - while ( justified.m_size > count.m_count ) - { - count << ' '; - } - return ostream; -} - -class FloatFormat -{ -public: -double m_f; -int m_width; -int m_precision; -FloatFormat( double f, int width, int precision ) - : m_f( f ), m_width( width ), m_precision( precision ){ -} -}; - -/// \brief Writes a floating point value to \p ostream with a specific width and precision. -template -inline TextOutputStreamType& ostream_write( TextOutputStreamType& ostream, const FloatFormat& formatted ){ - const std::size_t bufferSize = 32; - char buf[bufferSize]; - ostream.write( buf, snprintf( buf, bufferSize, "%*.*lf", formatted.m_width, formatted.m_precision, formatted.m_f ) ); - return ostream; -} - -// never displays exponent, prints up to 10 decimal places -class Decimal -{ -public: -double m_f; -Decimal( double f ) : m_f( f ){ -} -}; - -/// \brief Writes a floating point value to \p ostream in decimal form with trailing zeros removed. -template -inline TextOutputStreamType& ostream_write( TextOutputStreamType& ostream, const Decimal& decimal ){ - const int bufferSize = 22; - char buf[bufferSize]; - std::size_t length = snprintf( buf, bufferSize, "%10.10lf", decimal.m_f ); - const char* first = buf; - for (; *first == ' '; ++first ) - { - } - const char* last = buf + length - 1; - for (; *last == '0'; --last ) - { - } - if ( *last == '.' ) { - --last; - } - ostream.write( first, last - first + 1 ); - return ostream; -} - - -typedef ArrayRange StringRange; - -/// \brief Writes a \p range of characters to \p ostream. -template -inline TextOutputStreamType& ostream_write( TextOutputStreamType& ostream, const StringRange& range ){ - ostream.write( range.begin, range.end - range.begin ); - return ostream; -} - -template -class Quoted -{ -public: -const Type& m_type; -Quoted( const Type& type ) - : m_type( type ){ -} -}; - -template -inline Quoted makeQuoted( const Type& type ){ - return Quoted( type ); -} - -/// \brief Writes any type to \p ostream with a quotation mark character before and after it. -template -inline TextOutputStreamType& ostream_write( TextOutputStreamType& ostream, const Quoted& quoted ){ - return ostream << '"' << quoted.m_type << '"'; -} - - -class LowerCase -{ -public: -const char* m_string; -LowerCase( const char* string ) : m_string( string ){ -} -}; - -/// \brief Writes a string to \p ostream converted to lower-case. -template -inline TextOutputStreamType& ostream_write( TextOutputStreamType& ostream, const LowerCase& lower ){ - for ( const char* p = lower.m_string; *p != '\0'; ++p ) - { - ostream << static_cast( std::tolower( *p ) ); - } - return ostream; -} - - -/// \brief A wrapper for a TextInputStream optimised for reading a single character at a time. -template -class SingleCharacterInputStream -{ -TextInputStreamType& m_inputStream; -char m_buffer[SIZE]; -char* m_cur; -char* m_end; - -bool fillBuffer(){ - m_end = m_buffer + m_inputStream.read( m_buffer, SIZE ); - m_cur = m_buffer; - return m_cur != m_end; -} -public: - -SingleCharacterInputStream( TextInputStreamType& inputStream ) : m_inputStream( inputStream ), m_cur( m_buffer ), m_end( m_buffer ){ -} -bool readChar( char& c ){ - if ( m_cur == m_end && !fillBuffer() ) { - return false; - } - - c = *m_cur++; - return true; -} -}; - -#endif diff --git a/tools/urt/libs/string/string.cpp b/tools/urt/libs/string/string.cpp deleted file mode 100644 index b9a6b56..0000000 --- a/tools/urt/libs/string/string.cpp +++ /dev/null @@ -1,7 +0,0 @@ - -#include "string.h" - -void TestString(){ - CopiedString bleh( "bleh" ); - SmartString blah( "blah" ); -} \ No newline at end of file diff --git a/tools/urt/libs/string/string.h b/tools/urt/libs/string/string.h deleted file mode 100644 index f518926..0000000 --- a/tools/urt/libs/string/string.h +++ /dev/null @@ -1,505 +0,0 @@ - -#if !defined( INCLUDED_STRING_STRING_H ) -#define INCLUDED_STRING_STRING_H - -/// \file -/// C-style null-terminated-character-array string library. - -#include -#include -#include - -#include "memory/allocator.h" - -/// \brief Returns true if \p string length is zero. -/// O(1) -inline bool string_empty( const char* string ){ - return *string == '\0'; -} - -/// \brief Returns true if \p string length is not zero. -/// O(1) -inline bool string_not_empty( const char* string ){ - return !string_empty( string ); -} - -/// \brief Returns <0 if \p string is lexicographically less than \p other. -/// Returns >0 if \p string is lexicographically greater than \p other. -/// Returns 0 if \p string is lexicographically equal to \p other. -/// O(n) -inline int string_compare( const char* string, const char* other ){ - return std::strcmp( string, other ); -} - -/// \brief Returns true if \p string is lexicographically equal to \p other. -/// O(n) -inline bool string_equal( const char* string, const char* other ){ - return string_compare( string, other ) == 0; -} - -/// \brief Returns true if [\p string, \p string + \p n) is lexicographically equal to [\p other, \p other + \p n). -/// O(n) -inline bool string_equal_n( const char* string, const char* other, std::size_t n ){ - return std::strncmp( string, other, n ) == 0; -} - -/// \brief Returns true if \p string is lexicographically less than \p other. -/// O(n) -inline bool string_less( const char* string, const char* other ){ - return string_compare( string, other ) < 0; -} - -/// \brief Returns true if \p string is lexicographically greater than \p other. -/// O(n) -inline bool string_greater( const char* string, const char* other ){ - return string_compare( string, other ) > 0; -} - -/// \brief Returns <0 if \p string is lexicographically less than \p other after converting both to lower-case. -/// Returns >0 if \p string is lexicographically greater than \p other after converting both to lower-case. -/// Returns 0 if \p string is lexicographically equal to \p other after converting both to lower-case. -/// O(n) -inline int string_compare_nocase( const char* string, const char* other ){ -#ifdef WIN32 - return _stricmp( string, other ); -#else - return strcasecmp( string, other ); -#endif -} - -/// \brief Returns <0 if [\p string, \p string + \p n) is lexicographically less than [\p other, \p other + \p n). -/// Returns >0 if [\p string, \p string + \p n) is lexicographically greater than [\p other, \p other + \p n). -/// Returns 0 if [\p string, \p string + \p n) is lexicographically equal to [\p other, \p other + \p n). -/// Treats all ascii characters as lower-case during comparisons. -/// O(n) -inline int string_compare_nocase_n( const char* string, const char* other, std::size_t n ){ -#ifdef WIN32 - return _strnicmp( string, other, n ); -#else - return strncasecmp( string, other, n ); -#endif -} - -/// \brief Returns true if \p string is lexicographically equal to \p other. -/// Treats all ascii characters as lower-case during comparisons. -/// O(n) -inline bool string_equal_nocase( const char* string, const char* other ){ - return string_compare_nocase( string, other ) == 0; -} - -/// \brief Returns true if [\p string, \p string + \p n) is lexicographically equal to [\p other, \p other + \p n). -/// Treats all ascii characters as lower-case during comparisons. -/// O(n) -inline bool string_equal_nocase_n( const char* string, const char* other, std::size_t n ){ - return string_compare_nocase_n( string, other, n ) == 0; -} - -/// \brief Returns true if \p string is lexicographically less than \p other. -/// Treats all ascii characters as lower-case during comparisons. -/// O(n) -inline bool string_less_nocase( const char* string, const char* other ){ - return string_compare_nocase( string, other ) < 0; -} - -/// \brief Returns true if \p string is lexicographically greater than \p other. -/// Treats all ascii characters as lower-case during comparisons. -/// O(n) -inline bool string_greater_nocase( const char* string, const char* other ){ - return string_compare_nocase( string, other ) > 0; -} - -/// \brief Returns the number of non-null characters in \p string. -/// O(n) -inline std::size_t string_length( const char* string ){ - return std::strlen( string ); -} - -/// \brief Returns true if the beginning of \p string is equal to \p prefix. -/// O(n) -inline bool string_equal_prefix( const char* string, const char* prefix ){ - return string_equal_n( string, prefix, string_length( prefix ) ); -} - -/// \brief Copies \p other into \p string and returns \p string. -/// Assumes that the space allocated for \p string is at least string_length(other) + 1. -/// O(n) -inline char* string_copy( char* string, const char* other ){ - return std::strcpy( string, other ); -} - -/// \brief Allocates a string buffer large enough to hold \p length characters, using \p allocator. -/// The returned buffer must be released with \c string_release using a matching \p allocator. -template -inline char* string_new( std::size_t length, Allocator& allocator ){ - return allocator.allocate( length + 1 ); -} - -/// \brief Deallocates the \p buffer large enough to hold \p length characters, using \p allocator. -template -inline void string_release( char* buffer, std::size_t length, Allocator& allocator ){ - allocator.deallocate( buffer, length + 1 ); -} - -/// \brief Returns a newly-allocated string which is a clone of \p other, using \p allocator. -/// The returned buffer must be released with \c string_release using a matching \p allocator. -template -inline char* string_clone( const char* other, Allocator& allocator ){ - char* copied = string_new( string_length( other ), allocator ); - std::strcpy( copied, other ); - return copied; -} - -/// \brief Returns a newly-allocated string which is a clone of [\p first, \p last), using \p allocator. -/// The returned buffer must be released with \c string_release using a matching \p allocator. -template -inline char* string_clone_range( const char* first, const char* last, Allocator& allocator ){ - std::size_t length = last - first; - char* copied = strncpy( string_new( length, allocator ), first, length ); - copied[length] = '\0'; - return copied; -} - -/// \brief Allocates a string buffer large enough to hold \p length characters. -/// The returned buffer must be released with \c string_release. -inline char* string_new( std::size_t length ){ - DefaultAllocator allocator; - return string_new( length, allocator ); -} - -/// \brief Deallocates the \p buffer large enough to hold \p length characters. -inline void string_release( char* string, std::size_t length ){ - DefaultAllocator allocator; - string_release( string, length, allocator ); -} - -/// \brief Returns a newly-allocated string which is a clone of \p other. -/// The returned buffer must be released with \c string_release. -inline char* string_clone( const char* other ){ - DefaultAllocator allocator; - return string_clone( other, allocator ); -} - -/// \brief Returns a newly-allocated string which is a clone of [\p first, \p last). -/// The returned buffer must be released with \c string_release. -inline char* string_clone_range( const char* first, const char* last ){ - DefaultAllocator allocator; - return string_clone_range( first, last, allocator ); -} - -typedef char* char_pointer; -/// \brief Swaps the values of \p string and \p other. -inline void string_swap( char_pointer& string, char_pointer& other ){ - std::swap( string, other ); -} - -typedef const char* char_const_pointer; -/// \brief Swaps the values of \p string and \p other. -inline void string_swap( char_const_pointer& string, char_const_pointer& other ){ - std::swap( string, other ); -} - -/// \brief Converts each character of \p string to lower-case and returns \p string. -/// O(n) -inline char* string_to_lowercase( char* string ){ - for ( char* p = string; *p != '\0'; ++p ) - { - *p = std::tolower( *p ); - } - return string; -} - -/// \brief Converts each character of \p string to upper-case and returns \p string. -/// O(n) -inline char* string_to_uppercase( char* string ){ - for ( char* p = string; *p != '\0'; ++p ) - { - *p = std::toupper( *p ); - } - return string; -} - -/// \brief A re-entrant string tokeniser similar to strchr. -class StringTokeniser -{ -bool istoken( char c ) const { - if ( strchr( m_delimiters, c ) != 0 ) { - return false; - } - return true; -} -const char* advance(){ - const char* token = m_pos; - bool intoken = true; - while ( !string_empty( m_pos ) ) - { - if ( !istoken( *m_pos ) ) { - *m_pos = '\0'; - intoken = false; - } - else if ( !intoken ) { - return token; - } - ++m_pos; - } - return token; -} -std::size_t m_length; -char* m_string; -char* m_pos; -const char* m_delimiters; -public: -StringTokeniser( const char* string, const char* delimiters = " \n\r\t\v" ) : - m_length( string_length( string ) ), - m_string( string_copy( string_new( m_length ), string ) ), - m_pos( m_string ), - m_delimiters( delimiters ){ - while ( !string_empty( m_pos ) && !istoken( *m_pos ) ) - { - ++m_pos; - } -} -~StringTokeniser(){ - string_release( m_string, m_length ); -} -/// \brief Returns the next token or "" if there are no more tokens available. -const char* getToken(){ - return advance(); -} -}; - -/// \brief A non-mutable c-style string. -/// -/// \param Buffer The string storage implementation. Must be DefaultConstructible, CopyConstructible and Assignable. Must implement: -/// \li Buffer(const char* string) - constructor which copies a c-style \p string. -/// \li Buffer(const char* first, const char*) - constructor which copies a c-style string range [\p first, \p last). -/// \li void swap(Buffer& other) - swaps contents with \p other. -/// \li const char* c_str() - returns the stored non-mutable c-style string. -template -class String : public Buffer -{ -public: - -String() - : Buffer(){ -} -String( const char* string ) - : Buffer( string ){ -} -String( const char* first, const char* last ) - : Buffer( first, last ){ -} - -String& operator=( const String& other ){ - String temp( other ); - temp.swap( *this ); - return *this; -} -String& operator=( const char* string ){ - String temp( string ); - temp.swap( *this ); - return *this; -} - -void swap( String& other ){ - Buffer::swap( other ); -} - -bool empty() const { - return string_empty( Buffer::c_str() ); -} -}; - -template -inline bool operator<( const String& self, const String& other ){ - return string_less( self.c_str(), other.c_str() ); -} - -template -inline bool operator>( const String& self, const String& other ){ - return string_greater( self.c_str(), other.c_str() ); -} - -template -inline bool operator==( const String& self, const String& other ){ - return string_equal( self.c_str(), other.c_str() ); -} - -template -inline bool operator!=( const String& self, const String& other ){ - return !string_equal( self.c_str(), other.c_str() ); -} - -template -inline bool operator==( const String& self, const char* other ){ - return string_equal( self.c_str(), other ); -} - -template -inline bool operator!=( const String& self, const char* other ){ - return !string_equal( self.c_str(), other ); -} - -namespace std -{ -/// \brief Swaps the values of \p self and \p other. -/// Overloads std::swap. -template -inline void swap( String& self, String& other ){ - self.swap( other ); -} -} - - -/// \brief A non-mutable string buffer which manages memory allocation. -template -class CopiedBuffer : private Allocator -{ -char* m_string; - -char* copy_range( const char* first, const char* last ){ - return string_clone_range( first, last, static_cast( *this ) ); -} -char* copy( const char* other ){ - return string_clone( other, static_cast( *this ) ); -} -void destroy( char* string ){ - string_release( string, string_length( string ), static_cast( *this ) ); -} - -protected: -~CopiedBuffer(){ - destroy( m_string ); -} -public: -CopiedBuffer() - : m_string( copy( "" ) ){ -} -explicit CopiedBuffer( const Allocator& allocator ) - : Allocator( allocator ), m_string( copy( "" ) ){ -} -CopiedBuffer( const CopiedBuffer& other ) - : Allocator( other ), m_string( copy( other.m_string ) ){ -} -CopiedBuffer( const char* string, const Allocator& allocator = Allocator() ) - : Allocator( allocator ), m_string( copy( string ) ){ -} -CopiedBuffer( const char* first, const char* last, const Allocator& allocator = Allocator() ) - : Allocator( allocator ), m_string( copy_range( first, last ) ){ -} -const char* c_str() const { - return m_string; -} -void swap( CopiedBuffer& other ){ - string_swap( m_string, other.m_string ); -} -}; - -/// \brief A non-mutable string which uses copy-by-value for assignment. -typedef String< CopiedBuffer< DefaultAllocator > > CopiedString; - - -/// \brief A non-mutable string buffer which uses reference-counting to avoid unnecessary allocations. -template -class SmartBuffer : private Allocator -{ -char* m_buffer; - -char* copy_range( const char* first, const char* last ){ - char* buffer = Allocator::allocate( sizeof( std::size_t ) + ( last - first ) + 1 ); - strncpy( buffer + sizeof( std::size_t ), first, last - first ); - buffer[sizeof( std::size_t ) + ( last - first )] = '\0'; - *reinterpret_cast( buffer ) = 0; - return buffer; -} -char* copy( const char* string ){ - char* buffer = Allocator::allocate( sizeof( std::size_t ) + string_length( string ) + 1 ); - strcpy( buffer + sizeof( std::size_t ), string ); - *reinterpret_cast( buffer ) = 0; - return buffer; -} -void destroy( char* buffer ){ - Allocator::deallocate( buffer, sizeof( std::size_t ) + string_length( c_str() ) + 1 ); -} - -void incref( char* buffer ){ - ++( *reinterpret_cast( buffer ) ); -} -void decref( char* buffer ){ - if ( --( *reinterpret_cast( buffer ) ) == 0 ) { - destroy( buffer ); - } -} - -protected: -~SmartBuffer(){ - decref( m_buffer ); -} -public: -SmartBuffer() - : m_buffer( copy( "" ) ){ - incref( m_buffer ); -} -explicit SmartBuffer( const Allocator& allocator ) - : Allocator( allocator ), m_buffer( copy( "" ) ){ - incref( m_buffer ); -} -SmartBuffer( const SmartBuffer& other ) - : Allocator( other ), m_buffer( other.m_buffer ){ - incref( m_buffer ); -} -SmartBuffer( const char* string, const Allocator& allocator = Allocator() ) - : Allocator( allocator ), m_buffer( copy( string ) ){ - incref( m_buffer ); -} -SmartBuffer( const char* first, const char* last, const Allocator& allocator = Allocator() ) - : Allocator( allocator ), m_buffer( copy_range( first, last ) ){ - incref( m_buffer ); -} -const char* c_str() const { - return m_buffer + sizeof( std::size_t ); -} -void swap( SmartBuffer& other ){ - string_swap( m_buffer, other.m_buffer ); -} -}; - -/// \brief A non-mutable string which uses copy-by-reference for assignment of SmartString. -typedef String< SmartBuffer< DefaultAllocator > > SmartString; - -class StringEqualNoCase -{ -public: -bool operator()( const CopiedString& key, const CopiedString& other ) const { - return string_equal_nocase( key.c_str(), other.c_str() ); -} -}; - -struct StringLessNoCase -{ - bool operator()( const CopiedString& x, const CopiedString& y ) const { - return string_less_nocase( x.c_str(), y.c_str() ); - } -}; - -struct RawStringEqual -{ - bool operator()( const char* x, const char* y ) const { - return string_equal( x, y ); - } -}; - -struct RawStringLess -{ - bool operator()( const char* x, const char* y ) const { - return string_less( x, y ); - } -}; - -struct RawStringLessNoCase -{ - bool operator()( const char* x, const char* y ) const { - return string_less_nocase( x, y ); - } -}; - -#endif diff --git a/tools/urt/libs/string/stringfwd.cpp b/tools/urt/libs/string/stringfwd.cpp deleted file mode 100644 index f7ce7c2..0000000 --- a/tools/urt/libs/string/stringfwd.cpp +++ /dev/null @@ -1,2 +0,0 @@ - -#include "stringfwd.h" diff --git a/tools/urt/libs/string/stringfwd.h b/tools/urt/libs/string/stringfwd.h deleted file mode 100644 index 8e820f8..0000000 --- a/tools/urt/libs/string/stringfwd.h +++ /dev/null @@ -1,15 +0,0 @@ - -#if !defined( INCLUDED_STRING_STRINGFWD_H ) -#define INCLUDED_STRING_STRINGFWD_H - -// forward-declaration of CopiedString - -template -class DefaultAllocator; -template -class CopiedBuffer; -template -class String; -typedef String< CopiedBuffer< DefaultAllocator > > CopiedString; - -#endif diff --git a/tools/urt/libs/stringio.cpp b/tools/urt/libs/stringio.cpp deleted file mode 100644 index c966d54..0000000 --- a/tools/urt/libs/stringio.cpp +++ /dev/null @@ -1,2 +0,0 @@ - -#include "stringio.h" diff --git a/tools/urt/libs/stringio.h b/tools/urt/libs/stringio.h deleted file mode 100644 index b46a9fe..0000000 --- a/tools/urt/libs/stringio.h +++ /dev/null @@ -1,393 +0,0 @@ - -#if !defined ( INCLUDED_STRINGIO_H ) -#define INCLUDED_STRINGIO_H - -#include -#include - -#include "math/vector.h" -#include "iscriplib.h" -#include "string/string.h" -#include "stream/textstream.h" -#include "generic/callback.h" - -inline float string_read_float( const char* string ){ - return static_cast( atof( string ) ); -} - -inline int string_read_int( const char* string ){ - return atoi( string ); -} - -inline bool char_is_whitespace( char c ){ - return c == ' ' || c == '\t'; -} - -inline const char* string_remove_whitespace( const char* string ){ - for (;; ) - { - if ( !char_is_whitespace( *string ) ) { - break; - } - ++string; - } - return string; -} - -inline const char* string_remove_zeros( const char* string ){ - for (;; ) - { - char c = *string; - if ( c != '0' ) { - break; - } - ++string; - } - return string; -} - -inline const char* string_remove_sign( const char* string ){ - if ( *string == '-' || *string == '+' ) { // signed zero - acceptable - return ++string; - } - return string; -} - -inline bool string_is_unsigned_zero( const char* string ){ - for (; *string != '\0'; ++string ) - { - if ( *string != '0' ) { - return false; - } - } - return true; -} - -inline bool string_is_signed_zero( const char* string ){ - return string_is_unsigned_zero( string_remove_sign( string ) ); -} - -//[whitespaces][+|-][nnnnn][.nnnnn][e|E[+|-]nnnn] -//(where whitespaces are any tab or space character and nnnnn may be any number of digits) -inline bool string_is_float_zero( const char* string ){ - string = string_remove_whitespace( string ); - if ( string_empty( string ) ) { - return false; - } - - string = string_remove_sign( string ); - if ( string_empty( string ) ) { - // no whole number or fraction part - return false; - } - - // whole-number part - string = string_remove_zeros( string ); - if ( string_empty( string ) ) { - // no fraction or exponent - return true; - } - if ( *string == '.' ) { - // fraction part - if ( *string++ != '0' ) { - // invalid fraction - return false; - } - string = string_remove_zeros( ++string ); - if ( string_empty( string ) ) { - // no exponent - return true; - } - } - if ( *string == 'e' || *string == 'E' ) { - // exponent part - string = string_remove_sign( ++string ); - if ( *string++ != '0' ) { - // invalid exponent - return false; - } - string = string_remove_zeros( ++string ); - if ( string_empty( string ) ) { - // no trailing whitespace - return true; - } - } - string = string_remove_whitespace( string ); - return string_empty( string ); -} - -inline double buffer_parse_floating_literal( const char*& buffer ){ - return strtod( buffer, const_cast( &buffer ) ); -} - -inline int buffer_parse_signed_decimal_integer_literal( const char*& buffer ){ - return strtol( buffer, const_cast( &buffer ), 10 ); -} - -inline int buffer_parse_unsigned_decimal_integer_literal( const char*& buffer ){ - return strtoul( buffer, const_cast( &buffer ), 10 ); -} - -// [+|-][nnnnn][.nnnnn][e|E[+|-]nnnnn] -inline bool string_parse_float( const char* string, float& f ){ - if ( string_empty( string ) ) { - return false; - } - f = buffer_parse_floating_literal( string ); - return string_empty( string ); -} - -// format same as float -inline bool string_parse_double( const char* string, double& f ){ - if ( string_empty( string ) ) { - return false; - } - f = buffer_parse_floating_literal( string ); - return string_empty( string ); -} - -// -inline bool string_parse_vector( const char* string, Vector3& v ){ - if ( string_empty( string ) ) { - return false; - } - v[0] = buffer_parse_floating_literal( string ); - if ( *string++ != ' ' ) { - return false; - } - v[1] = buffer_parse_floating_literal( string ); - if ( *string++ != ' ' ) { - return false; - } - v[2] = buffer_parse_floating_literal( string ); - return string_empty( string ); -} - -// decimal signed integer -inline bool string_parse_int( const char* string, int& i ){ - if ( string_empty( string ) ) { - return false; - } - i = buffer_parse_signed_decimal_integer_literal( string ); - return string_empty( string ); -} - -// decimal unsigned integer -inline bool string_parse_size( const char* string, std::size_t& i ){ - if ( string_empty( string ) ) { - return false; - } - i = buffer_parse_unsigned_decimal_integer_literal( string ); - return string_empty( string ); -} - - - -inline bool Tokeniser_getFloat( Tokeniser& tokeniser, float& f ){ - return string_parse_float( tokeniser.getToken(), f ); -} - -inline bool Tokeniser_getDouble( Tokeniser& tokeniser, double& f ){ - return string_parse_double( tokeniser.getToken(), f ); -} - -inline bool Tokeniser_getInteger( Tokeniser& tokeniser, int& i ){ - return string_parse_int( tokeniser.getToken(), i ); -} - -inline bool Tokeniser_getSize( Tokeniser& tokeniser, std::size_t& i ){ - return string_parse_size( tokeniser.getToken(), i ); -} - -inline bool Tokeniser_nextTokenIsDigit( Tokeniser& tokeniser ){ - char c = tokeniser.getToken()[0]; - tokeniser.ungetToken(); - return std::isdigit( c ) != 0; -} - -template -inline TextOutputStreamType& ostream_write( TextOutputStreamType& outputStream, const Vector3& v ){ - return outputStream << '(' << v.x() << ' ' << v.y() << ' ' << v.z() << ')'; -} - - - - -inline void CopiedString_importString( CopiedString& self, const char* string ){ - self = string; -} -typedef ReferenceCaller1 CopiedStringImportStringCaller; -inline void CopiedString_exportString( const CopiedString& self, const StringImportCallback& importer ){ - importer( self.c_str() ); -} -typedef ConstReferenceCaller1 CopiedStringExportStringCaller; - -inline void Bool_importString( bool& self, const char* string ){ - self = string_equal( string, "true" ); -} -typedef ReferenceCaller1 BoolImportStringCaller; -inline void Bool_exportString( const bool& self, const StringImportCallback& importer ){ - importer( self ? "true" : "false" ); -} -typedef ConstReferenceCaller1 BoolExportStringCaller; - -inline void Int_importString( int& self, const char* string ){ - if ( !string_parse_int( string, self ) ) { - self = 0; - } -} -typedef ReferenceCaller1 IntImportStringCaller; -inline void Int_exportString( const int& self, const StringImportCallback& importer ){ - char buffer[16]; - sprintf( buffer, "%d", self ); - importer( buffer ); -} -typedef ConstReferenceCaller1 IntExportStringCaller; - -inline void Size_importString( std::size_t& self, const char* string ){ - int i; - if ( string_parse_int( string, i ) && i >= 0 ) { - self = i; - } - else - { - self = 0; - } -} -typedef ReferenceCaller1 SizeImportStringCaller; -inline void Size_exportString( const std::size_t& self, const StringImportCallback& importer ){ - char buffer[16]; - sprintf( buffer, "%u", Unsigned( self ) ); - importer( buffer ); -} -typedef ConstReferenceCaller1 SizeExportStringCaller; - -inline void Float_importString( float& self, const char* string ){ - if ( !string_parse_float( string, self ) ) { - self = 0; - } -} -typedef ReferenceCaller1 FloatImportStringCaller; -inline void Float_exportString( const float& self, const StringImportCallback& importer ){ - char buffer[16]; - sprintf( buffer, "%g", self ); - importer( buffer ); -} -typedef ConstReferenceCaller1 FloatExportStringCaller; - -inline void Vector3_importString( Vector3& self, const char* string ){ - if ( !string_parse_vector( string, self ) ) { - self = Vector3( 0, 0, 0 ); - } -} -typedef ReferenceCaller1 Vector3ImportStringCaller; -inline void Vector3_exportString( const Vector3& self, const StringImportCallback& importer ){ - char buffer[64]; - sprintf( buffer, "%g %g %g", self[0], self[1], self[2] ); - importer( buffer ); -} -typedef ConstReferenceCaller1 Vector3ExportStringCaller; - - - -template -class ImportConvert1 -{ -public: -static void thunk( void* environment, FirstArgument firstArgument ){ - Caller::thunk( environment, FirstConversion( firstArgument ) ); -} -}; - - -class BoolFromString -{ -bool m_value; -public: -BoolFromString( const char* string ){ - Bool_importString( m_value, string ); -} -operator bool() const -{ - return m_value; -} -}; - -inline void Bool_toString( const StringImportCallback& self, bool value ){ - Bool_exportString( value, self ); -} -typedef ConstReferenceCaller1 BoolToString; - - -template -inline StringImportCallback makeBoolStringImportCallback( const Caller& caller ){ - return StringImportCallback( caller.getEnvironment(), ImportConvert1::thunk ); -} - -template -inline StringExportCallback makeBoolStringExportCallback( const Caller& caller ){ - return StringExportCallback( caller.getEnvironment(), ImportConvert1::thunk ); -} - - -class IntFromString -{ -int m_value; -public: -IntFromString( const char* string ){ - Int_importString( m_value, string ); -} -operator int() const -{ - return m_value; -} -}; - -inline void Int_toString( const StringImportCallback& self, int value ){ - Int_exportString( value, self ); -} -typedef ConstReferenceCaller1 IntToString; - - -template -inline StringImportCallback makeIntStringImportCallback( const Caller& caller ){ - return StringImportCallback( caller.getEnvironment(), ImportConvert1::thunk ); -} - -template -inline StringExportCallback makeIntStringExportCallback( const Caller& caller ){ - return StringExportCallback( caller.getEnvironment(), ImportConvert1::thunk ); -} - - - -class SizeFromString -{ -std::size_t m_value; -public: -SizeFromString( const char* string ){ - Size_importString( m_value, string ); -} -operator std::size_t() const -{ - return m_value; -} -}; - -inline void Size_toString( const StringImportCallback& self, std::size_t value ){ - Size_exportString( value, self ); -} -typedef ConstReferenceCaller1 SizeToString; - - -template -inline StringImportCallback makeSizeStringImportCallback( const Caller& caller ){ - return StringImportCallback( caller.getEnvironment(), ImportConvert1::thunk ); -} - -template -inline StringExportCallback makeSizeStringExportCallback( const Caller& caller ){ - return StringExportCallback( caller.getEnvironment(), ImportConvert1::thunk ); -} - -#endif diff --git a/tools/urt/libs/texturelib.cpp b/tools/urt/libs/texturelib.cpp deleted file mode 100644 index bbba462..0000000 --- a/tools/urt/libs/texturelib.cpp +++ /dev/null @@ -1,2 +0,0 @@ - -#include "texturelib.h" diff --git a/tools/urt/libs/texturelib.h b/tools/urt/libs/texturelib.h deleted file mode 100644 index 3353ffb..0000000 --- a/tools/urt/libs/texturelib.h +++ /dev/null @@ -1,21 +0,0 @@ - -#if !defined ( INCLUDED_TEXTURELIB_H ) -#define INCLUDED_TEXTURELIB_H - -#include "math/vector.h" -typedef Vector3 Colour3; -typedef unsigned int GLuint; - -// describes a GL texture -struct qtexture_t -{ - // name of the texture file (the physical image file we are using) - // NOTE: used for lookup, must be unique .. vfs path of the texture, lowercase, NO FILE EXTENSION - // ex textures/gothic_wall/iron - std::size_t width, height; - GLuint texture_number; // gl bind number - Colour3 color; // for flat shade mode - int surfaceFlags, contentFlags, value; -}; - -#endif diff --git a/tools/urt/libs/transformlib.cpp b/tools/urt/libs/transformlib.cpp deleted file mode 100644 index 8856e91..0000000 --- a/tools/urt/libs/transformlib.cpp +++ /dev/null @@ -1,2 +0,0 @@ - -#include "transformlib.h" diff --git a/tools/urt/libs/transformlib.h b/tools/urt/libs/transformlib.h deleted file mode 100644 index 9bcfa04..0000000 --- a/tools/urt/libs/transformlib.h +++ /dev/null @@ -1,215 +0,0 @@ - -#if !defined ( INCLUDED_TRANSFORMLIB_H ) -#define INCLUDED_TRANSFORMLIB_H - -class Matrix4; - -/// \brief A transform node. -class Transformable -{ -public: -static const char* getTypeName(){ - return "Transformable"; -} -/// \brief Returns the transform which maps the node's local-space into the local-space of its parent node. -virtual const Matrix4& localToParent() const = 0; -}; - -#include "math/matrix.h" -#include "math/quaternion.h" - - -/// \brief A transform node which has no effect. -class IdentityTransform : public Transformable -{ -public: -/// \brief Returns the identity matrix. -const Matrix4& localToParent() const { - return g_matrix4_identity; -} -}; - -/// \brief A transform node which stores a generic transformation matrix. -class MatrixTransform : public Transformable -{ -Matrix4 m_localToParent; -public: -MatrixTransform() : m_localToParent( g_matrix4_identity ){ -} - -Matrix4& localToParent(){ - return m_localToParent; -} -/// \brief Returns the stored local->parent transform. -const Matrix4& localToParent() const { - return m_localToParent; -} -}; - - -namespace Transform -{ -class Translation -{ -Vector3 m_value; -public: -Translation() - : m_value( 0, 0, 0 ){ -} -const Vector3& get() const { - return m_value; -} -void set( const Vector3& value ){ - m_value = value; -} -void translate( const Vector3& value ){ - m_value[0] += value[0]; - m_value[1] += value[1]; - m_value[2] += value[2]; -} -}; - -class Rotation -{ -Quaternion m_value; -public: -Rotation() - : m_value( c_quaternion_identity ){ -} -const Quaternion& get() const { - return m_value; -} -void set( const Quaternion& value ){ - m_value = value; -} -void rotate( const Quaternion& value ){ - quaternion_multiply_by_quaternion( m_value, value ); - quaternion_normalise( m_value ); -} -}; - -class Scale -{ -Vector3 m_value; -public: -Scale() - : m_value( 1, 1, 1 ){ -} -const Vector3& get() const { - return m_value; -} -void set( const Vector3& value ){ - m_value = value; -} -void scale( const Vector3& value ){ - m_value[0] *= value[0]; - m_value[1] *= value[1]; - m_value[2] *= value[2]; -} -}; -} - -/// \brief A transform node composed of separate translation, rotation and scale transforms. -/// -/// - Each component transform can be individually modified at any time. -/// - The transforms are applied in the order: Scale, Rotate, Translate. -/// - The transformation matrix produced is guaranteed to be affine and orthogonal. -class ComponentTransform : public Transformable -{ -Transform::Translation m_translation; -Transform::Rotation m_rotation; -Transform::Scale m_scale; -mutable Matrix4 m_transform; -mutable bool m_changed; - -void changed() const { - m_changed = true; -} -void evaluate() const { - if ( m_changed ) { - m_changed = false; - - Matrix4 rotation( matrix4_rotation_for_quaternion_quantised( m_rotation.get() ) ); - - m_transform.xx() = rotation.xx() * m_scale.get().x(); - m_transform.xy() = rotation.xy() * m_scale.get().x(); - m_transform.xz() = rotation.xz() * m_scale.get().x(); - m_transform.xw() = 0; - - m_transform.yx() = rotation.yx() * m_scale.get().y(); - m_transform.yy() = rotation.yy() * m_scale.get().y(); - m_transform.yz() = rotation.yz() * m_scale.get().y(); - m_transform.yw() = 0; - - m_transform.zx() = rotation.zx() * m_scale.get().z(); - m_transform.zy() = rotation.zy() * m_scale.get().z(); - m_transform.zz() = rotation.zz() * m_scale.get().z(); - m_transform.zw() = 0; - - m_transform.tx() = m_translation.get().x(); - m_transform.ty() = m_translation.get().y(); - m_transform.tz() = m_translation.get().z(); - m_transform.tw() = 1; - } -} -public: -ComponentTransform() - : m_changed( true ){ -} -const Matrix4& localToParent() const { - evaluate(); - return m_transform; -} - -const Vector3& getTranslation(){ - return m_translation.get(); -} -const Quaternion& getRotation(){ - return m_rotation.get(); -} -const Vector3& getScale(){ - return m_scale.get(); -} - -void setTranslation( const Vector3& value ){ - m_translation.set( value ); - changed(); -} -void setRotation( const Quaternion& value ){ - m_rotation.set( value ); - changed(); -} -void setScale( const Vector3& value ){ - m_scale.set( value ); - changed(); -} - -void translate( const Vector3& translation ){ - m_translation.translate( translation ); - changed(); -} -void rotate( const Quaternion& rotation ){ - m_rotation.rotate( rotation ); - changed(); -} -void scale( const Vector3& scale ){ - m_scale.scale( scale ); - changed(); -} - -void identity_translate(){ - m_translation = Transform::Translation(); - changed(); -} -void identity_rotate(){ - m_rotation = Transform::Rotation(); - changed(); -} -void identity_scale(){ - m_scale = Transform::Scale(); - changed(); -} -}; - - -#endif diff --git a/tools/urt/libs/traverselib.cpp b/tools/urt/libs/traverselib.cpp deleted file mode 100644 index 539ffe9..0000000 --- a/tools/urt/libs/traverselib.cpp +++ /dev/null @@ -1,2 +0,0 @@ - -#include "traverselib.h" diff --git a/tools/urt/libs/traverselib.h b/tools/urt/libs/traverselib.h deleted file mode 100644 index 5e60506..0000000 --- a/tools/urt/libs/traverselib.h +++ /dev/null @@ -1,304 +0,0 @@ - -#if !defined ( INCLUDED_TRAVERSELIB_H ) -#define INCLUDED_TRAVERSELIB_H - -#include "debugging/debugging.h" - -#include "scenelib.h" -#include "undolib.h" -#include "container/container.h" - -#include -#include -#include - -class TraversableObserverInsertOutputIterator -{ -protected: -scene::Traversable::Observer* m_observer; -public: -typedef std::output_iterator_tag iterator_category; -typedef void difference_type; -typedef void value_type; -typedef void pointer; -typedef void reference; - -TraversableObserverInsertOutputIterator( scene::Traversable::Observer* observer ) - : m_observer( observer ){ -} -TraversableObserverInsertOutputIterator& operator=( const NodeReference& node ){ - m_observer->insert( node ); - return *this; -} -TraversableObserverInsertOutputIterator& operator*() { return *this; } -TraversableObserverInsertOutputIterator& operator++() { return *this; } -TraversableObserverInsertOutputIterator& operator++( int ) { return *this; } -}; - -class TraversableObserverEraseOutputIterator -{ -protected: -scene::Traversable::Observer* m_observer; -public: -typedef std::output_iterator_tag iterator_category; -typedef void difference_type; -typedef void value_type; -typedef void pointer; -typedef void reference; - -TraversableObserverEraseOutputIterator( scene::Traversable::Observer* observer ) - : m_observer( observer ){ -} -TraversableObserverEraseOutputIterator& operator=( const NodeReference& node ){ - m_observer->erase( node ); - return *this; -} -TraversableObserverEraseOutputIterator& operator*() { return *this; } -TraversableObserverEraseOutputIterator& operator++() { return *this; } -TraversableObserverEraseOutputIterator& operator++( int ) { return *this; } -}; - -typedef UnsortedSet UnsortedNodeSet; - -/// \brief Calls \p observer->\c insert for each node that exists only in \p other and \p observer->\c erase for each node that exists only in \p self -inline void nodeset_diff( const UnsortedNodeSet& self, const UnsortedNodeSet& other, scene::Traversable::Observer* observer ){ - std::vector sorted( self.begin(), self.end() ); - std::vector other_sorted( other.begin(), other.end() ); - - std::sort( sorted.begin(), sorted.end() ); - std::sort( other_sorted.begin(), other_sorted.end() ); - - std::set_difference( sorted.begin(), sorted.end(), other_sorted.begin(), other_sorted.end(), TraversableObserverEraseOutputIterator( observer ) ); - std::set_difference( other_sorted.begin(), other_sorted.end(), sorted.begin(), sorted.end(), TraversableObserverInsertOutputIterator( observer ) ); -} - -/// \brief A sequence of node references which notifies an observer of inserts and deletions, and uses the global undo system to provide undo for modifications. -class TraversableNodeSet : public scene::Traversable -{ -UnsortedNodeSet m_children; -UndoableObject m_undo; -Observer* m_observer; - -void copy( const TraversableNodeSet& other ){ - m_children = other.m_children; -} -void notifyInsertAll(){ - if ( m_observer ) { - for ( UnsortedNodeSet::iterator i = m_children.begin(); i != m_children.end(); ++i ) - { - m_observer->insert( *i ); - } - } -} -void notifyEraseAll(){ - if ( m_observer ) { - for ( UnsortedNodeSet::iterator i = m_children.begin(); i != m_children.end(); ++i ) - { - m_observer->erase( *i ); - } - } -} -public: -TraversableNodeSet() - : m_undo( *this ), m_observer( 0 ){ -} -TraversableNodeSet( const TraversableNodeSet& other ) - : scene::Traversable( other ), m_undo( *this ), m_observer( 0 ){ - copy( other ); - notifyInsertAll(); -} -~TraversableNodeSet(){ - notifyEraseAll(); -} -TraversableNodeSet& operator=( const TraversableNodeSet& other ){ -#if 1 // optimised change-tracking using diff algorithm - if ( m_observer ) { - nodeset_diff( m_children, other.m_children, m_observer ); - } - copy( other ); -#else - TraversableNodeSet tmp( other ); - tmp.swap( *this ); -#endif - return *this; -} -void swap( TraversableNodeSet& other ){ - std::swap( m_children, other.m_children ); - std::swap( m_observer, other.m_observer ); -} - -void attach( Observer* observer ){ - ASSERT_MESSAGE( m_observer == 0, "TraversableNodeSet::attach: observer cannot be attached" ); - m_observer = observer; - notifyInsertAll(); -} -void detach( Observer* observer ){ - ASSERT_MESSAGE( m_observer == observer, "TraversableNodeSet::detach: observer cannot be detached" ); - notifyEraseAll(); - m_observer = 0; -} -/// \brief \copydoc scene::Traversable::insert() -void insert( scene::Node& node ){ - ASSERT_MESSAGE( &node != 0, "TraversableNodeSet::insert: sanity check failed" ); - m_undo.save(); - - ASSERT_MESSAGE( m_children.find( NodeSmartReference( node ) ) == m_children.end(), "TraversableNodeSet::insert - element already exists" ); - - m_children.insert( NodeSmartReference( node ) ); - - if ( m_observer ) { - m_observer->insert( node ); - } -} -/// \brief \copydoc scene::Traversable::erase() -void erase( scene::Node& node ){ - ASSERT_MESSAGE( &node != 0, "TraversableNodeSet::erase: sanity check failed" ); - m_undo.save(); - - ASSERT_MESSAGE( m_children.find( NodeSmartReference( node ) ) != m_children.end(), "TraversableNodeSet::erase - failed to find element" ); - - if ( m_observer ) { - m_observer->erase( node ); - } - - m_children.erase( NodeSmartReference( node ) ); -} -/// \brief \copydoc scene::Traversable::traverse() -void traverse( const Walker& walker ){ - UnsortedNodeSet::iterator i = m_children.begin(); - while ( i != m_children.end() ) - { - // post-increment the iterator - Node_traverseSubgraph( *i++, walker ); - // the Walker can safely remove the current node from - // this container without invalidating the iterator - } -} -/// \brief \copydoc scene::Traversable::empty() -bool empty() const { - return m_children.empty(); -} - -void instanceAttach( MapFile* map ){ - m_undo.instanceAttach( map ); -} -void instanceDetach( MapFile* map ){ - m_undo.instanceDetach( map ); -} -}; - -namespace std -{ -/// \brief Swaps the values of \p self and \p other. -/// Overloads std::swap. -inline void swap( TraversableNodeSet& self, TraversableNodeSet& other ){ - self.swap( other ); -} -} - - -class TraversableNode : public scene::Traversable -{ -public: -TraversableNode() : m_node( 0 ), m_observer( 0 ){ -} - -// traverse -void attach( Observer* observer ){ - ASSERT_MESSAGE( m_observer == 0, "TraversableNode::attach - cannot attach observer" ); - m_observer = observer; - if ( m_node != 0 ) { - m_observer->insert( *m_node ); - } -} -void detach( Observer* observer ){ - ASSERT_MESSAGE( m_observer == observer, "TraversableNode::detach - cannot detach observer" ); - if ( m_node != 0 ) { - m_observer->erase( *m_node ); - } - m_observer = 0; -} -void insert( scene::Node& node ){ - ASSERT_MESSAGE( m_node == 0, "TraversableNode::insert - element already exists" ); - - m_node = &node; - node.IncRef(); - - if ( m_observer != 0 ) { - m_observer->insert( node ); - } -} -void erase( scene::Node& node ){ - ASSERT_MESSAGE( m_node == &node, "TraversableNode::erase - failed to find element" ); - - if ( m_observer != 0 ) { - m_observer->erase( node ); - } - - m_node = 0; - node.DecRef(); -} -void traverse( const scene::Traversable::Walker& walker ){ - if ( m_node != 0 ) { - Node_traverseSubgraph( *m_node, walker ); - } -} -bool empty() const { - return m_node != 0; -} - -scene::Node& get(){ - return *m_node; -} - -private: -scene::Node* m_node; -Observer* m_observer; -}; - - -class TraversableObserverPairRelay : public scene::Traversable::Observer -{ -scene::Traversable::Observer* m_first; -scene::Traversable::Observer* m_second; -public: -TraversableObserverPairRelay() : m_first( 0 ), m_second( 0 ){ -} -void attach( scene::Traversable::Observer* observer ){ - ASSERT_MESSAGE( m_first == 0 || m_second == 0, "TraversableObserverPair::attach: cannot attach observer" ); - if ( m_first == 0 ) { - m_first = observer; - } - else if ( m_second == 0 ) { - m_second = observer; - } -} -void detach( scene::Traversable::Observer* observer ){ - ASSERT_MESSAGE( m_first == observer || m_second == observer, "TraversableObserverPair::detach: cannot detach observer" ); - if ( m_first == observer ) { - m_first = 0; - } - else if ( m_second == observer ) { - m_second = 0; - } -} -void insert( scene::Node& node ){ - if ( m_first != 0 ) { - m_first->insert( node ); - } - if ( m_second != 0 ) { - m_second->insert( node ); - } -} -void erase( scene::Node& node ){ - if ( m_second != 0 ) { - m_second->erase( node ); - } - if ( m_first != 0 ) { - m_first->erase( node ); - } -} -}; - - -#endif diff --git a/tools/urt/libs/typesystem.cpp b/tools/urt/libs/typesystem.cpp deleted file mode 100644 index ecc8748..0000000 --- a/tools/urt/libs/typesystem.cpp +++ /dev/null @@ -1,2 +0,0 @@ - -#include "typesystem.h" diff --git a/tools/urt/libs/typesystem.h b/tools/urt/libs/typesystem.h deleted file mode 100644 index ba60b0f..0000000 --- a/tools/urt/libs/typesystem.h +++ /dev/null @@ -1,116 +0,0 @@ - -#if !defined( INCLUDED_TYPESYSTEM_H ) -#define INCLUDED_TYPESYSTEM_H - - -#include -#include "generic/callback.h" -#include "generic/static.h" - -class InitialiserList -{ -typedef std::list Initialisers; -Initialisers m_initialisers; -mutable bool m_initialised; -public: -InitialiserList() : m_initialised( false ){ -} -void addInitialiser( const Callback& callback ){ - m_initialisers.push_back( callback ); -} -void initialise() const { - if ( !m_initialised ) { - m_initialised = true; - - for ( Initialisers::const_iterator i = m_initialisers.begin(); i != m_initialisers.end(); ++i ) - { - ( *i )( ); - } - } -} -}; - -//--Type System------------------- - -class TypeSystemInitialiser : public InitialiserList -{ -}; - -typedef SmartStatic StaticTypeSystemInitialiser; - -class TypeSystemRef : public StaticTypeSystemInitialiser -{ -public: -TypeSystemRef(){ - StaticTypeSystemInitialiser::instance().initialise(); -} -}; - - - -typedef std::size_t TypeId; -typedef void*( *TypeCast )( void* ); - -template -class TypeCastTable -{ -TypeCast m_casts[SIZE]; -public: -TypeCastTable(){ - std::uninitialized_fill( m_casts, m_casts + SIZE, TypeCast( 0 ) ); -} -void install( TypeId typeId, TypeCast typeCast ){ - m_casts[typeId] = typeCast; -} -void* cast( TypeId typeId, void* p ){ - TypeCast typeCast = m_casts[typeId]; - if ( typeCast != 0 ) { - return typeCast( p ); - } - return 0; -} -}; - -template -class CastInstaller -{ -public: -static void install( TypeCastTable& table ){ - table.install( Type::getTypeId(), Cast::cast ); -} -}; - -template -class IdentityCast -{ -public: -static void* cast( void* p ){ - return p; -} -}; - -template -class StaticCast -{ -public: -static void* cast( void* p ){ - return static_cast( reinterpret_cast( p ) ); -} -}; - -template -class NullType -{ -}; - -template -class ContainedCast -{ -public: -static void* cast( void* p ){ - return &reinterpret_cast( p )->get( NullType() ); -} -}; - - -#endif diff --git a/tools/urt/libs/undolib.cpp b/tools/urt/libs/undolib.cpp deleted file mode 100644 index 07fee2e..0000000 --- a/tools/urt/libs/undolib.cpp +++ /dev/null @@ -1,2 +0,0 @@ - -#include "undolib.h" diff --git a/tools/urt/libs/undolib.h b/tools/urt/libs/undolib.h deleted file mode 100644 index 571f94d..0000000 --- a/tools/urt/libs/undolib.h +++ /dev/null @@ -1,121 +0,0 @@ - -#if !defined ( INCLUDED_UNDOLIB_H ) -#define INCLUDED_UNDOLIB_H - -#include "iundo.h" -#include "mapfile.h" -#include "warnings.h" -#include "generic/callback.h" - -template -class BasicUndoData : public UndoData -{ -Copyable m_data; -public: -BasicUndoData( const Copyable& data ) - : m_data( data ){ -} - -void release(){ - delete this; -} - -const Copyable& get() const { - return m_data; -} -}; - - -template -class ObservedUndoableObject : public Undoable -{ -typedef Callback1 ImportCallback; - -Copyable& m_object; -ImportCallback m_importCallback; -UndoObserver* m_undoQueue; -MapFile* m_map; -public: - -ObservedUndoableObject( Copyable & object, const ImportCallback &importCallback ) - : m_object( object ), m_importCallback( importCallback ), m_undoQueue( 0 ), m_map( 0 ) -{ -} -~ObservedUndoableObject(){ -} - -MapFile* map(){ - return m_map; -} - -void instanceAttach( MapFile* map ){ - m_map = map; - m_undoQueue = GlobalUndoSystem().observer( this ); -} -void instanceDetach( MapFile* map ){ - m_map = 0; - m_undoQueue = 0; - GlobalUndoSystem().release( this ); -} - -void save(){ - if ( m_map != 0 ) { - m_map->changed(); - } - if ( m_undoQueue != 0 ) { - m_undoQueue->save( this ); - } -} - -UndoData* exportState() const { - return new BasicUndoData( m_object ); -} -void importState( const UndoData* state ){ - save(); - m_importCallback( ( static_cast*>( state ) )->get() ); -} -}; - -template -class UndoableObject : public Undoable -{ -Copyable& m_object; -UndoObserver* m_undoQueue; -MapFile* m_map; - -public: -UndoableObject( Copyable& object ) - : m_object( object ), m_undoQueue( 0 ), m_map( 0 ) -{} -~UndoableObject(){ -} - -void instanceAttach( MapFile* map ){ - m_map = map; - m_undoQueue = GlobalUndoSystem().observer( this ); -} -void instanceDetach( MapFile* map ){ - m_map = 0; - m_undoQueue = 0; - GlobalUndoSystem().release( this ); -} - -void save(){ - if ( m_map != 0 ) { - m_map->changed(); - } - if ( m_undoQueue != 0 ) { - m_undoQueue->save( this ); - } -} - -UndoData* exportState() const { - return new BasicUndoData( m_object ); -} -void importState( const UndoData* state ){ - save(); - m_object = ( static_cast*>( state ) )->get(); -} -}; - -#endif diff --git a/tools/urt/libs/uniquenames.cpp b/tools/urt/libs/uniquenames.cpp deleted file mode 100644 index 9694c51..0000000 --- a/tools/urt/libs/uniquenames.cpp +++ /dev/null @@ -1,2 +0,0 @@ - -#include "uniquenames.h" diff --git a/tools/urt/libs/uniquenames.h b/tools/urt/libs/uniquenames.h deleted file mode 100644 index 29f7093..0000000 --- a/tools/urt/libs/uniquenames.h +++ /dev/null @@ -1,282 +0,0 @@ - -#if !defined( INCLUDED_UNIQUENAMES_H ) -#define INCLUDED_UNIQUENAMES_H - -#include "debugging/debugging.h" -#include -#include "string/string.h" -#include "generic/static.h" - -#if 1 -class Postfix -{ -unsigned int m_value; -public: -Postfix( const char* postfix ) : m_value( atoi( postfix ) ){ -} -unsigned int number() const { - return m_value; -} -void write( char* buffer ){ - sprintf( buffer, "%u", m_value ); -} -Postfix& operator++(){ - ++m_value; - return *this; -} -bool operator<( const Postfix& other ) const { - return m_value < other.m_value; -} -bool operator==( const Postfix& other ) const { - return m_value == other.m_value; -} -bool operator!=( const Postfix& other ) const { - return !operator==( other ); -} -}; - -#else -class Postfix -{ -std::pair m_value; -public: -Postfix( unsigned int number, unsigned int leading_zeros ) - : m_value( leading_zeros, number ){ -} -Postfix( const char* postfix ) - : m_value( number_count_leading_zeros( postfix ), atoi( postfix ) ){ -} -unsigned int number() const { - return m_value.second; -} -unsigned int leading_zeros() const { - return m_value.first; -} -void write( char* buffer ){ - for ( unsigned int count = 0; count < m_value.first; ++count, ++buffer ) - *buffer = '0'; - sprintf( buffer, "%u", m_value.second ); -} -Postfix& operator++(){ - ++m_value.second; - if ( m_value.first != 0 && m_value.second % 10 == 0 ) { - --m_value.first; - } - return *this; -} -bool operator<( const Postfix& other ) const { - return m_value < other.m_value; -} -bool operator==( const Postfix& other ) const { - return m_value == other.m_value; -} -bool operator!=( const Postfix& other ) const { - return !operator==( other ); -} -}; - -#endif - -typedef std::pair name_t; - -inline void name_write( char* buffer, name_t name ){ - strcpy( buffer, name.first.c_str() ); - name.second.write( buffer + strlen( name.first.c_str() ) ); -} - -inline name_t name_read( const char* name ){ - const char* end = name + strlen( name ); - for ( const char* p = end; end != name; --p ) - { - if ( strrchr( "1234567890", *p ) == NULL ) { - break; - } - end = p; - } - - return name_t( CopiedString( name, end ), Postfix( end ) ); -} - - -class PostFixes -{ -typedef std::map postfixes_t; -postfixes_t m_postfixes; - -Postfix find_first_empty() const { - Postfix postfix( "1" ); - for ( postfixes_t::const_iterator i = m_postfixes.find( postfix ); i != m_postfixes.end(); ++i, ++postfix ) - { - if ( ( *i ).first != postfix ) { - break; - } - } - return postfix; -} - -public: -Postfix make_unique( Postfix postfix ) const { - postfixes_t::const_iterator i = m_postfixes.find( postfix ); - if ( i == m_postfixes.end() ) { - return postfix; - } - else - { - return find_first_empty(); - } -} - -void insert( Postfix postfix ){ - postfixes_t::iterator i = m_postfixes.find( postfix ); - if ( i == m_postfixes.end() ) { - m_postfixes.insert( postfixes_t::value_type( postfix, 1 ) ); - } - else - { - ++( *i ).second; - } -} - -void erase( Postfix postfix ){ - postfixes_t::iterator i = m_postfixes.find( postfix ); - if ( i == m_postfixes.end() ) { - // error - } - else - { - if ( --( *i ).second == 0 ) { - m_postfixes.erase( i ); - } - } -} - -bool empty() const { - return m_postfixes.empty(); -} -}; - - -class UniqueNames -{ -typedef std::map names_t; -names_t m_names; -public: -name_t make_unique( const name_t& name ) const { - names_t::const_iterator i = m_names.find( name.first ); - if ( i == m_names.end() ) { - return name; - } - else - { - return name_t( name.first, ( *i ).second.make_unique( name.second ) ); - } -} - -void insert( const name_t& name ){ - m_names[name.first].insert( name.second ); -} - -void erase( const name_t& name ){ - names_t::iterator i = m_names.find( name.first ); - if ( i == m_names.end() ) { - ASSERT_MESSAGE( true, "erase: name not found" ); - } - else - { - ( *i ).second.erase( name.second ); - if ( ( *i ).second.empty() ) { - m_names.erase( i ); - } - } -} - -bool empty() const { - return m_names.empty(); -} -}; - - - -#if 0 - -#undef ERROR_MESSAGE -#define ERROR_MESSAGE( message ) - -class TestUniqueName -{ -void name_check_equal( const name_t& name, const char* string, unsigned int postfix ){ - ASSERT_MESSAGE( strcmp( name.first.c_str(), string ) == 0 - && name.second.number() == postfix, - "test failed!" ); -} -void test_refcount(){ - Names names; - - names.insert( name_t( "func_bleh_", "100" ) ); - names.insert( name_t( "func_bleh_", "100" ) ); - names.insert( name_t( "func_bleh_", "100" ) ); - - - names.erase( name_t( "func_bleh_", "100" ) ); - names.erase( name_t( "func_bleh_", "100" ) ); - names.erase( name_t( "func_bleh_", "100" ) ); - - ASSERT_MESSAGE( names.empty(), "test failed!" ); -} - -void test_make_unique(){ - Names names; - - { - name_t name( names.make_unique( name_t( "func_bleh_", "01" ) ) ); - name_check_equal( name, "func_bleh_", 1 ); - names.insert( name ); - } - { - name_t name( names.make_unique( name_t( "func_bleh_", "04" ) ) ); - name_check_equal( name, "func_bleh_", 4 ); - names.insert( name ); - } - { - name_t name( names.make_unique( name_t( "func_bleh_", "04" ) ) ); - name_check_equal( name, "func_bleh_", 2 ); - names.insert( name ); - } - { - name_t name( names.make_unique( name_t( "func_bleh_", "1" ) ) ); - name_check_equal( name, "func_bleh_", 3 ); - names.insert( name ); - } - { - name_t name( names.make_unique( name_t( "func_bleh_", "2" ) ) ); - name_check_equal( name, "func_bleh_", 5 ); - names.insert( name ); - } - { - name_t name( names.make_unique( name_t( "func_bleh_", "3" ) ) ); - name_check_equal( name, "func_bleh_", 6 ); - names.insert( name ); - } - - names.erase( name_t( "func_bleh_", "1" ) ); - names.erase( name_t( "func_bleh_", "2" ) ); - names.erase( name_t( "func_bleh_", "3" ) ); - names.erase( name_t( "func_bleh_", "4" ) ); - names.erase( name_t( "func_bleh_", "5" ) ); - names.erase( name_t( "func_bleh_", "6" ) ); - - ASSERT_MESSAGE( names.empty(), "test failed!" ); -} -public: -TestUniqueName(){ - test_refcount(); - test_make_unique(); -} -}; - -const TestUniqueName g_testuniquename; - -#endif - - -#endif diff --git a/tools/urt/libs/versionlib.cpp b/tools/urt/libs/versionlib.cpp deleted file mode 100644 index 220b893..0000000 --- a/tools/urt/libs/versionlib.cpp +++ /dev/null @@ -1,2 +0,0 @@ - -#include "versionlib.h" diff --git a/tools/urt/libs/versionlib.h b/tools/urt/libs/versionlib.h deleted file mode 100644 index 3c46db0..0000000 --- a/tools/urt/libs/versionlib.h +++ /dev/null @@ -1,62 +0,0 @@ - -#if !defined( INCLUDED_VERSIONLIB_H ) -#define INCLUDED_VERSIONLIB_H - -#include -#include -#include - -class Version -{ -public: -int major; -int minor; -}; - -inline bool operator<( const Version& version, const Version& other ){ - return version.major < other.major || ( !( other.major < version.major ) && version.minor < other.minor ); -} - -template -TextOutputStreamType& ostream_write( TextOutputStreamType& outputStream, const Version& version ){ - return outputStream << version.major << '.' << version.minor; -} - -/// \brief Returns true if \p version (code) is compatible with \p other (data). -inline bool version_compatible( const Version& version, const Version& other ){ - return version.major == other.major // different major-versions are always incompatible - && !( version.minor < other.minor ); // data minor-version is incompatible if greater than code minor-version -} - -inline int string_range_parse_int( const char* first, const char* last ){ - const std::size_t bufferSize = 32; - char buffer[bufferSize]; - strncpy( buffer, first, std::min( std::size_t( last - first ), bufferSize - 1 ) ); - buffer[bufferSize - 1] = '\0'; - return atoi( buffer ); -} - -inline Version version_parse( const char* versionString ){ - Version version; - const char* endVersion = versionString + strlen( versionString ); - - const char* endMajor = strchr( versionString, '.' ); - if ( endMajor == 0 ) { - endMajor = endVersion; - - version.minor = 0; - } - else - { - const char* endMinor = strchr( endMajor + 1, '.' ); - if ( endMinor == 0 ) { - endMinor = endVersion; - } - version.minor = string_range_parse_int( endMajor + 1, endMinor ); - } - version.major = string_range_parse_int( versionString, endMajor ); - - return version; -} - -#endif diff --git a/tools/urt/libs/xml/ixml.cpp b/tools/urt/libs/xml/ixml.cpp deleted file mode 100644 index 66aa9d1..0000000 --- a/tools/urt/libs/xml/ixml.cpp +++ /dev/null @@ -1,2 +0,0 @@ - -#include "ixml.h" diff --git a/tools/urt/libs/xml/ixml.h b/tools/urt/libs/xml/ixml.h deleted file mode 100644 index 10819c5..0000000 --- a/tools/urt/libs/xml/ixml.h +++ /dev/null @@ -1,43 +0,0 @@ - -#if !defined( INCLUDED_XML_IXML_H ) -#define INCLUDED_XML_IXML_H - -#include "itextstream.h" - -class XMLAttrVisitor -{ -public: -virtual void visit( const char* name, const char* value ) = 0; -}; - -class XMLElement -{ -public: -virtual const char* name() const = 0; -virtual const char* attribute( const char* name ) const = 0; -virtual void forEachAttribute( XMLAttrVisitor& visitor ) const = 0; -}; - -class XMLImporter : public TextOutputStream -{ -public: -static const char* getTypeName(){ - return "XMLImporter"; -} - -virtual void pushElement( const XMLElement& element ) = 0; -virtual void popElement( const char* name ) = 0; -}; - -class XMLExporter -{ -public: -static const char* getTypeName(){ - return "XMLExporter"; -} - -virtual void exportXML( XMLImporter& importer ) = 0; -}; - - -#endif diff --git a/tools/urt/libs/xml/xmlelement.cpp b/tools/urt/libs/xml/xmlelement.cpp deleted file mode 100644 index bf7a6a7..0000000 --- a/tools/urt/libs/xml/xmlelement.cpp +++ /dev/null @@ -1,2 +0,0 @@ - -#include "xmlelement.h" diff --git a/tools/urt/libs/xml/xmlelement.h b/tools/urt/libs/xml/xmlelement.h deleted file mode 100644 index d4a2ccc..0000000 --- a/tools/urt/libs/xml/xmlelement.h +++ /dev/null @@ -1,83 +0,0 @@ - -#if !defined( INCLUDED_XML_XMLELEMENT_H ) -#define INCLUDED_XML_XMLELEMENT_H - -#include "xml/ixml.h" -#include "string/string.h" - -#include - -class StaticElement : public XMLElement -{ -struct strless -{ - bool operator()( const char* s1, const char* s2 ) const { - return strcmp( s1, s2 ) < 0; - } -}; - -typedef std::map attrs_t; -public: -StaticElement( const char* name ) - : m_name( name ){ -} -void insertAttribute( const char* name, const char* value ){ - m_attrs.insert( attrs_t::value_type( name, value ) ); -} -const char* name() const { - return m_name; -} -const char* attribute( const char* name ) const { - attrs_t::const_iterator i = m_attrs.find( name ); - if ( i != m_attrs.end() ) { - return i->second; - } - else{ - return ""; - } -} -void forEachAttribute( XMLAttrVisitor& visitor ) const { - for ( attrs_t::const_iterator i = m_attrs.begin(); i != m_attrs.end(); ++i ) - { - visitor.visit( i->first, i->second ); - } -} -private: -const char* m_name; -attrs_t m_attrs; -}; - -class DynamicElement : public XMLElement -{ -typedef std::map attrs_t; -public: -DynamicElement( const char* name ) - : m_name( name ) -{} -void insertAttribute( const char* name, const char* value ){ - m_attrs.insert( attrs_t::value_type( name, value ) ); -} -const char* name() const { - return m_name.c_str(); -} -const char* attribute( const char* name ) const { - attrs_t::const_iterator i = m_attrs.find( name ); - if ( i != m_attrs.end() ) { - return i->second.c_str(); - } - else{ - return ""; - } -} -void forEachAttribute( XMLAttrVisitor& visitor ) const { - for ( attrs_t::const_iterator i = m_attrs.begin(); i != m_attrs.end(); ++i ) - { - visitor.visit( i->first.c_str(), i->second.c_str() ); - } -} -private: -CopiedString m_name; -attrs_t m_attrs; -}; - -#endif diff --git a/tools/urt/libs/xml/xmlparser.cpp b/tools/urt/libs/xml/xmlparser.cpp deleted file mode 100644 index 70ce7e1..0000000 --- a/tools/urt/libs/xml/xmlparser.cpp +++ /dev/null @@ -1,2 +0,0 @@ - -#include "xmlparser.h" diff --git a/tools/urt/libs/xml/xmlparser.h b/tools/urt/libs/xml/xmlparser.h deleted file mode 100644 index 93c4d3d..0000000 --- a/tools/urt/libs/xml/xmlparser.h +++ /dev/null @@ -1,199 +0,0 @@ - -#if !defined( INCLUDED_XML_XMLPARSER_H ) -#define INCLUDED_XML_XMLPARSER_H - -#include -#include -#include "ixml.h" -#include "libxml/parser.h" -#include "convert.h" - -class TextInputStream; - -class SAXElement : public XMLElement -{ -public: -SAXElement( const char* name, const char** atts ) - : m_name( name ), m_atts( atts ){ -} -const char* name() const { - return m_name; -} -const char* attribute( const char* name ) const { - if ( m_atts != 0 ) { - for ( const char** att = m_atts; *att != 0; att += 2 ) - { - if ( strcmp( *att, name ) == 0 ) { - return *( ++att ); - } - } - } - return ""; -} -void forEachAttribute( XMLAttrVisitor& visitor ) const { - if ( m_atts != 0 ) { - for ( const char** att = m_atts; *att != 0; att += 2 ) - { - visitor.visit( *att, *( att + 1 ) ); - } - } -} -private: -const char* m_name; -const char** m_atts; -}; - -#include - -class FormattedVA -{ -public: -const char* m_format; -va_list& m_arguments; -FormattedVA( const char* format, va_list& m_arguments ) - : m_format( format ), m_arguments( m_arguments ){ -} -}; - -class Formatted -{ -public: -const char* m_format; -va_list m_arguments; -Formatted( const char* format, ... ) - : m_format( format ){ - va_start( m_arguments, format ); -} -~Formatted(){ - va_end( m_arguments ); -} -}; - -#ifdef WIN32 -#if _MSC_VER < 1400 -#define vsnprintf std::vsnprintf -#endif -#endif - -template -inline TextOutputStreamType& ostream_write( TextOutputStreamType& ostream, const FormattedVA& formatted ){ - char buffer[1024]; - ostream.write( buffer, vsnprintf( buffer, 1023, formatted.m_format, formatted.m_arguments ) ); - return ostream; -} - -template -inline TextOutputStreamType& ostream_write( TextOutputStreamType& ostream, const Formatted& formatted ){ - char buffer[1024]; - ostream.write( buffer, vsnprintf( buffer, 1023, formatted.m_format, formatted.m_arguments ) ); - return ostream; -} - -class XMLSAXImporter -{ -XMLImporter& m_importer; -xmlSAXHandler m_sax; - -static void startElement( void *user_data, const xmlChar *name, const xmlChar **atts ){ - SAXElement element( reinterpret_cast( name ), reinterpret_cast( atts ) ); - reinterpret_cast( user_data )->m_importer.pushElement( element ); -} -static void endElement( void *user_data, const xmlChar *name ){ - reinterpret_cast( user_data )->m_importer.popElement( reinterpret_cast( name ) ); -} -static void characters( void *user_data, const xmlChar *ch, int len ){ - reinterpret_cast( user_data )->m_importer - << ConvertUTF8ToLocale( StringRange( reinterpret_cast( ch ), reinterpret_cast( ch + len ) ) ); -} - -static void warning( void *user_data, const char *msg, ... ){ - va_list args; - va_start( args, msg ); - globalErrorStream() << "XML WARNING: " << FormattedVA( msg, args ); - va_end( args ); -} -static void error( void *user_data, const char *msg, ... ){ - va_list args; - va_start( args, msg ); - globalErrorStream() << "XML ERROR: " << FormattedVA( msg, args ); - va_end( args ); -} - -public: -XMLSAXImporter( XMLImporter& importer ) : m_importer( importer ){ - m_sax.internalSubset = 0; - m_sax.isStandalone = 0; - m_sax.hasInternalSubset = 0; - m_sax.hasExternalSubset = 0; - m_sax.resolveEntity = 0; - m_sax.getEntity = 0; - m_sax.entityDecl = 0; - m_sax.notationDecl = 0; - m_sax.attributeDecl = 0; - m_sax.elementDecl = 0; - m_sax.unparsedEntityDecl = 0; - m_sax.setDocumentLocator = 0; - m_sax.startDocument = 0; - m_sax.endDocument = 0; - m_sax.startElement = startElement; - m_sax.endElement = endElement; - m_sax.reference = 0; - m_sax.characters = characters; - m_sax.ignorableWhitespace = 0; - m_sax.processingInstruction = 0; - m_sax.comment = 0; - m_sax.warning = warning; - m_sax.error = error; - m_sax.fatalError = 0; - m_sax.getParameterEntity = 0; - m_sax.cdataBlock = 0; - m_sax.externalSubset = 0; - m_sax.initialized = 1; -} - -xmlSAXHandler* callbacks(){ - return &m_sax; -} -void* context(){ - return this; -} -}; - -class XMLStreamParser : public XMLExporter -{ -enum { BUFSIZE = 1024 }; -public: -XMLStreamParser( TextInputStream& istream ) - : m_istream( istream ){ -} -virtual void exportXML( XMLImporter& importer ){ - bool wellFormed = false; - - char chars[BUFSIZE]; - std::size_t res = m_istream.read( chars, 4 ); - if ( res > 0 ) { - XMLSAXImporter sax( importer ); - - xmlParserCtxtPtr ctxt = xmlCreatePushParserCtxt( sax.callbacks(), sax.context(), chars, static_cast( res ), 0 ); - ctxt->replaceEntities = 1; - - while ( ( res = m_istream.read( chars, BUFSIZE ) ) > 0 ) - { - xmlParseChunk( ctxt, chars, static_cast( res ), 0 ); - } - xmlParseChunk( ctxt, chars, 0, 1 ); - - wellFormed = ( ctxt->wellFormed == 1 ); - - xmlFreeParserCtxt( ctxt ); - } - - //return wellFormed; -} -private: -TextInputStream& m_istream; -}; - - - -#endif diff --git a/tools/urt/libs/xml/xmlwriter.cpp b/tools/urt/libs/xml/xmlwriter.cpp deleted file mode 100644 index 209abb1..0000000 --- a/tools/urt/libs/xml/xmlwriter.cpp +++ /dev/null @@ -1,2 +0,0 @@ - -#include "xmlwriter.h" diff --git a/tools/urt/libs/xml/xmlwriter.h b/tools/urt/libs/xml/xmlwriter.h deleted file mode 100644 index 6c0a7a7..0000000 --- a/tools/urt/libs/xml/xmlwriter.h +++ /dev/null @@ -1,196 +0,0 @@ - -#if !defined( INCLUDED_XML_XMLWRITER_H ) -#define INCLUDED_XML_XMLWRITER_H - -#include "convert.h" -#include -#include "xml/ixml.h" - -class BufferedTextOutputStream : public TextOutputStream -{ -enum { m_bufsize = 1024 }; // aka const std::size_t m_bufsize = 1024; -TextOutputStream& m_ostream; -char m_buffer[m_bufsize]; -char* m_pos; -const char* m_end; - -const char* end() const { - return m_end; -} -void reset(){ - m_pos = m_buffer; -} -void flush(){ - m_ostream.write( m_buffer, m_pos - m_buffer ); - reset(); -} -public: -BufferedTextOutputStream( TextOutputStream& ostream ) : m_ostream( ostream ), m_pos( m_buffer ), m_end( m_buffer + m_bufsize ){ -} -~BufferedTextOutputStream(){ - flush(); -} -void write( const char c ){ - if ( m_pos == end() ) { - flush(); - } - *m_pos++ = c; -} -std::size_t write( const char* buffer, std::size_t length ){ - const char*const end = buffer + length; - for ( const char* p = buffer; p != end; ++p ) - { - write( *p ); - } - return length; -} -}; - -class XMLEntityOutputStream -{ -BufferedTextOutputStream m_ostream; -public: -XMLEntityOutputStream( TextOutputStream& ostream ) - : m_ostream( ostream ){ -} -void write( const char c ){ - m_ostream.write( c ); -} -void writeEscaped( const char c ){ - switch ( c ) - { - case '<': - write( '&' ); - write( 'l' ); - write( 't' ); - write( ';' ); - break; - case '>': - write( '&' ); - write( 'g' ); - write( 't' ); - write( ';' ); - break; - case '"': - write( '&' ); - write( 'q' ); - write( 'u' ); - write( 'o' ); - write( 't' ); - write( ';' ); - break; - case '&': - write( '&' ); - write( 'a' ); - write( 'm' ); - write( 'p' ); - write( ';' ); - break; - default: - write( c ); - break; - } -} -std::size_t write( const char* buffer, std::size_t length ){ - const char*const end = buffer + length; - for ( const char* p = buffer; p != end; ++p ) - { - writeEscaped( *p ); - } - return length; -} -}; - -template -inline XMLEntityOutputStream& operator<<( XMLEntityOutputStream& ostream, const T& t ){ - return ostream_write( ostream, t ); -} - - -class XMLStreamWriter : public XMLImporter, public XMLAttrVisitor -{ -class state_t -{ -public: -enum EState -{ - eStartElement, - eContent, -}; -state_t() - : m_state( eStartElement ) -{} -EState m_state; -}; - -XMLEntityOutputStream m_ostream; -std::vector m_elements; - -void write_cdata( const char* buffer, std::size_t length ){ - m_ostream << ConvertLocaleToUTF8( StringRange( buffer, buffer + length ) ); -} -void write_string( const char* string ){ - m_ostream << string; -} -void write_quoted_string( const char* string ){ - m_ostream.write( '"' ); - m_ostream << string; - m_ostream.write( '"' ); -} -public: -XMLStreamWriter( TextOutputStream& ostream ) - : m_ostream( ostream ){ - m_elements.push_back( state_t() ); - m_elements.back().m_state = state_t::eContent; - m_ostream.write( '<' ); - m_ostream.write( '?' ); - write_string( "xml" ); - visit( "version", "1.0" ); - m_ostream.write( '?' ); - m_ostream.write( '>' ); -} - -void pushElement( const XMLElement& element ){ - if ( m_elements.back().m_state == state_t::eStartElement ) { - m_elements.back().m_state = state_t::eContent; - m_ostream.write( '>' ); - } - - m_elements.push_back( state_t() ); - - m_ostream.write( '<' ); - write_string( element.name() ); - element.forEachAttribute( *this ); -} -void popElement( const char* name ){ - if ( m_elements.back().m_state == state_t::eStartElement ) { - m_ostream.write( '/' ); - m_ostream.write( '>' ); - } - else - { - m_ostream.write( '<' ); - m_ostream.write( '/' ); - write_string( name ); - m_ostream.write( '>' ); - } -} -std::size_t write( const char* data, std::size_t length ){ - if ( m_elements.back().m_state == state_t::eStartElement ) { - m_elements.back().m_state = state_t::eContent; - m_ostream.write( '>' ); - } - write_cdata( data, length ); - return length; -} - -void visit( const char* name, const char* value ){ - m_ostream.write( ' ' ); - write_string( name ); - m_ostream.write( '=' ); - write_quoted_string( value ); -} -}; - - -#endif diff --git a/tools/urt/tools/quake3/common/aselib.c b/tools/urt/tools/quake3/common/aselib.c deleted file mode 100644 index 13eca7b..0000000 --- a/tools/urt/tools/quake3/common/aselib.c +++ /dev/null @@ -1,894 +0,0 @@ -/* - Copyright (C) 1999-2007 id Software, Inc. and contributors. - For a list of contributors, see the accompanying CONTRIBUTORS file. - - This file is part of GtkRadiant. - - GtkRadiant is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - GtkRadiant is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with GtkRadiant; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - */ - - -#include "aselib.h" -#include "inout.h" - -#include -#include -#include - -#define MAX_ASE_MATERIALS 32 -#define MAX_ASE_OBJECTS 64 -#define MAX_ASE_ANIMATIONS 32 -#define MAX_ASE_ANIMATION_FRAMES 512 - -#define VERBOSE( x ) { if ( ase.verbose ) { Sys_Printf x ; } } - -typedef struct -{ - float x, y, z; - float nx, ny, nz; - float s, t; -} aseVertex_t; - -typedef struct -{ - float s, t; -} aseTVertex_t; - -typedef int aseFace_t[3]; - -typedef struct -{ - int numFaces; - int numVertexes; - int numTVertexes; - - int timeValue; - - aseVertex_t *vertexes; - aseTVertex_t *tvertexes; - aseFace_t *faces, *tfaces; - - int currentFace, currentVertex; -} aseMesh_t; - -typedef struct -{ - int numFrames; - aseMesh_t frames[MAX_ASE_ANIMATION_FRAMES]; - - int currentFrame; -} aseMeshAnimation_t; - -typedef struct -{ - char name[128]; -} aseMaterial_t; - -/* -** contains the animate sequence of a single surface -** using a single material -*/ -typedef struct -{ - char name[128]; - - int materialRef; - int numAnimations; - - aseMeshAnimation_t anim; - -} aseGeomObject_t; - -typedef struct -{ - int numMaterials; - aseMaterial_t materials[MAX_ASE_MATERIALS]; - aseGeomObject_t objects[MAX_ASE_OBJECTS]; - - char *buffer; - char *curpos; - int len; - - int currentObject; - qboolean verbose; - qboolean grabAnims; - -} ase_t; - -static char s_token[1024]; -static ase_t ase; -static char gl_filename[1024]; - -static void ASE_Process( void ); -static void ASE_FreeGeomObject( int ndx ); - -#if defined ( __linux__ ) || defined ( __APPLE__ ) - -static char* strlwr( char* string ){ - char *cp; - for ( cp = string; *cp; ++cp ) - { - if ( 'A' <= *cp && *cp <= 'Z' ) { - *cp += 'a' - 'A'; - } - } - - return string; -} - -#endif - -/* -** ASE_Load -*/ -void ASE_Load( const char *filename, qboolean verbose, qboolean grabAnims ){ - FILE *fp = fopen( filename, "rb" ); - - if ( !fp ) { - Error( "File not found '%s'", filename ); - } - - memset( &ase, 0, sizeof( ase ) ); - - ase.verbose = verbose; - ase.grabAnims = grabAnims; - ase.len = Q_filelength( fp ); - - ase.curpos = ase.buffer = safe_malloc( ase.len ); - - Sys_Printf( "Processing '%s'\n", filename ); - - if ( fread( ase.buffer, ase.len, 1, fp ) != 1 ) { - fclose( fp ); - Error( "fread() != -1 for '%s'", filename ); - } - - fclose( fp ); - - strcpy( gl_filename, filename ); - - ASE_Process(); -} - -/* -** ASE_Free -*/ -void ASE_Free( void ){ - int i; - - for ( i = 0; i < ase.currentObject; i++ ) - { - ASE_FreeGeomObject( i ); - } -} - -/* -** ASE_GetNumSurfaces -*/ -int ASE_GetNumSurfaces( void ){ - return ase.currentObject; -} - -/* -** ASE_GetSurfaceName -*/ -const char *ASE_GetSurfaceName( int which ){ - aseGeomObject_t *pObject = &ase.objects[which]; - - if ( !pObject->anim.numFrames ) { - return 0; - } - - return pObject->name; -} - -/* -** ASE_GetSurfaceAnimation -** -** Returns an animation (sequence of polysets) -*/ -polyset_t *ASE_GetSurfaceAnimation( int which, int *pNumFrames, int skipFrameStart, int skipFrameEnd, int maxFrames ){ - aseGeomObject_t *pObject = &ase.objects[which]; - polyset_t *psets; - int numFramesInAnimation; - int numFramesToKeep; - int i, f; - - if ( !pObject->anim.numFrames ) { - return 0; - } - - if ( pObject->anim.numFrames > maxFrames && maxFrames != -1 ) { - numFramesInAnimation = maxFrames; - } - else - { - numFramesInAnimation = pObject->anim.numFrames; - if ( maxFrames != -1 ) { - Sys_Printf( "WARNING: ASE_GetSurfaceAnimation maxFrames > numFramesInAnimation\n" ); - } - } - - if ( skipFrameEnd != -1 ) { - numFramesToKeep = numFramesInAnimation - ( skipFrameEnd - skipFrameStart + 1 ); - } - else{ - numFramesToKeep = numFramesInAnimation; - } - - *pNumFrames = numFramesToKeep; - - psets = calloc( sizeof( polyset_t ) * numFramesToKeep, 1 ); - - for ( f = 0, i = 0; i < numFramesInAnimation; i++ ) - { - int t; - aseMesh_t *pMesh = &pObject->anim.frames[i]; - - if ( skipFrameStart != -1 ) { - if ( i >= skipFrameStart && i <= skipFrameEnd ) { - continue; - } - } - - strcpy( psets[f].name, pObject->name ); - strcpy( psets[f].materialname, ase.materials[pObject->materialRef].name ); - - psets[f].triangles = calloc( sizeof( triangle_t ) * pObject->anim.frames[i].numFaces, 1 ); - psets[f].numtriangles = pObject->anim.frames[i].numFaces; - - for ( t = 0; t < pObject->anim.frames[i].numFaces; t++ ) - { - int k; - - for ( k = 0; k < 3; k++ ) - { - psets[f].triangles[t].verts[k][0] = pMesh->vertexes[pMesh->faces[t][k]].x; - psets[f].triangles[t].verts[k][1] = pMesh->vertexes[pMesh->faces[t][k]].y; - psets[f].triangles[t].verts[k][2] = pMesh->vertexes[pMesh->faces[t][k]].z; - - if ( pMesh->tvertexes && pMesh->tfaces ) { - psets[f].triangles[t].texcoords[k][0] = pMesh->tvertexes[pMesh->tfaces[t][k]].s; - psets[f].triangles[t].texcoords[k][1] = pMesh->tvertexes[pMesh->tfaces[t][k]].t; - } - - } - } - - f++; - } - - return psets; -} - -static void ASE_FreeGeomObject( int ndx ){ - aseGeomObject_t *pObject; - int i; - - pObject = &ase.objects[ndx]; - - for ( i = 0; i < pObject->anim.numFrames; i++ ) - { - if ( pObject->anim.frames[i].vertexes ) { - free( pObject->anim.frames[i].vertexes ); - } - if ( pObject->anim.frames[i].tvertexes ) { - free( pObject->anim.frames[i].tvertexes ); - } - if ( pObject->anim.frames[i].faces ) { - free( pObject->anim.frames[i].faces ); - } - if ( pObject->anim.frames[i].tfaces ) { - free( pObject->anim.frames[i].tfaces ); - } - } - - memset( pObject, 0, sizeof( *pObject ) ); -} - -static aseMesh_t *ASE_GetCurrentMesh( void ){ - aseGeomObject_t *pObject; - - if ( ase.currentObject >= MAX_ASE_OBJECTS ) { - Error( "Too many GEOMOBJECTs" ); - return 0; // never called - } - - pObject = &ase.objects[ase.currentObject]; - - if ( pObject->anim.currentFrame >= MAX_ASE_ANIMATION_FRAMES ) { - Error( "Too many MESHes" ); - return 0; - } - - return &pObject->anim.frames[pObject->anim.currentFrame]; -} - -static int CharIsTokenDelimiter( int ch ){ - if ( ch <= 32 ) { - return 1; - } - return 0; -} - -static int ASE_GetToken( qboolean restOfLine ){ - int i = 0; - - if ( ase.buffer == 0 ) { - return 0; - } - - if ( ( ase.curpos - ase.buffer ) == ase.len ) { - return 0; - } - - // skip over crap - while ( ( ( ase.curpos - ase.buffer ) < ase.len ) && - ( *ase.curpos <= 32 ) ) - { - ase.curpos++; - } - - while ( ( ase.curpos - ase.buffer ) < ase.len ) - { - s_token[i] = *ase.curpos; - - ase.curpos++; - i++; - - if ( ( CharIsTokenDelimiter( s_token[i - 1] ) && !restOfLine ) || - ( ( s_token[i - 1] == '\n' ) || ( s_token[i - 1] == '\r' ) ) ) { - s_token[i - 1] = 0; - break; - } - } - - s_token[i] = 0; - - return 1; -} - -static void ASE_ParseBracedBlock( void ( *parser )( const char *token ) ){ - int indent = 0; - - while ( ASE_GetToken( qfalse ) ) - { - if ( !strcmp( s_token, "{" ) ) { - indent++; - } - else if ( !strcmp( s_token, "}" ) ) { - --indent; - if ( indent == 0 ) { - break; - } - else if ( indent < 0 ) { - Error( "Unexpected '}'" ); - } - } - else - { - if ( parser ) { - parser( s_token ); - } - } - } -} - -static void ASE_SkipEnclosingBraces( void ){ - int indent = 0; - - while ( ASE_GetToken( qfalse ) ) - { - if ( !strcmp( s_token, "{" ) ) { - indent++; - } - else if ( !strcmp( s_token, "}" ) ) { - indent--; - if ( indent == 0 ) { - break; - } - else if ( indent < 0 ) { - Error( "Unexpected '}'" ); - } - } - } -} - -static void ASE_SkipRestOfLine( void ){ - ASE_GetToken( qtrue ); -} - -static void ASE_KeyMAP_DIFFUSE( const char *token ){ - char fullpath[1024], bitmap[1024], modeldir[1024]; - char filename[1024]; - int i = 0, count; - - strcpy( filename, gl_filename ); - - if ( !strcmp( token, "*BITMAP" ) ) { - ASE_GetToken( qfalse ); - - // the purpose of this whole chunk of code below is to extract the relative path - // from a full path in the ASE - - strcpy( bitmap, s_token + 1 ); - if ( strchr( bitmap, '"' ) ) { - *strchr( bitmap, '"' ) = 0; - } - - /* convert backslash to slash */ - while ( bitmap[i] ) - { - if ( bitmap[i] == '\\' ) { - bitmap[i] = '/'; - } - i++; - } - - /* remove filename from path */ - for ( i = strlen( filename ); i > 0; i-- ) - { - if ( filename[i] == '/' ) { - filename[i] = '\0'; - break; - } - } - - /* replaces a relative path with a full path */ - if ( bitmap[0] == '.' && bitmap[1] == '.' && bitmap[2] == '/' ) { - while ( bitmap[0] == '.' && bitmap[1] == '.' && bitmap[2] == '/' ) - { - /* remove last item from path */ - for ( i = strlen( filename ); i > 0; i-- ) - { - if ( filename[i] == '/' ) { - filename[i] = '\0'; - break; - } - } - strcpy( bitmap, &bitmap[3] ); - } - strcat( filename, "/" ); - strcat( filename, bitmap ); - strcpy( bitmap, filename ); - } - - if ( strstr( bitmap, gamedir ) ) { - strcpy( ase.materials[ase.numMaterials].name, strstr( bitmap, gamedir ) + strlen( gamedir ) ); - Sys_Printf( "material name: \'%s\'\n", strstr( bitmap, gamedir ) + strlen( gamedir ) ); - } - else - { - sprintf( ase.materials[ase.numMaterials].name, "(not converted: '%s')", bitmap ); - Sys_Printf( "WARNING: illegal material name '%s'\n", bitmap ); - } - } - else - { - } -} - -static void ASE_KeyMATERIAL( const char *token ){ - if ( !strcmp( token, "*MAP_DIFFUSE" ) ) { - ASE_ParseBracedBlock( ASE_KeyMAP_DIFFUSE ); - } - else - { - } -} - -static void ASE_KeyMATERIAL_LIST( const char *token ){ - if ( !strcmp( token, "*MATERIAL_COUNT" ) ) { - ASE_GetToken( qfalse ); - VERBOSE( ( "..num materials: %s\n", s_token ) ); - if ( atoi( s_token ) > MAX_ASE_MATERIALS ) { - Error( "Too many materials!" ); - } - ase.numMaterials = 0; - } - else if ( !strcmp( token, "*MATERIAL" ) ) { - VERBOSE( ( "..material %d ", ase.numMaterials ) ); - ASE_ParseBracedBlock( ASE_KeyMATERIAL ); - ase.numMaterials++; - } -} - -static void ASE_KeyMESH_VERTEX_LIST( const char *token ){ - aseMesh_t *pMesh = ASE_GetCurrentMesh(); - - if ( !strcmp( token, "*MESH_VERTEX" ) ) { - ASE_GetToken( qfalse ); // skip number - - ASE_GetToken( qfalse ); - pMesh->vertexes[pMesh->currentVertex].y = atof( s_token ); - - ASE_GetToken( qfalse ); - pMesh->vertexes[pMesh->currentVertex].x = -atof( s_token ); - - ASE_GetToken( qfalse ); - pMesh->vertexes[pMesh->currentVertex].z = atof( s_token ); - - pMesh->currentVertex++; - - if ( pMesh->currentVertex > pMesh->numVertexes ) { - Error( "pMesh->currentVertex >= pMesh->numVertexes" ); - } - } - else - { - Error( "Unknown token '%s' while parsing MESH_VERTEX_LIST", token ); - } -} - -static void ASE_KeyMESH_FACE_LIST( const char *token ){ - aseMesh_t *pMesh = ASE_GetCurrentMesh(); - - if ( !strcmp( token, "*MESH_FACE" ) ) { - ASE_GetToken( qfalse ); // skip face number - - ASE_GetToken( qfalse ); // skip label - ASE_GetToken( qfalse ); // first vertex - pMesh->faces[pMesh->currentFace][0] = atoi( s_token ); - - ASE_GetToken( qfalse ); // skip label - ASE_GetToken( qfalse ); // second vertex - pMesh->faces[pMesh->currentFace][2] = atoi( s_token ); - - ASE_GetToken( qfalse ); // skip label - ASE_GetToken( qfalse ); // third vertex - pMesh->faces[pMesh->currentFace][1] = atoi( s_token ); - - ASE_GetToken( qtrue ); - -/* - if ( ( p = strstr( s_token, "*MESH_MTLID" ) ) != 0 ) - { - p += strlen( "*MESH_MTLID" ) + 1; - mtlID = atoi( p ); - } - else - { - Error( "No *MESH_MTLID found for face!" ); - } - */ - - pMesh->currentFace++; - } - else - { - Error( "Unknown token '%s' while parsing MESH_FACE_LIST", token ); - } -} - -static void ASE_KeyTFACE_LIST( const char *token ){ - aseMesh_t *pMesh = ASE_GetCurrentMesh(); - - if ( !strcmp( token, "*MESH_TFACE" ) ) { - int a, b, c; - - ASE_GetToken( qfalse ); - - ASE_GetToken( qfalse ); - a = atoi( s_token ); - ASE_GetToken( qfalse ); - c = atoi( s_token ); - ASE_GetToken( qfalse ); - b = atoi( s_token ); - - pMesh->tfaces[pMesh->currentFace][0] = a; - pMesh->tfaces[pMesh->currentFace][1] = b; - pMesh->tfaces[pMesh->currentFace][2] = c; - - pMesh->currentFace++; - } - else - { - Error( "Unknown token '%s' in MESH_TFACE", token ); - } -} - -static void ASE_KeyMESH_TVERTLIST( const char *token ){ - aseMesh_t *pMesh = ASE_GetCurrentMesh(); - - if ( !strcmp( token, "*MESH_TVERT" ) ) { - char u[80], v[80], w[80]; - - ASE_GetToken( qfalse ); - - ASE_GetToken( qfalse ); - strcpy( u, s_token ); - - ASE_GetToken( qfalse ); - strcpy( v, s_token ); - - ASE_GetToken( qfalse ); - strcpy( w, s_token ); - - pMesh->tvertexes[pMesh->currentVertex].s = atof( u ); - pMesh->tvertexes[pMesh->currentVertex].t = 1.0f - atof( v ); - - pMesh->currentVertex++; - - if ( pMesh->currentVertex > pMesh->numTVertexes ) { - Error( "pMesh->currentVertex > pMesh->numTVertexes" ); - } - } - else - { - Error( "Unknown token '%s' while parsing MESH_TVERTLIST" ); - } -} - -static void ASE_KeyMESH( const char *token ){ - aseMesh_t *pMesh = ASE_GetCurrentMesh(); - - if ( !strcmp( token, "*TIMEVALUE" ) ) { - ASE_GetToken( qfalse ); - - pMesh->timeValue = atoi( s_token ); - VERBOSE( ( ".....timevalue: %d\n", pMesh->timeValue ) ); - } - else if ( !strcmp( token, "*MESH_NUMVERTEX" ) ) { - ASE_GetToken( qfalse ); - - pMesh->numVertexes = atoi( s_token ); - VERBOSE( ( ".....TIMEVALUE: %d\n", pMesh->timeValue ) ); - VERBOSE( ( ".....num vertexes: %d\n", pMesh->numVertexes ) ); - } - else if ( !strcmp( token, "*MESH_NUMFACES" ) ) { - ASE_GetToken( qfalse ); - - pMesh->numFaces = atoi( s_token ); - VERBOSE( ( ".....num faces: %d\n", pMesh->numFaces ) ); - } - else if ( !strcmp( token, "*MESH_NUMTVFACES" ) ) { - ASE_GetToken( qfalse ); - - if ( atoi( s_token ) != pMesh->numFaces ) { - Error( "MESH_NUMTVFACES != MESH_NUMFACES" ); - } - } - else if ( !strcmp( token, "*MESH_NUMTVERTEX" ) ) { - ASE_GetToken( qfalse ); - - pMesh->numTVertexes = atoi( s_token ); - VERBOSE( ( ".....num tvertexes: %d\n", pMesh->numTVertexes ) ); - } - else if ( !strcmp( token, "*MESH_VERTEX_LIST" ) ) { - pMesh->vertexes = calloc( sizeof( aseVertex_t ) * pMesh->numVertexes, 1 ); - pMesh->currentVertex = 0; - VERBOSE( ( ".....parsing MESH_VERTEX_LIST\n" ) ); - ASE_ParseBracedBlock( ASE_KeyMESH_VERTEX_LIST ); - } - else if ( !strcmp( token, "*MESH_TVERTLIST" ) ) { - pMesh->currentVertex = 0; - pMesh->tvertexes = calloc( sizeof( aseTVertex_t ) * pMesh->numTVertexes, 1 ); - VERBOSE( ( ".....parsing MESH_TVERTLIST\n" ) ); - ASE_ParseBracedBlock( ASE_KeyMESH_TVERTLIST ); - } - else if ( !strcmp( token, "*MESH_FACE_LIST" ) ) { - pMesh->faces = calloc( sizeof( aseFace_t ) * pMesh->numFaces, 1 ); - pMesh->currentFace = 0; - VERBOSE( ( ".....parsing MESH_FACE_LIST\n" ) ); - ASE_ParseBracedBlock( ASE_KeyMESH_FACE_LIST ); - } - else if ( !strcmp( token, "*MESH_TFACELIST" ) ) { - pMesh->tfaces = calloc( sizeof( aseFace_t ) * pMesh->numFaces, 1 ); - pMesh->currentFace = 0; - VERBOSE( ( ".....parsing MESH_TFACE_LIST\n" ) ); - ASE_ParseBracedBlock( ASE_KeyTFACE_LIST ); - } - else if ( !strcmp( token, "*MESH_NORMALS" ) ) { - ASE_ParseBracedBlock( 0 ); - } -} - -static void ASE_KeyMESH_ANIMATION( const char *token ){ - aseMesh_t *pMesh = ASE_GetCurrentMesh(); - - // loads a single animation frame - if ( !strcmp( token, "*MESH" ) ) { - VERBOSE( ( "...found MESH\n" ) ); - assert( pMesh->faces == 0 ); - assert( pMesh->vertexes == 0 ); - assert( pMesh->tvertexes == 0 ); - memset( pMesh, 0, sizeof( *pMesh ) ); - - ASE_ParseBracedBlock( ASE_KeyMESH ); - - if ( ++ase.objects[ase.currentObject].anim.currentFrame == MAX_ASE_ANIMATION_FRAMES ) { - Error( "Too many animation frames" ); - } - } - else - { - Error( "Unknown token '%s' while parsing MESH_ANIMATION", token ); - } -} - -static void ASE_KeyGEOMOBJECT( const char *token ){ - if ( !strcmp( token, "*NODE_NAME" ) ) { - char *name = ase.objects[ase.currentObject].name; - - ASE_GetToken( qtrue ); - VERBOSE( ( " %s\n", s_token ) ); - strcpy( ase.objects[ase.currentObject].name, s_token + 1 ); - if ( strchr( ase.objects[ase.currentObject].name, '"' ) ) { - *strchr( ase.objects[ase.currentObject].name, '"' ) = 0; - } - - if ( strstr( name, "tag" ) == name ) { - while ( strchr( name, '_' ) != strrchr( name, '_' ) ) - { - *strrchr( name, '_' ) = 0; - } - while ( strrchr( name, ' ' ) ) - { - *strrchr( name, ' ' ) = 0; - } - } - } - else if ( !strcmp( token, "*NODE_PARENT" ) ) { - ASE_SkipRestOfLine(); - } - // ignore unused data blocks - else if ( !strcmp( token, "*NODE_TM" ) || - !strcmp( token, "*TM_ANIMATION" ) ) { - ASE_ParseBracedBlock( 0 ); - } - // ignore regular meshes that aren't part of animation - else if ( !strcmp( token, "*MESH" ) && !ase.grabAnims ) { -/* - if ( strstr( ase.objects[ase.currentObject].name, "tag_" ) == ase.objects[ase.currentObject].name ) - { - s_forceStaticMesh = true; - ASE_ParseBracedBlock( ASE_KeyMESH ); - s_forceStaticMesh = false; - } - */ - ASE_ParseBracedBlock( ASE_KeyMESH ); - if ( ++ase.objects[ase.currentObject].anim.currentFrame == MAX_ASE_ANIMATION_FRAMES ) { - Error( "Too many animation frames" ); - } - ase.objects[ase.currentObject].anim.numFrames = ase.objects[ase.currentObject].anim.currentFrame; - ase.objects[ase.currentObject].numAnimations++; -/* - // ignore meshes that aren't part of animations if this object isn't a - // a tag - else - { - ASE_ParseBracedBlock( 0 ); - } - */ - } - // according to spec these are obsolete - else if ( !strcmp( token, "*MATERIAL_REF" ) ) { - ASE_GetToken( qfalse ); - - ase.objects[ase.currentObject].materialRef = atoi( s_token ); - } - // loads a sequence of animation frames - else if ( !strcmp( token, "*MESH_ANIMATION" ) ) { - if ( ase.grabAnims ) { - VERBOSE( ( "..found MESH_ANIMATION\n" ) ); - - if ( ase.objects[ase.currentObject].numAnimations ) { - Error( "Multiple MESH_ANIMATIONS within a single GEOM_OBJECT" ); - } - ASE_ParseBracedBlock( ASE_KeyMESH_ANIMATION ); - ase.objects[ase.currentObject].anim.numFrames = ase.objects[ase.currentObject].anim.currentFrame; - ase.objects[ase.currentObject].numAnimations++; - } - else - { - ASE_SkipEnclosingBraces(); - } - } - // skip unused info - else if ( !strcmp( token, "*PROP_MOTIONBLUR" ) || - !strcmp( token, "*PROP_CASTSHADOW" ) || - !strcmp( token, "*PROP_RECVSHADOW" ) ) { - ASE_SkipRestOfLine(); - } -} - -static void ConcatenateObjects( aseGeomObject_t *pObjA, aseGeomObject_t *pObjB ){ -} - -static void CollapseObjects( void ){ - int i; - int numObjects = ase.currentObject; - - for ( i = 0; i < numObjects; i++ ) - { - int j; - - // skip tags - if ( strstr( ase.objects[i].name, "tag" ) == ase.objects[i].name ) { - continue; - } - - if ( !ase.objects[i].numAnimations ) { - continue; - } - - for ( j = i + 1; j < numObjects; j++ ) - { - if ( strstr( ase.objects[j].name, "tag" ) == ase.objects[j].name ) { - continue; - } - if ( ase.objects[i].materialRef == ase.objects[j].materialRef ) { - if ( ase.objects[j].numAnimations ) { - ConcatenateObjects( &ase.objects[i], &ase.objects[j] ); - } - } - } - } -} - -/* -** ASE_Process -*/ -static void ASE_Process( void ){ - while ( ASE_GetToken( qfalse ) ) - { - if ( !strcmp( s_token, "*3DSMAX_ASCIIEXPORT" ) || - !strcmp( s_token, "*COMMENT" ) ) { - ASE_SkipRestOfLine(); - } - else if ( !strcmp( s_token, "*SCENE" ) ) { - ASE_SkipEnclosingBraces(); - } - else if ( !strcmp( s_token, "*MATERIAL_LIST" ) ) { - VERBOSE( ( "MATERIAL_LIST\n" ) ); - - ASE_ParseBracedBlock( ASE_KeyMATERIAL_LIST ); - } - else if ( !strcmp( s_token, "*GEOMOBJECT" ) ) { - VERBOSE( ( "GEOMOBJECT" ) ); - - ASE_ParseBracedBlock( ASE_KeyGEOMOBJECT ); - - if ( strstr( ase.objects[ase.currentObject].name, "Bip" ) || - strstr( ase.objects[ase.currentObject].name, "ignore_" ) ) { - ASE_FreeGeomObject( ase.currentObject ); - VERBOSE( ( "(discarding BIP/ignore object)\n" ) ); - } - else if ( ( strstr( ase.objects[ase.currentObject].name, "h_" ) != ase.objects[ase.currentObject].name ) && - ( strstr( ase.objects[ase.currentObject].name, "l_" ) != ase.objects[ase.currentObject].name ) && - ( strstr( ase.objects[ase.currentObject].name, "u_" ) != ase.objects[ase.currentObject].name ) && - ( strstr( ase.objects[ase.currentObject].name, "tag" ) != ase.objects[ase.currentObject].name ) && - ase.grabAnims ) { - VERBOSE( ( "(ignoring improperly labeled object '%s')\n", ase.objects[ase.currentObject].name ) ); - ASE_FreeGeomObject( ase.currentObject ); - } - else - { - if ( ++ase.currentObject == MAX_ASE_OBJECTS ) { - Error( "Too many GEOMOBJECTs" ); - } - } - } - else if ( s_token[0] ) { - Sys_Printf( "Unknown token '%s'\n", s_token ); - } - } - - if ( !ase.currentObject ) { - Error( "No animation data!" ); - } - - CollapseObjects(); -} diff --git a/tools/urt/tools/quake3/common/aselib.h b/tools/urt/tools/quake3/common/aselib.h deleted file mode 100644 index f9a254d..0000000 --- a/tools/urt/tools/quake3/common/aselib.h +++ /dev/null @@ -1,31 +0,0 @@ -/* - Copyright (C) 1999-2007 id Software, Inc. and contributors. - For a list of contributors, see the accompanying CONTRIBUTORS file. - - This file is part of GtkRadiant. - - GtkRadiant is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - GtkRadiant is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with GtkRadiant; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - */ - - -#include "../common/cmdlib.h" -#include "mathlib.h" -#include "polyset.h" - -void ASE_Load( const char *filename, qboolean verbose, qboolean meshanims ); -int ASE_GetNumSurfaces( void ); -polyset_t *ASE_GetSurfaceAnimation( int ndx, int *numFrames, int skipFrameStart, int skipFrameEnd, int maxFrames ); -const char *ASE_GetSurfaceName( int ndx ); -void ASE_Free( void ); diff --git a/tools/urt/tools/quake3/common/bspfile.c b/tools/urt/tools/quake3/common/bspfile.c deleted file mode 100644 index a5d5fba..0000000 --- a/tools/urt/tools/quake3/common/bspfile.c +++ /dev/null @@ -1,709 +0,0 @@ -/* - Copyright (C) 1999-2007 id Software, Inc. and contributors. - For a list of contributors, see the accompanying CONTRIBUTORS file. - - This file is part of GtkRadiant. - - GtkRadiant is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - GtkRadiant is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with GtkRadiant; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - */ - - -#include "cmdlib.h" -#include "mathlib.h" -#include "inout.h" -#include "bspfile.h" -#include "scriplib.h" - -void GetLeafNums( void ); - -//============================================================================= - -int bsp_version = Q3_BSP_VERSION; - -int nummodels; -dmodel_t dmodels[MAX_MAP_MODELS]; - -int numShaders; -dshader_t dshaders[MAX_MAP_SHADERS]; - -int entdatasize; -char dentdata[MAX_MAP_ENTSTRING]; - -int numleafs; -dleaf_t dleafs[MAX_MAP_LEAFS]; - -int numplanes; -dplane_t dplanes[MAX_MAP_PLANES]; - -int numnodes; -dnode_t dnodes[MAX_MAP_NODES]; - -int numleafsurfaces; -int dleafsurfaces[MAX_MAP_LEAFFACES]; - -int numleafbrushes; -int dleafbrushes[MAX_MAP_LEAFBRUSHES]; - -int numbrushes; -dbrush_t dbrushes[MAX_MAP_BRUSHES]; - -int numbrushsides; -dbrushside_t dbrushsides[MAX_MAP_BRUSHSIDES]; - -int numLightBytes; -byte *lightBytes; - -int numGridPoints; -byte *gridData; - -int numVisBytes; -byte visBytes[MAX_MAP_VISIBILITY]; - -int numDrawVerts = 0; -int numDrawVertsBuffer = 0; -drawVert_t *drawVerts = NULL; - -int numDrawIndexes; -int drawIndexes[MAX_MAP_DRAW_INDEXES]; - -int numDrawSurfaces; -int numDrawSurfacesBuffer = 0; -dsurface_t *drawSurfaces = NULL; - -int numFogs; -dfog_t dfogs[MAX_MAP_FOGS]; - -void SetLightBytes( int n ){ - if ( lightBytes != 0 ) { - free( lightBytes ); - } - - numLightBytes = n; - - if ( n == 0 ) { - return; - } - - lightBytes = safe_malloc_info( numLightBytes, "SetLightBytes" ); - - memset( lightBytes, 0, numLightBytes ); -} - -void SetGridPoints( int n ){ - if ( gridData != 0 ) { - free( gridData ); - } - - numGridPoints = n; - - if ( n == 0 ) { - return; - } - - gridData = safe_malloc_info( numGridPoints * 8, "SetGridPoints" ); - - memset( gridData, 0, numGridPoints * 8 ); -} - -void IncDrawVerts(){ - numDrawVerts++; - - if ( drawVerts == 0 ) { - numDrawVertsBuffer = MAX_MAP_DRAW_VERTS / 37; - - drawVerts = safe_malloc_info( sizeof( drawVert_t ) * numDrawVertsBuffer, "IncDrawVerts" ); - - } - else if ( numDrawVerts > numDrawVertsBuffer ) { - numDrawVertsBuffer *= 3; // multiply by 1.5 - numDrawVertsBuffer /= 2; - - if ( numDrawVertsBuffer > MAX_MAP_DRAW_VERTS ) { - numDrawVertsBuffer = MAX_MAP_DRAW_VERTS; - } - - drawVerts = realloc( drawVerts, sizeof( drawVert_t ) * numDrawVertsBuffer ); - - if ( !drawVerts ) { - Error( "realloc() failed (IncDrawVerts)" ); - } - } - - memset( drawVerts + ( numDrawVerts - 1 ), 0, sizeof( drawVert_t ) ); -} - -void SetDrawVerts( int n ){ - if ( drawVerts != 0 ) { - free( drawVerts ); - } - - numDrawVerts = n; - numDrawVertsBuffer = numDrawVerts; - - drawVerts = safe_malloc_info( sizeof( drawVert_t ) * numDrawVertsBuffer, "IncDrawVerts" ); - - memset( drawVerts, 0, n * sizeof( drawVert_t ) ); -} - -void SetDrawSurfacesBuffer(){ - if ( drawSurfaces != 0 ) { - free( drawSurfaces ); - } - - numDrawSurfacesBuffer = MAX_MAP_DRAW_SURFS; - - drawSurfaces = safe_malloc_info( sizeof( dsurface_t ) * numDrawSurfacesBuffer, "IncDrawSurfaces" ); - - memset( drawSurfaces, 0, MAX_MAP_DRAW_SURFS * sizeof( drawVert_t ) ); -} - -void SetDrawSurfaces( int n ){ - if ( drawSurfaces != 0 ) { - free( drawSurfaces ); - } - - numDrawSurfaces = n; - numDrawSurfacesBuffer = numDrawSurfaces; - - drawSurfaces = safe_malloc_info( sizeof( dsurface_t ) * numDrawSurfacesBuffer, "IncDrawSurfaces" ); - - memset( drawSurfaces, 0, n * sizeof( drawVert_t ) ); -} - -void BspFilesCleanup(){ - if ( drawVerts != 0 ) { - free( drawVerts ); - } - if ( drawSurfaces != 0 ) { - free( drawSurfaces ); - } - if ( lightBytes != 0 ) { - free( lightBytes ); - } - if ( gridData != 0 ) { - free( gridData ); - } -} - -//============================================================================= - -/* - ============= - SwapBlock - - If all values are 32 bits, this can be used to swap everything - ============= - */ -void SwapBlock( int *block, int sizeOfBlock ) { - int i; - - sizeOfBlock >>= 2; - for ( i = 0 ; i < sizeOfBlock ; i++ ) { - block[i] = LittleLong( block[i] ); - } -} - -/* - ============= - SwapBSPFile - - Byte swaps all data in a bsp file. - ============= - */ -void SwapBSPFile( void ) { - int i; - - // models - SwapBlock( (int *)dmodels, nummodels * sizeof( dmodels[0] ) ); - - // shaders (don't swap the name) - for ( i = 0 ; i < numShaders ; i++ ) { - dshaders[i].contentFlags = LittleLong( dshaders[i].contentFlags ); - dshaders[i].surfaceFlags = LittleLong( dshaders[i].surfaceFlags ); - } - - // planes - SwapBlock( (int *)dplanes, numplanes * sizeof( dplanes[0] ) ); - - // nodes - SwapBlock( (int *)dnodes, numnodes * sizeof( dnodes[0] ) ); - - // leafs - SwapBlock( (int *)dleafs, numleafs * sizeof( dleafs[0] ) ); - - // leaffaces - SwapBlock( (int *)dleafsurfaces, numleafsurfaces * sizeof( dleafsurfaces[0] ) ); - - // leafbrushes - SwapBlock( (int *)dleafbrushes, numleafbrushes * sizeof( dleafbrushes[0] ) ); - - // brushes - SwapBlock( (int *)dbrushes, numbrushes * sizeof( dbrushes[0] ) ); - - // brushsides - SwapBlock( (int *)dbrushsides, numbrushsides * sizeof( dbrushsides[0] ) ); - - // vis - ( (int *)&visBytes )[0] = LittleLong( ( (int *)&visBytes )[0] ); - ( (int *)&visBytes )[1] = LittleLong( ( (int *)&visBytes )[1] ); - - // drawverts (don't swap colors ) - for ( i = 0 ; i < numDrawVerts ; i++ ) { - drawVerts[i].lightmap[0] = LittleFloat( drawVerts[i].lightmap[0] ); - drawVerts[i].lightmap[1] = LittleFloat( drawVerts[i].lightmap[1] ); - drawVerts[i].st[0] = LittleFloat( drawVerts[i].st[0] ); - drawVerts[i].st[1] = LittleFloat( drawVerts[i].st[1] ); - drawVerts[i].xyz[0] = LittleFloat( drawVerts[i].xyz[0] ); - drawVerts[i].xyz[1] = LittleFloat( drawVerts[i].xyz[1] ); - drawVerts[i].xyz[2] = LittleFloat( drawVerts[i].xyz[2] ); - drawVerts[i].normal[0] = LittleFloat( drawVerts[i].normal[0] ); - drawVerts[i].normal[1] = LittleFloat( drawVerts[i].normal[1] ); - drawVerts[i].normal[2] = LittleFloat( drawVerts[i].normal[2] ); - } - - // drawindexes - SwapBlock( (int *)drawIndexes, numDrawIndexes * sizeof( drawIndexes[0] ) ); - - // drawsurfs - SwapBlock( (int *)drawSurfaces, numDrawSurfaces * sizeof( drawSurfaces[0] ) ); - - // fogs - for ( i = 0 ; i < numFogs ; i++ ) { - dfogs[i].brushNum = LittleLong( dfogs[i].brushNum ); - dfogs[i].visibleSide = LittleLong( dfogs[i].visibleSide ); - } -} - - - -/* - ============= - GetLumpElements - ============= - */ -int GetLumpElements( dheader_t *header, int lump, int size ) { - int length, ofs; - - length = header->lumps[lump].filelen; - ofs = header->lumps[lump].fileofs; - - if ( length % size ) { - Error( "LoadBSPFile: odd lump size" ); - } - - return length / size; -} - -/* - ============= - CopyLump - ============= - */ -int CopyLump( dheader_t *header, int lump, void *dest, int size ) { - int length, ofs; - - length = header->lumps[lump].filelen; - ofs = header->lumps[lump].fileofs; - - if ( length == 0 ) { - return 0; - } - - if ( length % size ) { - Error( "LoadBSPFile: odd lump size" ); - } - - memcpy( dest, (byte *)header + ofs, length ); - - return length / size; -} - -/* - ============= - LoadBSPFile - ============= - */ -void LoadBSPFile( const char *filename ) { - dheader_t *header; - - // load the file header - LoadFile( filename, (void **)&header ); - - // swap the header - SwapBlock( (int *)header, sizeof( *header ) ); - - if ( header->ident != BSP_IDENT ) { - Error( "%s is not a IBSP file", filename ); - } - if ( header->version != bsp_version ) { - Error( "%s is version %i, not %i", filename, header->version, bsp_version ); - } - - numShaders = CopyLump( header, LUMP_SHADERS, dshaders, sizeof( dshader_t ) ); - nummodels = CopyLump( header, LUMP_MODELS, dmodels, sizeof( dmodel_t ) ); - numplanes = CopyLump( header, LUMP_PLANES, dplanes, sizeof( dplane_t ) ); - numleafs = CopyLump( header, LUMP_LEAFS, dleafs, sizeof( dleaf_t ) ); - numnodes = CopyLump( header, LUMP_NODES, dnodes, sizeof( dnode_t ) ); - numleafsurfaces = CopyLump( header, LUMP_LEAFSURFACES, dleafsurfaces, sizeof( dleafsurfaces[0] ) ); - numleafbrushes = CopyLump( header, LUMP_LEAFBRUSHES, dleafbrushes, sizeof( dleafbrushes[0] ) ); - numbrushes = CopyLump( header, LUMP_BRUSHES, dbrushes, sizeof( dbrush_t ) ); - numbrushsides = CopyLump( header, LUMP_BRUSHSIDES, dbrushsides, sizeof( dbrushside_t ) ); - numDrawVerts = GetLumpElements( header, LUMP_DRAWVERTS, sizeof( drawVert_t ) ); - SetDrawVerts( numDrawVerts ); - CopyLump( header, LUMP_DRAWVERTS, drawVerts, sizeof( drawVert_t ) ); - numDrawSurfaces = GetLumpElements( header, LUMP_SURFACES, sizeof( dsurface_t ) ); - SetDrawSurfaces( numDrawSurfaces ); - numDrawSurfaces = CopyLump( header, LUMP_SURFACES, drawSurfaces, sizeof( dsurface_t ) ); - numFogs = CopyLump( header, LUMP_FOGS, dfogs, sizeof( dfog_t ) ); - numDrawIndexes = CopyLump( header, LUMP_DRAWINDEXES, drawIndexes, sizeof( drawIndexes[0] ) ); - - numVisBytes = CopyLump( header, LUMP_VISIBILITY, visBytes, 1 ); - numLightBytes = GetLumpElements( header, LUMP_LIGHTMAPS, 1 ); - SetLightBytes( numLightBytes ); - CopyLump( header, LUMP_LIGHTMAPS, lightBytes, 1 ); - entdatasize = CopyLump( header, LUMP_ENTITIES, dentdata, 1 ); - - numGridPoints = GetLumpElements( header, LUMP_LIGHTGRID, 8 ); - SetGridPoints( numGridPoints ); - CopyLump( header, LUMP_LIGHTGRID, gridData, 8 ); - - - free( header ); // everything has been copied out - - // swap everything - SwapBSPFile(); -} - - -//============================================================================ - -/* - ============= - AddLump - ============= - */ -void AddLump( FILE *bspfile, dheader_t *header, int lumpnum, const void *data, int len ) { - lump_t *lump; - - lump = &header->lumps[lumpnum]; - - lump->fileofs = LittleLong( ftell( bspfile ) ); - lump->filelen = LittleLong( len ); - SafeWrite( bspfile, data, ( len + 3 ) & ~3 ); -} - -/* - ============= - WriteBSPFile - - Swaps the bsp file in place, so it should not be referenced again - ============= - */ -void WriteBSPFile( const char *filename ) { - dheader_t outheader, *header; - FILE *bspfile; - - header = &outheader; - memset( header, 0, sizeof( dheader_t ) ); - - SwapBSPFile(); - - header->ident = LittleLong( BSP_IDENT ); - header->version = LittleLong( bsp_version ); - - bspfile = SafeOpenWrite( filename ); - SafeWrite( bspfile, header, sizeof( dheader_t ) ); // overwritten later - - AddLump( bspfile, header, LUMP_SHADERS, dshaders, numShaders * sizeof( dshader_t ) ); - AddLump( bspfile, header, LUMP_PLANES, dplanes, numplanes * sizeof( dplane_t ) ); - AddLump( bspfile, header, LUMP_LEAFS, dleafs, numleafs * sizeof( dleaf_t ) ); - AddLump( bspfile, header, LUMP_NODES, dnodes, numnodes * sizeof( dnode_t ) ); - AddLump( bspfile, header, LUMP_BRUSHES, dbrushes, numbrushes * sizeof( dbrush_t ) ); - AddLump( bspfile, header, LUMP_BRUSHSIDES, dbrushsides, numbrushsides * sizeof( dbrushside_t ) ); - AddLump( bspfile, header, LUMP_LEAFSURFACES, dleafsurfaces, numleafsurfaces * sizeof( dleafsurfaces[0] ) ); - AddLump( bspfile, header, LUMP_LEAFBRUSHES, dleafbrushes, numleafbrushes * sizeof( dleafbrushes[0] ) ); - AddLump( bspfile, header, LUMP_MODELS, dmodels, nummodels * sizeof( dmodel_t ) ); - AddLump( bspfile, header, LUMP_DRAWVERTS, drawVerts, numDrawVerts * sizeof( drawVert_t ) ); - AddLump( bspfile, header, LUMP_SURFACES, drawSurfaces, numDrawSurfaces * sizeof( dsurface_t ) ); - AddLump( bspfile, header, LUMP_VISIBILITY, visBytes, numVisBytes ); - AddLump( bspfile, header, LUMP_LIGHTMAPS, lightBytes, numLightBytes ); - AddLump( bspfile, header, LUMP_LIGHTGRID, gridData, 8 * numGridPoints ); - AddLump( bspfile, header, LUMP_ENTITIES, dentdata, entdatasize ); - AddLump( bspfile, header, LUMP_FOGS, dfogs, numFogs * sizeof( dfog_t ) ); - AddLump( bspfile, header, LUMP_DRAWINDEXES, drawIndexes, numDrawIndexes * sizeof( drawIndexes[0] ) ); - - fseek( bspfile, 0, SEEK_SET ); - SafeWrite( bspfile, header, sizeof( dheader_t ) ); - fclose( bspfile ); -} - -//============================================================================ - -/* - ============= - PrintBSPFileSizes - - Dumps info about current file - ============= - */ -void PrintBSPFileSizes( void ) { - if ( !num_entities ) { - ParseEntities(); - } - - Sys_Printf( "%6i models %7i\n" - ,nummodels, (int)( nummodels * sizeof( dmodel_t ) ) ); - Sys_Printf( "%6i shaders %7i\n" - ,numShaders, (int)( numShaders * sizeof( dshader_t ) ) ); - Sys_Printf( "%6i brushes %7i\n" - ,numbrushes, (int)( numbrushes * sizeof( dbrush_t ) ) ); - Sys_Printf( "%6i brushsides %7i\n" - ,numbrushsides, (int)( numbrushsides * sizeof( dbrushside_t ) ) ); - Sys_Printf( "%6i fogs %7i\n" - ,numFogs, (int)( numFogs * sizeof( dfog_t ) ) ); - Sys_Printf( "%6i planes %7i\n" - ,numplanes, (int)( numplanes * sizeof( dplane_t ) ) ); - Sys_Printf( "%6i entdata %7i\n", num_entities, entdatasize ); - - Sys_Printf( "\n" ); - - Sys_Printf( "%6i nodes %7i\n" - ,numnodes, (int)( numnodes * sizeof( dnode_t ) ) ); - Sys_Printf( "%6i leafs %7i\n" - ,numleafs, (int)( numleafs * sizeof( dleaf_t ) ) ); - Sys_Printf( "%6i leafsurfaces %7i\n" - ,numleafsurfaces, (int)( numleafsurfaces * sizeof( dleafsurfaces[0] ) ) ); - Sys_Printf( "%6i leafbrushes %7i\n" - ,numleafbrushes, (int)( numleafbrushes * sizeof( dleafbrushes[0] ) ) ); - Sys_Printf( "%6i drawverts %7i\n" - ,numDrawVerts, (int)( numDrawVerts * sizeof( drawVerts[0] ) ) ); - Sys_Printf( "%6i drawindexes %7i\n" - ,numDrawIndexes, (int)( numDrawIndexes * sizeof( drawIndexes[0] ) ) ); - Sys_Printf( "%6i drawsurfaces %7i\n" - ,numDrawSurfaces, (int)( numDrawSurfaces * sizeof( drawSurfaces[0] ) ) ); - - Sys_Printf( "%6i lightmaps %7i\n" - ,numLightBytes / ( LIGHTMAP_WIDTH * LIGHTMAP_HEIGHT * 3 ), numLightBytes ); - Sys_Printf( " visibility %7i\n" - , numVisBytes ); -} - - -//============================================ - -int num_entities; -entity_t entities[MAX_MAP_ENTITIES]; - -void StripTrailing( char *e ) { - char *s; - - s = e + strlen( e ) - 1; - while ( s >= e && *s <= 32 ) - { - *s = 0; - s--; - } -} - -/* - ================= - ParseEpair - ================= - */ -epair_t *ParseEpair( void ) { - epair_t *e; - - e = safe_malloc( sizeof( epair_t ) ); - memset( e, 0, sizeof( epair_t ) ); - - if ( strlen( token ) >= MAX_KEY - 1 ) { - Error( "ParseEpar: token too long" ); - } - e->key = copystring( token ); - GetToken( qfalse ); - if ( strlen( token ) >= MAX_VALUE - 1 ) { - Error( "ParseEpar: token too long" ); - } - e->value = copystring( token ); - - // strip trailing spaces that sometimes get accidentally - // added in the editor - StripTrailing( e->key ); - StripTrailing( e->value ); - - return e; -} - - -/* - ================ - ParseEntity - ================ - */ -qboolean ParseEntity( void ) { - epair_t *e; - entity_t *mapent; - - if ( !GetToken( qtrue ) ) { - return qfalse; - } - - if ( strcmp( token, "{" ) ) { - Error( "ParseEntity: { not found" ); - } - if ( num_entities == MAX_MAP_ENTITIES ) { - Error( "num_entities == MAX_MAP_ENTITIES" ); - } - mapent = &entities[num_entities]; - num_entities++; - - do { - if ( !GetToken( qtrue ) ) { - Error( "ParseEntity: EOF without closing brace" ); - } - if ( !strcmp( token, "}" ) ) { - break; - } - e = ParseEpair(); - e->next = mapent->epairs; - mapent->epairs = e; - } while ( 1 ); - - return qtrue; -} - -/* - ================ - ParseEntities - - Parses the dentdata string into entities - ================ - */ -void ParseEntities( void ) { - num_entities = 0; - ParseFromMemory( dentdata, entdatasize ); - - while ( ParseEntity() ) { - } -} - - -/* - ================ - UnparseEntities - - Generates the dentdata string from all the entities - This allows the utilities to add or remove key/value pairs - to the data created by the map editor. - ================ - */ -void UnparseEntities( void ) { - char *buf, *end; - epair_t *ep; - char line[2048]; - int i; - char key[1024], value[1024]; - - buf = dentdata; - end = buf; - *end = 0; - - for ( i = 0 ; i < num_entities ; i++ ) { - ep = entities[i].epairs; - if ( !ep ) { - continue; // ent got removed - } - - strcat( end,"{\n" ); - end += 2; - - for ( ep = entities[i].epairs ; ep ; ep = ep->next ) { - strcpy( key, ep->key ); - StripTrailing( key ); - strcpy( value, ep->value ); - StripTrailing( value ); - - sprintf( line, "\"%s\" \"%s\"\n", key, value ); - strcat( end, line ); - end += strlen( line ); - } - strcat( end,"}\n" ); - end += 2; - - if ( end > buf + MAX_MAP_ENTSTRING ) { - Error( "Entity text too long" ); - } - } - entdatasize = end - buf + 1; -} - -void PrintEntity( const entity_t *ent ) { - epair_t *ep; - - Sys_Printf( "------- entity %p -------\n", ent ); - for ( ep = ent->epairs ; ep ; ep = ep->next ) { - Sys_Printf( "%s = %s\n", ep->key, ep->value ); - } - -} - -void SetKeyValue( entity_t *ent, const char *key, const char *value ) { - epair_t *ep; - - for ( ep = ent->epairs ; ep ; ep = ep->next ) { - if ( !strcmp( ep->key, key ) ) { - free( ep->value ); - ep->value = copystring( value ); - return; - } - } - ep = safe_malloc( sizeof( *ep ) ); - ep->next = ent->epairs; - ent->epairs = ep; - ep->key = copystring( key ); - ep->value = copystring( value ); -} - -const char *ValueForKey( const entity_t *ent, const char *key ) { - epair_t *ep; - - for ( ep = ent->epairs ; ep ; ep = ep->next ) { - if ( !strcmp( ep->key, key ) ) { - return ep->value; - } - } - return ""; -} - -vec_t FloatForKey( const entity_t *ent, const char *key ) { - const char *k; - - k = ValueForKey( ent, key ); - return atof( k ); -} - -void GetVectorForKey( const entity_t *ent, const char *key, vec3_t vec ) { - const char *k; - double v1, v2, v3; - - k = ValueForKey( ent, key ); - - // scanf into doubles, then assign, so it is vec_t size independent - v1 = v2 = v3 = 0; - sscanf( k, "%lf %lf %lf", &v1, &v2, &v3 ); - vec[0] = v1; - vec[1] = v2; - vec[2] = v3; -} diff --git a/tools/urt/tools/quake3/common/bspfile.h b/tools/urt/tools/quake3/common/bspfile.h deleted file mode 100644 index a6f8679..0000000 --- a/tools/urt/tools/quake3/common/bspfile.h +++ /dev/null @@ -1,120 +0,0 @@ -/* - Copyright (C) 1999-2007 id Software, Inc. and contributors. - For a list of contributors, see the accompanying CONTRIBUTORS file. - - This file is part of GtkRadiant. - - GtkRadiant is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - GtkRadiant is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with GtkRadiant; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - */ - -#include "qfiles.h" -#include "surfaceflags.h" - -extern int bsp_version; - -extern int nummodels; -extern dmodel_t dmodels[MAX_MAP_MODELS]; - -extern int numShaders; -extern dshader_t dshaders[MAX_MAP_MODELS]; - -extern int entdatasize; -extern char dentdata[MAX_MAP_ENTSTRING]; - -extern int numleafs; -extern dleaf_t dleafs[MAX_MAP_LEAFS]; - -extern int numplanes; -extern dplane_t dplanes[MAX_MAP_PLANES]; - -extern int numnodes; -extern dnode_t dnodes[MAX_MAP_NODES]; - -extern int numleafsurfaces; -extern int dleafsurfaces[MAX_MAP_LEAFFACES]; - -extern int numleafbrushes; -extern int dleafbrushes[MAX_MAP_LEAFBRUSHES]; - -extern int numbrushes; -extern dbrush_t dbrushes[MAX_MAP_BRUSHES]; - -extern int numbrushsides; -extern dbrushside_t dbrushsides[MAX_MAP_BRUSHSIDES]; - -void SetLightBytes( int n ); -extern int numLightBytes; -extern byte *lightBytes; - -void SetGridPoints( int n ); -extern int numGridPoints; -extern byte *gridData; - -extern int numVisBytes; -extern byte visBytes[MAX_MAP_VISIBILITY]; - -void SetDrawVerts( int n ); -void IncDrawVerts(); -extern int numDrawVerts; -extern drawVert_t *drawVerts; - -extern int numDrawIndexes; -extern int drawIndexes[MAX_MAP_DRAW_INDEXES]; - -void SetDrawSurfaces( int n ); -void SetDrawSurfacesBuffer(); -extern int numDrawSurfaces; -extern dsurface_t *drawSurfaces; - -extern int numFogs; -extern dfog_t dfogs[MAX_MAP_FOGS]; - -void LoadBSPFile( const char *filename ); -void WriteBSPFile( const char *filename ); -void PrintBSPFileSizes( void ); - -//=============== - - -typedef struct epair_s { - struct epair_s *next; - char *key; - char *value; -} epair_t; - -typedef struct { - vec3_t origin; - struct bspbrush_s *brushes; - struct parseMesh_s *patches; - int firstDrawSurf; - epair_t *epairs; -} entity_t; - -extern int num_entities; -extern entity_t entities[MAX_MAP_ENTITIES]; - -void ParseEntities( void ); -void UnparseEntities( void ); - -void SetKeyValue( entity_t *ent, const char *key, const char *value ); -const char *ValueForKey( const entity_t *ent, const char *key ); -// will return "" if not present - -vec_t FloatForKey( const entity_t *ent, const char *key ); -void GetVectorForKey( const entity_t *ent, const char *key, vec3_t vec ); - -epair_t *ParseEpair( void ); - -void PrintEntity( const entity_t *ent ); diff --git a/tools/urt/tools/quake3/common/cmdlib.c b/tools/urt/tools/quake3/common/cmdlib.c deleted file mode 100644 index 8f1cbf7..0000000 --- a/tools/urt/tools/quake3/common/cmdlib.c +++ /dev/null @@ -1,1117 +0,0 @@ -/* - Copyright (C) 1999-2007 id Software, Inc. and contributors. - For a list of contributors, see the accompanying CONTRIBUTORS file. - - This file is part of GtkRadiant. - - GtkRadiant is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - GtkRadiant is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with GtkRadiant; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - */ - -// cmdlib.c -// TTimo 09/30/2000 -// from an intial copy of common/cmdlib.c -// stripped out the Sys_Printf Sys_Printf stuff - -// SPoG 05/27/2001 -// merging alpha branch into trunk -// replaced qprintf with Sys_Printf - -#include "cmdlib.h" -#include "mathlib.h" -#include "inout.h" -#include -#include - -#ifdef WIN32 -#include -#include -#endif - -#if defined ( __linux__ ) || defined ( __APPLE__ ) -#include -#endif - -#ifdef NeXT -#include -#endif - -#define BASEDIRNAME "quake" // assumed to have a 2 or 3 following -#define PATHSEPERATOR '/' - -#ifdef SAFE_MALLOC -void *safe_malloc( size_t size ){ - void *p; - - p = malloc( size ); - if ( !p ) { - Error( "safe_malloc failed on allocation of %i bytes", size ); - } - - return p; -} - -void *safe_malloc_info( size_t size, char* info ){ - void *p; - - p = malloc( size ); - if ( !p ) { - Error( "%s: safe_malloc failed on allocation of %i bytes", info, size ); - } - - return p; -} -#endif - -// set these before calling CheckParm -int myargc; -char **myargv; - -char com_token[1024]; -qboolean com_eof; - -qboolean archive; -char archivedir[1024]; - - -/* - =================== - ExpandWildcards - - Mimic unix command line expansion - =================== - */ -#define MAX_EX_ARGC 1024 -int ex_argc; -char *ex_argv[MAX_EX_ARGC]; -#ifdef _WIN32 -#include "io.h" -void ExpandWildcards( int *argc, char ***argv ){ - struct _finddata_t fileinfo; - int handle; - int i; - char filename[1024]; - char filebase[1024]; - char *path; - - ex_argc = 0; - for ( i = 0 ; i < *argc ; i++ ) - { - path = ( *argv )[i]; - if ( path[0] == '-' - || ( !strstr( path, "*" ) && !strstr( path, "?" ) ) ) { - ex_argv[ex_argc++] = path; - continue; - } - - handle = _findfirst( path, &fileinfo ); - if ( handle == -1 ) { - return; - } - - ExtractFilePath( path, filebase ); - - do - { - sprintf( filename, "%s%s", filebase, fileinfo.name ); - ex_argv[ex_argc++] = copystring( filename ); - } while ( _findnext( handle, &fileinfo ) != -1 ); - - _findclose( handle ); - } - - *argc = ex_argc; - *argv = ex_argv; -} -#else -void ExpandWildcards( int *argc, char ***argv ){ -} -#endif - -/* - - qdir will hold the path up to the quake directory, including the slash - - f:\quake\ - /raid/quake/ - - gamedir will hold qdir + the game directory (id1, id2, etc) - - */ - -char qdir[1024]; -char gamedir[1024]; -char writedir[1024]; - -void SetQdirFromPath( const char *path ){ - char temp[1024]; - const char *c; - const char *sep; - int len, count; - - if ( !( path[0] == '/' || path[0] == '\\' || path[1] == ':' ) ) { // path is partial - Q_getwd( temp ); - strcat( temp, path ); - path = temp; - } - - // search for "quake2" in path - - len = strlen( BASEDIRNAME ); - for ( c = path + strlen( path ) - 1 ; c != path ; c-- ) - { - int i; - - if ( !Q_strncasecmp( c, BASEDIRNAME, len ) ) { - // - //strncpy (qdir, path, c+len+2-path); - // the +2 assumes a 2 or 3 following quake which is not the - // case with a retail install - // so we need to add up how much to the next separator - sep = c + len; - count = 1; - while ( *sep && *sep != '/' && *sep != '\\' ) - { - sep++; - count++; - } - strncpy( qdir, path, c + len + count - path ); - Sys_Printf( "qdir: %s\n", qdir ); - for ( i = 0; i < strlen( qdir ); i++ ) - { - if ( qdir[i] == '\\' ) { - qdir[i] = '/'; - } - } - - c += len + count; - while ( *c ) - { - if ( *c == '/' || *c == '\\' ) { - strncpy( gamedir, path, c + 1 - path ); - - for ( i = 0; i < strlen( gamedir ); i++ ) - { - if ( gamedir[i] == '\\' ) { - gamedir[i] = '/'; - } - } - - Sys_Printf( "gamedir: %s\n", gamedir ); - - if ( !writedir[0] ) { - strcpy( writedir, gamedir ); - } - else if ( writedir[strlen( writedir ) - 1] != '/' ) { - writedir[strlen( writedir )] = '/'; - writedir[strlen( writedir ) + 1] = 0; - } - - return; - } - c++; - } - Error( "No gamedir in %s", path ); - return; - } - } - Error( "SetQdirFromPath: no '%s' in %s", BASEDIRNAME, path ); -} - -char *ExpandArg( const char *path ){ - static char full[1024]; - - if ( path[0] != '/' && path[0] != '\\' && path[1] != ':' ) { - Q_getwd( full ); - strcat( full, path ); - } - else{ - strcpy( full, path ); - } - return full; -} - -char *ExpandPath( const char *path ){ - static char full[1024]; - if ( !qdir ) { - Error( "ExpandPath called without qdir set" ); - } - if ( path[0] == '/' || path[0] == '\\' || path[1] == ':' ) { - strcpy( full, path ); - return full; - } - sprintf( full, "%s%s", qdir, path ); - return full; -} - -char *ExpandGamePath( const char *path ){ - static char full[1024]; - if ( !qdir ) { - Error( "ExpandGamePath called without qdir set" ); - } - if ( path[0] == '/' || path[0] == '\\' || path[1] == ':' ) { - strcpy( full, path ); - return full; - } - sprintf( full, "%s%s", gamedir, path ); - return full; -} - -char *ExpandPathAndArchive( const char *path ){ - char *expanded; - char archivename[1024]; - - expanded = ExpandPath( path ); - - if ( archive ) { - sprintf( archivename, "%s/%s", archivedir, path ); - QCopyFile( expanded, archivename ); - } - return expanded; -} - - -char *copystring( const char *s ){ - char *b; - b = safe_malloc( strlen( s ) + 1 ); - strcpy( b, s ); - return b; -} - - - -/* - ================ - I_FloatTime - ================ - */ -double I_FloatTime( void ){ - time_t t; - - time( &t ); - - return t; -#if 0 -// more precise, less portable - struct timeval tp; - struct timezone tzp; - static int secbase; - - gettimeofday( &tp, &tzp ); - - if ( !secbase ) { - secbase = tp.tv_sec; - return tp.tv_usec / 1000000.0; - } - - return ( tp.tv_sec - secbase ) + tp.tv_usec / 1000000.0; -#endif -} - -void Q_getwd( char *out ){ - int i = 0; - -#ifdef WIN32 - _getcwd( out, 256 ); - strcat( out, "\\" ); -#else - // Gef: Changed from getwd() to getcwd() to avoid potential buffer overflow - getcwd( out, 256 ); - strcat( out, "/" ); -#endif - while ( out[i] != 0 ) - { - if ( out[i] == '\\' ) { - out[i] = '/'; - } - i++; - } -} - - -void Q_mkdir( const char *path ){ -#ifdef WIN32 - if ( _mkdir( path ) != -1 ) { - return; - } -#else - if ( mkdir( path, 0777 ) != -1 ) { - return; - } -#endif - if ( errno != EEXIST ) { - Error( "mkdir %s: %s",path, strerror( errno ) ); - } -} - -/* - ============ - FileTime - - returns -1 if not present - ============ - */ -int FileTime( const char *path ){ - struct stat buf; - - if ( stat( path,&buf ) == -1 ) { - return -1; - } - - return buf.st_mtime; -} - - - -/* - ============== - COM_Parse - - Parse a token out of a string - ============== - */ -char *COM_Parse( char *data ){ - int c; - int len; - - len = 0; - com_token[0] = 0; - - if ( !data ) { - return NULL; - } - -// skip whitespace -skipwhite: - while ( ( c = *data ) <= ' ' ) - { - if ( c == 0 ) { - com_eof = qtrue; - return NULL; // end of file; - } - data++; - } - -// skip // comments - if ( c == '/' && data[1] == '/' ) { - while ( *data && *data != '\n' ) - data++; - goto skipwhite; - } - - -// handle quoted strings specially - if ( c == '\"' ) { - data++; - do - { - c = *data++; - if ( c == '\"' ) { - com_token[len] = 0; - return data; - } - com_token[len] = c; - len++; - } while ( 1 ); - } - -// parse single characters - if ( c == '{' || c == '}' || c == ')' || c == '(' || c == '\'' || c == ':' ) { - com_token[len] = c; - len++; - com_token[len] = 0; - return data + 1; - } - -// parse a regular word - do - { - com_token[len] = c; - data++; - len++; - c = *data; - if ( c == '{' || c == '}' || c == ')' || c == '(' || c == '\'' || c == ':' ) { - break; - } - } while ( c > 32 ); - - com_token[len] = 0; - return data; -} - -int Q_strncasecmp( const char *s1, const char *s2, int n ){ - int c1, c2; - - do - { - c1 = *s1++; - c2 = *s2++; - - if ( !n-- ) { - return 0; // strings are equal until end point - - } - if ( c1 != c2 ) { - if ( c1 >= 'a' && c1 <= 'z' ) { - c1 -= ( 'a' - 'A' ); - } - if ( c2 >= 'a' && c2 <= 'z' ) { - c2 -= ( 'a' - 'A' ); - } - if ( c1 != c2 ) { - return -1; // strings not equal - } - } - } while ( c1 ); - - return 0; // strings are equal -} - -int Q_stricmp( const char *s1, const char *s2 ){ - return Q_strncasecmp( s1, s2, 99999 ); -} - -// NOTE TTimo when switching to Multithread DLL (Release/Debug) in the config -// started getting warnings about that function, prolly a duplicate with the runtime function -// maybe we still need to have it in linux builds -/* - char *strupr (char *start) - { - char *in; - in = start; - while (*in) - { - *in = toupper(*in); - in++; - } - return start; - } - */ - -char *strlower( char *start ){ - char *in; - in = start; - while ( *in ) - { - *in = tolower( *in ); - in++; - } - return start; -} - - -/* - ============================================================================= - - MISC FUNCTIONS - - ============================================================================= - */ - - -/* - ================= - CheckParm - - Checks for the given parameter in the program's command line arguments - Returns the argument number (1 to argc-1) or 0 if not present - ================= - */ -int CheckParm( const char *check ){ - int i; - - for ( i = 1; i < myargc; i++ ) - { - if ( !Q_stricmp( check, myargv[i] ) ) { - return i; - } - } - - return 0; -} - - - -/* - ================ - Q_filelength - ================ - */ -int Q_filelength( FILE *f ){ - int pos; - int end; - - pos = ftell( f ); - fseek( f, 0, SEEK_END ); - end = ftell( f ); - fseek( f, pos, SEEK_SET ); - - return end; -} - - -FILE *SafeOpenWrite( const char *filename ){ - FILE *f; - - f = fopen( filename, "wb" ); - - if ( !f ) { - Error( "Error opening %s: %s",filename,strerror( errno ) ); - } - - return f; -} - -FILE *SafeOpenRead( const char *filename ){ - FILE *f; - - f = fopen( filename, "rb" ); - - if ( !f ) { - Error( "Error opening %s: %s",filename,strerror( errno ) ); - } - - return f; -} - - -void SafeRead( FILE *f, void *buffer, int count ){ - if ( fread( buffer, 1, count, f ) != (size_t)count ) { - Error( "File read failure" ); - } -} - - -void SafeWrite( FILE *f, const void *buffer, int count ){ - if ( fwrite( buffer, 1, count, f ) != (size_t)count ) { - Error( "File write failure" ); - } -} - - -/* - ============== - FileExists - ============== - */ -qboolean FileExists( const char *filename ){ - FILE *f; - - f = fopen( filename, "r" ); - if ( !f ) { - return qfalse; - } - fclose( f ); - return qtrue; -} - -/* - ============== - LoadFile - ============== - */ -int LoadFile( const char *filename, void **bufferptr ){ - FILE *f; - int length; - void *buffer; - - f = SafeOpenRead( filename ); - length = Q_filelength( f ); - buffer = safe_malloc( length + 1 ); - ( (char *)buffer )[length] = 0; - SafeRead( f, buffer, length ); - fclose( f ); - - *bufferptr = buffer; - return length; -} - - -/* - ============== - LoadFileBlock - - - rounds up memory allocation to 4K boundry - - - ============== - */ -int LoadFileBlock( const char *filename, void **bufferptr ){ - FILE *f; - int length, nBlock, nAllocSize; - void *buffer; - - f = SafeOpenRead( filename ); - length = Q_filelength( f ); - nAllocSize = length; - nBlock = nAllocSize % MEM_BLOCKSIZE; - if ( nBlock > 0 ) { - nAllocSize += MEM_BLOCKSIZE - nBlock; - } - buffer = safe_malloc( nAllocSize + 1 ); - memset( buffer, 0, nAllocSize + 1 ); - SafeRead( f, buffer, length ); - fclose( f ); - - *bufferptr = buffer; - return length; -} - - -/* - ============== - TryLoadFile - - Allows failure - ============== - */ -int TryLoadFile( const char *filename, void **bufferptr ){ - FILE *f; - int length; - void *buffer; - - *bufferptr = NULL; - - f = fopen( filename, "rb" ); - if ( !f ) { - return -1; - } - length = Q_filelength( f ); - buffer = safe_malloc( length + 1 ); - ( (char *)buffer )[length] = 0; - SafeRead( f, buffer, length ); - fclose( f ); - - *bufferptr = buffer; - return length; -} - - -/* - ============== - SaveFile - ============== - */ -void SaveFile( const char *filename, const void *buffer, int count ){ - FILE *f; - - f = SafeOpenWrite( filename ); - SafeWrite( f, buffer, count ); - fclose( f ); -} - - - -void DefaultExtension( char *path, const char *extension ){ - char *src; -// -// if path doesnt have a .EXT, append extension -// (extension should include the .) -// - src = path + strlen( path ) - 1; - - while ( *src != '/' && *src != '\\' && src != path ) - { - if ( *src == '.' ) { - return; // it has an extension - } - src--; - } - - strcat( path, extension ); -} - - -void DefaultPath( char *path, const char *basepath ){ - char temp[128]; - - if ( path[ 0 ] == '/' || path[ 0 ] == '\\' ) { - return; // absolute path location - } - strcpy( temp,path ); - strcpy( path,basepath ); - strcat( path,temp ); -} - - -void StripFilename( char *path ){ - int length; - - length = strlen( path ) - 1; - while ( length > 0 && path[length] != '/' && path[ length ] != '\\' ) - length--; - path[length] = 0; -} - -void StripExtension( char *path ){ - int length; - - length = strlen( path ) - 1; - while ( length > 0 && path[length] != '.' ) - { - length--; - if ( path[length] == '/' || path[ length ] == '\\' ) { - return; // no extension - } - } - if ( length ) { - path[length] = 0; - } -} - - -/* - ==================== - Extract file parts - ==================== - */ -// FIXME: should include the slash, otherwise -// backing to an empty path will be wrong when appending a slash -void ExtractFilePath( const char *path, char *dest ){ - const char *src; - - src = path + strlen( path ) - 1; - -// -// back up until a \ or the start -// - while ( src != path && *( src - 1 ) != '\\' && *( src - 1 ) != '/' ) - src--; - - memcpy( dest, path, src - path ); - dest[src - path] = 0; -} - -void ExtractFileBase( const char *path, char *dest ){ - const char *src; - - src = path + strlen( path ) - 1; - -// -// back up until a \ or the start -// - while ( src != path && *( src - 1 ) != '/' && *( src - 1 ) != '\\' ) - src--; - - while ( *src && *src != '.' ) - { - *dest++ = *src++; - } - *dest = 0; -} - -void ExtractFileExtension( const char *path, char *dest ){ - const char *src; - - src = path + strlen( path ) - 1; - -// -// back up until a . or the start -// - while ( src != path && *( src - 1 ) != '.' ) - src--; - if ( src == path ) { - *dest = 0; // no extension - return; - } - - strcpy( dest,src ); -} - - -/* - ============== - ParseNum / ParseHex - ============== - */ -int ParseHex( const char *hex ){ - const char *str; - int num; - - num = 0; - str = hex; - - while ( *str ) - { - num <<= 4; - if ( *str >= '0' && *str <= '9' ) { - num += *str - '0'; - } - else if ( *str >= 'a' && *str <= 'f' ) { - num += 10 + *str - 'a'; - } - else if ( *str >= 'A' && *str <= 'F' ) { - num += 10 + *str - 'A'; - } - else{ - Error( "Bad hex number: %s",hex ); - } - str++; - } - - return num; -} - - -int ParseNum( const char *str ){ - if ( str[0] == '$' ) { - return ParseHex( str + 1 ); - } - if ( str[0] == '0' && str[1] == 'x' ) { - return ParseHex( str + 2 ); - } - return atol( str ); -} - - - -/* - ============================================================================ - - BYTE ORDER FUNCTIONS - - ============================================================================ - */ - -#ifdef _SGI_SOURCE -#define __BIG_ENDIAN__ -#endif - -#ifdef __BIG_ENDIAN__ - -short LittleShort( short l ){ - byte b1,b2; - - b1 = l & 255; - b2 = ( l >> 8 ) & 255; - - return ( b1 << 8 ) + b2; -} - -short BigShort( short l ){ - return l; -} - - -int LittleLong( int l ){ - byte b1,b2,b3,b4; - - b1 = l & 255; - b2 = ( l >> 8 ) & 255; - b3 = ( l >> 16 ) & 255; - b4 = ( l >> 24 ) & 255; - - return ( (int)b1 << 24 ) + ( (int)b2 << 16 ) + ( (int)b3 << 8 ) + b4; -} - -int BigLong( int l ){ - return l; -} - - -float LittleFloat( float l ){ - union {byte b[4]; float f; } in, out; - - in.f = l; - out.b[0] = in.b[3]; - out.b[1] = in.b[2]; - out.b[2] = in.b[1]; - out.b[3] = in.b[0]; - - return out.f; -} - -float BigFloat( float l ){ - return l; -} - - -#else - - -short BigShort( short l ){ - byte b1,b2; - - b1 = l & 255; - b2 = ( l >> 8 ) & 255; - - return ( b1 << 8 ) + b2; -} - -short LittleShort( short l ){ - return l; -} - - -int BigLong( int l ){ - byte b1,b2,b3,b4; - - b1 = l & 255; - b2 = ( l >> 8 ) & 255; - b3 = ( l >> 16 ) & 255; - b4 = ( l >> 24 ) & 255; - - return ( (int)b1 << 24 ) + ( (int)b2 << 16 ) + ( (int)b3 << 8 ) + b4; -} - -int LittleLong( int l ){ - return l; -} - -float BigFloat( float l ){ - union {byte b[4]; float f; } in, out; - - in.f = l; - out.b[0] = in.b[3]; - out.b[1] = in.b[2]; - out.b[2] = in.b[1]; - out.b[3] = in.b[0]; - - return out.f; -} - -float LittleFloat( float l ){ - return l; -} - - -#endif - - -//======================================================= - - -// FIXME: byte swap? - -// this is a 16 bit, non-reflected CRC using the polynomial 0x1021 -// and the initial and final xor values shown below... in other words, the -// CCITT standard CRC used by XMODEM - -#define CRC_INIT_VALUE 0xffff -#define CRC_XOR_VALUE 0x0000 - -static unsigned short crctable[256] = -{ - 0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50a5, 0x60c6, 0x70e7, - 0x8108, 0x9129, 0xa14a, 0xb16b, 0xc18c, 0xd1ad, 0xe1ce, 0xf1ef, - 0x1231, 0x0210, 0x3273, 0x2252, 0x52b5, 0x4294, 0x72f7, 0x62d6, - 0x9339, 0x8318, 0xb37b, 0xa35a, 0xd3bd, 0xc39c, 0xf3ff, 0xe3de, - 0x2462, 0x3443, 0x0420, 0x1401, 0x64e6, 0x74c7, 0x44a4, 0x5485, - 0xa56a, 0xb54b, 0x8528, 0x9509, 0xe5ee, 0xf5cf, 0xc5ac, 0xd58d, - 0x3653, 0x2672, 0x1611, 0x0630, 0x76d7, 0x66f6, 0x5695, 0x46b4, - 0xb75b, 0xa77a, 0x9719, 0x8738, 0xf7df, 0xe7fe, 0xd79d, 0xc7bc, - 0x48c4, 0x58e5, 0x6886, 0x78a7, 0x0840, 0x1861, 0x2802, 0x3823, - 0xc9cc, 0xd9ed, 0xe98e, 0xf9af, 0x8948, 0x9969, 0xa90a, 0xb92b, - 0x5af5, 0x4ad4, 0x7ab7, 0x6a96, 0x1a71, 0x0a50, 0x3a33, 0x2a12, - 0xdbfd, 0xcbdc, 0xfbbf, 0xeb9e, 0x9b79, 0x8b58, 0xbb3b, 0xab1a, - 0x6ca6, 0x7c87, 0x4ce4, 0x5cc5, 0x2c22, 0x3c03, 0x0c60, 0x1c41, - 0xedae, 0xfd8f, 0xcdec, 0xddcd, 0xad2a, 0xbd0b, 0x8d68, 0x9d49, - 0x7e97, 0x6eb6, 0x5ed5, 0x4ef4, 0x3e13, 0x2e32, 0x1e51, 0x0e70, - 0xff9f, 0xefbe, 0xdfdd, 0xcffc, 0xbf1b, 0xaf3a, 0x9f59, 0x8f78, - 0x9188, 0x81a9, 0xb1ca, 0xa1eb, 0xd10c, 0xc12d, 0xf14e, 0xe16f, - 0x1080, 0x00a1, 0x30c2, 0x20e3, 0x5004, 0x4025, 0x7046, 0x6067, - 0x83b9, 0x9398, 0xa3fb, 0xb3da, 0xc33d, 0xd31c, 0xe37f, 0xf35e, - 0x02b1, 0x1290, 0x22f3, 0x32d2, 0x4235, 0x5214, 0x6277, 0x7256, - 0xb5ea, 0xa5cb, 0x95a8, 0x8589, 0xf56e, 0xe54f, 0xd52c, 0xc50d, - 0x34e2, 0x24c3, 0x14a0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405, - 0xa7db, 0xb7fa, 0x8799, 0x97b8, 0xe75f, 0xf77e, 0xc71d, 0xd73c, - 0x26d3, 0x36f2, 0x0691, 0x16b0, 0x6657, 0x7676, 0x4615, 0x5634, - 0xd94c, 0xc96d, 0xf90e, 0xe92f, 0x99c8, 0x89e9, 0xb98a, 0xa9ab, - 0x5844, 0x4865, 0x7806, 0x6827, 0x18c0, 0x08e1, 0x3882, 0x28a3, - 0xcb7d, 0xdb5c, 0xeb3f, 0xfb1e, 0x8bf9, 0x9bd8, 0xabbb, 0xbb9a, - 0x4a75, 0x5a54, 0x6a37, 0x7a16, 0x0af1, 0x1ad0, 0x2ab3, 0x3a92, - 0xfd2e, 0xed0f, 0xdd6c, 0xcd4d, 0xbdaa, 0xad8b, 0x9de8, 0x8dc9, - 0x7c26, 0x6c07, 0x5c64, 0x4c45, 0x3ca2, 0x2c83, 0x1ce0, 0x0cc1, - 0xef1f, 0xff3e, 0xcf5d, 0xdf7c, 0xaf9b, 0xbfba, 0x8fd9, 0x9ff8, - 0x6e17, 0x7e36, 0x4e55, 0x5e74, 0x2e93, 0x3eb2, 0x0ed1, 0x1ef0 -}; - -void CRC_Init( unsigned short *crcvalue ){ - *crcvalue = CRC_INIT_VALUE; -} - -void CRC_ProcessByte( unsigned short *crcvalue, byte data ){ - *crcvalue = ( *crcvalue << 8 ) ^ crctable[( *crcvalue >> 8 ) ^ data]; -} - -unsigned short CRC_Value( unsigned short crcvalue ){ - return crcvalue ^ CRC_XOR_VALUE; -} -//============================================================================= - -/* - ============ - CreatePath - ============ - */ -void CreatePath( const char *path ){ - const char *ofs; - char c; - char dir[1024]; - -#ifdef _WIN32 - int olddrive = -1; - - if ( path[1] == ':' ) { - olddrive = _getdrive(); - _chdrive( toupper( path[0] ) - 'A' + 1 ); - } -#endif - - if ( path[1] == ':' ) { - path += 2; - } - - for ( ofs = path + 1 ; *ofs ; ofs++ ) - { - c = *ofs; - if ( c == '/' || c == '\\' ) { // create the directory - memcpy( dir, path, ofs - path ); - dir[ ofs - path ] = 0; - Q_mkdir( dir ); - } - } - -#ifdef _WIN32 - if ( olddrive != -1 ) { - _chdrive( olddrive ); - } -#endif -} - - -/* - ============ - QCopyFile - - Used to archive source files - ============ - */ -void QCopyFile( const char *from, const char *to ){ - void *buffer; - int length; - - length = LoadFile( from, &buffer ); - CreatePath( to ); - SaveFile( to, buffer, length ); - free( buffer ); -} - -void Sys_Sleep( int n ){ -#ifdef WIN32 - Sleep( n ); -#endif -#if defined ( __linux__ ) || defined ( __APPLE__ ) - usleep( n * 1000 ); -#endif -} diff --git a/tools/urt/tools/quake3/common/cmdlib.h b/tools/urt/tools/quake3/common/cmdlib.h deleted file mode 100644 index e7b555b..0000000 --- a/tools/urt/tools/quake3/common/cmdlib.h +++ /dev/null @@ -1,160 +0,0 @@ -/* - Copyright (C) 1999-2007 id Software, Inc. and contributors. - For a list of contributors, see the accompanying CONTRIBUTORS file. - - This file is part of GtkRadiant. - - GtkRadiant is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - GtkRadiant is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with GtkRadiant; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - */ - -// cmdlib.h - -#ifndef __CMDLIB__ -#define __CMDLIB__ - -#include "bytebool.h" - -#ifdef _WIN32 -#pragma warning(disable : 4244) // MIPS -#pragma warning(disable : 4136) // X86 -#pragma warning(disable : 4051) // ALPHA - -#pragma warning(disable : 4018) // signed/unsigned mismatch -#pragma warning(disable : 4305) // truncate from double to float - -#pragma check_stack(off) - -#endif - -#include -#include -#include -#include -#include -#include -#include - -#ifdef _WIN32 - -#pragma intrinsic( memset, memcpy ) - -#endif - - -#define MAX_OS_PATH 1024 -#define MEM_BLOCKSIZE 4096 - -// the dec offsetof macro doesnt work very well... -#define myoffsetof( type,identifier ) ( (size_t)& ( (type *)0 )->identifier ) - -#define SAFE_MALLOC -#ifdef SAFE_MALLOC -void *safe_malloc( size_t size ); -void *safe_malloc_info( size_t size, char* info ); -#else -#define safe_malloc( a ) malloc( a ) -#endif /* SAFE_MALLOC */ - -// set these before calling CheckParm -extern int myargc; -extern char **myargv; - -char *strlower( char *in ); -int Q_strncasecmp( const char *s1, const char *s2, int n ); -int Q_stricmp( const char *s1, const char *s2 ); -void Q_getwd( char *out ); - -int Q_filelength( FILE *f ); -int FileTime( const char *path ); - -void Q_mkdir( const char *path ); - -extern char qdir[1024]; -extern char gamedir[1024]; -extern char writedir[1024]; -extern char *moddirparam; -void SetQdirFromPath( const char *path ); -char *ExpandArg( const char *path ); // from cmd line -char *ExpandPath( const char *path ); // from scripts -char *ExpandGamePath( const char *path ); -char *ExpandPathAndArchive( const char *path ); -void ExpandWildcards( int *argc, char ***argv ); - - -double I_FloatTime( void ); - -void Error( const char *error, ... ); -int CheckParm( const char *check ); - -FILE *SafeOpenWrite( const char *filename ); -FILE *SafeOpenRead( const char *filename ); -void SafeRead( FILE *f, void *buffer, int count ); -void SafeWrite( FILE *f, const void *buffer, int count ); - -int LoadFile( const char *filename, void **bufferptr ); -int LoadFileBlock( const char *filename, void **bufferptr ); -int TryLoadFile( const char *filename, void **bufferptr ); -void SaveFile( const char *filename, const void *buffer, int count ); -qboolean FileExists( const char *filename ); - -void DefaultExtension( char *path, const char *extension ); -void DefaultPath( char *path, const char *basepath ); -void StripFilename( char *path ); -void StripExtension( char *path ); - -void ExtractFilePath( const char *path, char *dest ); -void ExtractFileBase( const char *path, char *dest ); -void ExtractFileExtension( const char *path, char *dest ); - -int ParseNum( const char *str ); - -short BigShort( short l ); -short LittleShort( short l ); -int BigLong( int l ); -int LittleLong( int l ); -float BigFloat( float l ); -float LittleFloat( float l ); - - -char *COM_Parse( char *data ); - -extern char com_token[1024]; -extern qboolean com_eof; - -char *copystring( const char *s ); - - -void CRC_Init( unsigned short *crcvalue ); -void CRC_ProcessByte( unsigned short *crcvalue, byte data ); -unsigned short CRC_Value( unsigned short crcvalue ); - -void CreatePath( const char *path ); -void QCopyFile( const char *from, const char *to ); - -extern qboolean archive; -extern char archivedir[1024]; - -// sleep for the given amount of milliseconds -void Sys_Sleep( int n ); - -// for compression routines -typedef struct -{ - void *data; - int count, width, height; -} cblock_t; - - -#endif diff --git a/tools/urt/tools/quake3/common/glib-object.h b/tools/urt/tools/quake3/common/glib-object.h deleted file mode 100644 index 974f714..0000000 --- a/tools/urt/tools/quake3/common/glib-object.h +++ /dev/null @@ -1,41 +0,0 @@ -/* GObject - GLib Type, Object, Parameter and Signal Library - * Copyright (C) 1998, 1999, 2000 Tim Janik and Red Hat, Inc. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General - * Public License along with this library; if not, write to the - * Free Software Foundation, Inc., 59 Temple Place, Suite 330, - * Boston, MA 02111-1307, USA. - */ -#ifndef __GLIB_GOBJECT_H__ -#define __GLIB_GOBJECT_H__ - -#define __GLIB_GOBJECT_H_INSIDE__ - -/* topmost include file for GObject header files */ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#undef __GLIB_GOBJECT_H_INSIDE__ - -#endif /* __GLIB_GOBJECT_H__ */ diff --git a/tools/urt/tools/quake3/common/glib.h b/tools/urt/tools/quake3/common/glib.h deleted file mode 100644 index d2122b2..0000000 --- a/tools/urt/tools/quake3/common/glib.h +++ /dev/null @@ -1,77 +0,0 @@ -/* GLIB - Library of useful routines for C programming - * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the - * Free Software Foundation, Inc., 59 Temple Place - Suite 330, - * Boston, MA 02111-1307, USA. - */ - -/* - * Modified by the GLib Team and others 1997-2000. See the AUTHORS - * file for a list of people on the GLib Team. See the ChangeLog - * files for a list of changes. These files are distributed with - * GLib at ftp://ftp.gtk.org/pub/gtk/. - */ - -#ifndef __G_LIB_H__ -#define __G_LIB_H__ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#ifdef G_PLATFORM_WIN32 -#include -#endif - -#endif /* __G_LIB_H__ */ diff --git a/tools/urt/tools/quake3/common/glib/galloca.h b/tools/urt/tools/quake3/common/glib/galloca.h deleted file mode 100644 index f0616d7..0000000 --- a/tools/urt/tools/quake3/common/glib/galloca.h +++ /dev/null @@ -1,60 +0,0 @@ -/* GLIB - Library of useful routines for C programming - * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the - * Free Software Foundation, Inc., 59 Temple Place - Suite 330, - * Boston, MA 02111-1307, USA. - */ - -/* - * Modified by the GLib Team and others 1997-2000. See the AUTHORS - * file for a list of people on the GLib Team. See the ChangeLog - * files for a list of changes. These files are distributed with - * GLib at ftp://ftp.gtk.org/pub/gtk/. - */ - -#ifndef __G_ALLOCA_H__ -#define __G_ALLOCA_H__ - -#include - -#ifdef __GNUC__ -/* GCC does the right thing */ -# undef alloca -# define alloca( size ) __builtin_alloca( size ) -#elif defined ( GLIB_HAVE_ALLOCA_H ) -/* a native and working alloca.h is there */ -# include -#else /* !__GNUC__ && !GLIB_HAVE_ALLOCA_H */ -# ifdef _MSC_VER -# include -# define alloca _alloca -# else /* !_MSC_VER */ -# ifdef _AIX -# pragma alloca -# else /* !_AIX */ -# ifndef alloca /* predefined by HP cc +Olibcalls */ -G_BEGIN_DECLS -char *alloca(); -G_END_DECLS -# endif /* !alloca */ -# endif /* !_AIX */ -# endif /* !_MSC_VER */ -#endif /* !__GNUC__ && !GLIB_HAVE_ALLOCA_H */ - -#define g_alloca( size ) alloca( size ) -#define g_newa( struct_type, n_structs ) ( (struct_type*) g_alloca( sizeof( struct_type ) * (gsize) ( n_structs ) ) ) - - -#endif /* __G_ALLOCA_H__ */ diff --git a/tools/urt/tools/quake3/common/glib/garray.h b/tools/urt/tools/quake3/common/glib/garray.h deleted file mode 100644 index f6bb3ae..0000000 --- a/tools/urt/tools/quake3/common/glib/garray.h +++ /dev/null @@ -1,166 +0,0 @@ -/* GLIB - Library of useful routines for C programming - * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the - * Free Software Foundation, Inc., 59 Temple Place - Suite 330, - * Boston, MA 02111-1307, USA. - */ - -/* - * Modified by the GLib Team and others 1997-2000. See the AUTHORS - * file for a list of people on the GLib Team. See the ChangeLog - * files for a list of changes. These files are distributed with - * GLib at ftp://ftp.gtk.org/pub/gtk/. - */ - -#ifndef __G_ARRAY_H__ -#define __G_ARRAY_H__ - -#include - -G_BEGIN_DECLS - -typedef struct _GArray GArray; -typedef struct _GByteArray GByteArray; -typedef struct _GPtrArray GPtrArray; - -struct _GArray -{ - gchar *data; - guint len; -}; - -struct _GByteArray -{ - guint8 *data; - guint len; -}; - -struct _GPtrArray -{ - gpointer *pdata; - guint len; -}; - -/* Resizable arrays. remove fills any cleared spot and shortens the - * array, while preserving the order. remove_fast will distort the - * order by moving the last element to the position of the removed. - */ - -#define g_array_append_val( a,v ) g_array_append_vals( a, & ( v ), 1 ) -#define g_array_prepend_val( a,v ) g_array_prepend_vals( a, & ( v ), 1 ) -#define g_array_insert_val( a,i,v ) g_array_insert_vals( a, i, & ( v ), 1 ) -#define g_array_index( a,t,i ) ( ( (t*) ( a )->data ) [( i )] ) - -GArray* g_array_new( gboolean zero_terminated, - gboolean clear_, - guint element_size ); -GArray* g_array_sized_new( gboolean zero_terminated, - gboolean clear_, - guint element_size, - guint reserved_size ); -gchar* g_array_free( GArray *array, - gboolean free_segment ); -GArray* g_array_append_vals( GArray *array, - gconstpointer data, - guint len ); -GArray* g_array_prepend_vals( GArray *array, - gconstpointer data, - guint len ); -GArray* g_array_insert_vals( GArray *array, - guint index_, - gconstpointer data, - guint len ); -GArray* g_array_set_size( GArray *array, - guint length ); -GArray* g_array_remove_index( GArray *array, - guint index_ ); -GArray* g_array_remove_index_fast( GArray *array, - guint index_ ); -GArray* g_array_remove_range( GArray *array, - guint index_, - guint length ); -void g_array_sort( GArray *array, - GCompareFunc compare_func ); -void g_array_sort_with_data( GArray *array, - GCompareDataFunc compare_func, - gpointer user_data ); - -/* Resizable pointer array. This interface is much less complicated - * than the above. Add appends a pointer. Remove fills any cleared - * spot and shortens the array. remove_fast will again distort order. - */ -#define g_ptr_array_index( array,index_ ) ( ( array )->pdata )[index_] -GPtrArray* g_ptr_array_new( void ); -GPtrArray* g_ptr_array_sized_new( guint reserved_size ); -gpointer* g_ptr_array_free( GPtrArray *array, - gboolean free_seg ); -void g_ptr_array_set_size( GPtrArray *array, - gint length ); -gpointer g_ptr_array_remove_index( GPtrArray *array, - guint index_ ); -gpointer g_ptr_array_remove_index_fast( GPtrArray *array, - guint index_ ); -gboolean g_ptr_array_remove( GPtrArray *array, - gpointer data ); -gboolean g_ptr_array_remove_fast( GPtrArray *array, - gpointer data ); -void g_ptr_array_remove_range( GPtrArray *array, - guint index_, - guint length ); -void g_ptr_array_add( GPtrArray *array, - gpointer data ); -void g_ptr_array_sort( GPtrArray *array, - GCompareFunc compare_func ); -void g_ptr_array_sort_with_data( GPtrArray *array, - GCompareDataFunc compare_func, - gpointer user_data ); -void g_ptr_array_foreach( GPtrArray *array, - GFunc func, - gpointer user_data ); - - -/* Byte arrays, an array of guint8. Implemented as a GArray, - * but type-safe. - */ - -GByteArray* g_byte_array_new( void ); -GByteArray* g_byte_array_sized_new( guint reserved_size ); -guint8* g_byte_array_free( GByteArray *array, - gboolean free_segment ); -GByteArray* g_byte_array_append( GByteArray *array, - const guint8 *data, - guint len ); -GByteArray* g_byte_array_prepend( GByteArray *array, - const guint8 *data, - guint len ); -GByteArray* g_byte_array_set_size( GByteArray *array, - guint length ); -GByteArray* g_byte_array_remove_index( GByteArray *array, - guint index_ ); -GByteArray* g_byte_array_remove_index_fast( GByteArray *array, - guint index_ ); -GByteArray* g_byte_array_remove_range( GByteArray *array, - guint index_, - guint length ); -void g_byte_array_sort( GByteArray *array, - GCompareFunc compare_func ); -void g_byte_array_sort_with_data( GByteArray *array, - GCompareDataFunc compare_func, - gpointer user_data ); - - -G_END_DECLS - -#endif /* __G_ARRAY_H__ */ diff --git a/tools/urt/tools/quake3/common/glib/gasyncqueue.h b/tools/urt/tools/quake3/common/glib/gasyncqueue.h deleted file mode 100644 index 194ad69..0000000 --- a/tools/urt/tools/quake3/common/glib/gasyncqueue.h +++ /dev/null @@ -1,91 +0,0 @@ -/* GLIB - Library of useful routines for C programming - * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the - * Free Software Foundation, Inc., 59 Temple Place - Suite 330, - * Boston, MA 02111-1307, USA. - */ - -/* - * Modified by the GLib Team and others 1997-2000. See the AUTHORS - * file for a list of people on the GLib Team. See the ChangeLog - * files for a list of changes. These files are distributed with - * GLib at ftp://ftp.gtk.org/pub/gtk/. - */ - -#ifndef __G_ASYNCQUEUE_H__ -#define __G_ASYNCQUEUE_H__ - -#include - -G_BEGIN_DECLS - -typedef struct _GAsyncQueue GAsyncQueue; - -/* Asyncronous Queues, can be used to communicate between threads - */ - -/* Get a new GAsyncQueue with the ref_count 1 */ -GAsyncQueue* g_async_queue_new( void ); - -/* Lock and unlock a GAsyncQueue. All functions lock the queue for - * themselves, but in certain cirumstances you want to hold the lock longer, - * thus you lock the queue, call the *_unlocked functions and unlock it again. - */ -void g_async_queue_lock( GAsyncQueue *queue ); -void g_async_queue_unlock( GAsyncQueue *queue ); - -/* Ref and unref the GAsyncQueue. */ -void g_async_queue_ref( GAsyncQueue *queue ); -void g_async_queue_unref( GAsyncQueue *queue ); -#ifndef G_DISABLE_DEPRECATED -/* You don't have to hold the lock for calling *_ref and *_unref anymore. */ -void g_async_queue_ref_unlocked( GAsyncQueue *queue ); -void g_async_queue_unref_and_unlock( GAsyncQueue *queue ); -#endif /* !G_DISABLE_DEPRECATED */ - -/* Push data into the async queue. Must not be NULL. */ -void g_async_queue_push( GAsyncQueue *queue, - gpointer data ); -void g_async_queue_push_unlocked( GAsyncQueue *queue, - gpointer data ); - -/* Pop data from the async queue. When no data is there, the thread is blocked - * until data arrives. */ -gpointer g_async_queue_pop( GAsyncQueue *queue ); -gpointer g_async_queue_pop_unlocked( GAsyncQueue *queue ); - -/* Try to pop data. NULL is returned in case of empty queue. */ -gpointer g_async_queue_try_pop( GAsyncQueue *queue ); -gpointer g_async_queue_try_pop_unlocked( GAsyncQueue *queue ); - -/* Wait for data until at maximum until end_time is reached. NULL is returned - * in case of empty queue. */ -gpointer g_async_queue_timed_pop( GAsyncQueue *queue, - GTimeVal *end_time ); -gpointer g_async_queue_timed_pop_unlocked( GAsyncQueue *queue, - GTimeVal *end_time ); - -/* Return the length of the queue. Negative values mean that threads - * are waiting, positve values mean that there are entries in the - * queue. Actually this function returns the length of the queue minus - * the number of waiting threads, g_async_queue_length == 0 could also - * mean 'n' entries in the queue and 'n' thread waiting. Such can - * happen due to locking of the queue or due to scheduling. */ -gint g_async_queue_length( GAsyncQueue *queue ); -gint g_async_queue_length_unlocked( GAsyncQueue *queue ); - -G_END_DECLS - -#endif /* __G_ASYNCQUEUE_H__ */ diff --git a/tools/urt/tools/quake3/common/glib/gatomic.h b/tools/urt/tools/quake3/common/glib/gatomic.h deleted file mode 100644 index 44e0489..0000000 --- a/tools/urt/tools/quake3/common/glib/gatomic.h +++ /dev/null @@ -1,62 +0,0 @@ -/* GLIB - Library of useful routines for C programming - * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald - * - * g_atomic_*: atomic operations. - * Copyright (C) 2003 Sebastian Wilhelmi - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the - * Free Software Foundation, Inc., 59 Temple Place - Suite 330, - * Boston, MA 02111-1307, USA. - */ - -/* - * Modified by the GLib Team and others 1997-2000. See the AUTHORS - * file for a list of people on the GLib Team. See the ChangeLog - * files for a list of changes. These files are distributed with - * GLib at ftp://ftp.gtk.org/pub/gtk/. - */ - -#ifndef __G_ATOMIC_H__ -#define __G_ATOMIC_H__ - -#include - -G_BEGIN_DECLS - -gint g_atomic_int_exchange_and_add( gint *atomic, - gint val ); -void g_atomic_int_add( gint *atomic, - gint val ); -gboolean g_atomic_int_compare_and_exchange( gint *atomic, - gint oldval, - gint newval ); -gboolean g_atomic_pointer_compare_and_exchange( gpointer *atomic, - gpointer oldval, - gpointer newval ); - -#ifdef G_ATOMIC_OP_MEMORY_BARRIER_NEEDED -gint g_atomic_int_get( gint *atomic ); -gpointer g_atomic_pointer_get( gpointer *atomic ); -#else /* !G_ATOMIC_OP_MEMORY_BARRIER_NEEDED */ -# define g_atomic_int_get( atomic ) ( *( atomic ) ) -# define g_atomic_pointer_get( atomic ) ( *( atomic ) ) -#endif /* G_ATOMIC_OP_MEMORY_BARRIER_NEEDED */ - -#define g_atomic_int_inc( atomic ) ( g_atomic_int_add( ( atomic ), 1 ) ) -#define g_atomic_int_dec_and_test( atomic ) \ - ( g_atomic_int_exchange_and_add( ( atomic ), -1 ) == 1 ) - -G_END_DECLS - -#endif /* __G_ATOMIC_H__ */ diff --git a/tools/urt/tools/quake3/common/glib/gbacktrace.h b/tools/urt/tools/quake3/common/glib/gbacktrace.h deleted file mode 100644 index 07cc4fa..0000000 --- a/tools/urt/tools/quake3/common/glib/gbacktrace.h +++ /dev/null @@ -1,61 +0,0 @@ -/* GLIB - Library of useful routines for C programming - * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the - * Free Software Foundation, Inc., 59 Temple Place - Suite 330, - * Boston, MA 02111-1307, USA. - */ - -/* - * Modified by the GLib Team and others 1997-2000. See the AUTHORS - * file for a list of people on the GLib Team. See the ChangeLog - * files for a list of changes. These files are distributed with - * GLib at ftp://ftp.gtk.org/pub/gtk/. - */ - -#ifndef __G_BACKTRACE_H__ -#define __G_BACKTRACE_H__ - -#include - -G_BEGIN_DECLS - -/* Fatal error handlers. - * g_on_error_query() will prompt the user to either - * [E]xit, [H]alt, [P]roceed or show [S]tack trace. - * g_on_error_stack_trace() invokes gdb, which attaches to the current - * process and shows a stack trace. - * These function may cause different actions on non-unix platforms. - * The prg_name arg is required by gdb to find the executable, if it is - * passed as NULL, g_on_error_query() will try g_get_prgname(). - */ -void g_on_error_query( const gchar *prg_name ); -void g_on_error_stack_trace( const gchar *prg_name ); - -/* Hacker macro to place breakpoints for selected machines. - * Actual use is strongly discouraged of course ;) - */ -#if ( defined ( __i386__ ) || defined ( __x86_64__ ) ) && defined ( __GNUC__ ) && __GNUC__ >= 2 -# define G_BREAKPOINT() G_STMT_START { __asm__ __volatile__ ( "int $03" ); } G_STMT_END -#elif defined ( _MSC_VER ) && defined ( _M_IX86 ) -# define G_BREAKPOINT() G_STMT_START { __asm int 3h } G_STMT_END -#elif defined ( __alpha__ ) && !defined( __osf__ ) && defined ( __GNUC__ ) && __GNUC__ >= 2 -# define G_BREAKPOINT() G_STMT_START { __asm__ __volatile__ ( "bpt" ); } G_STMT_END -#else /* !__i386__ && !__alpha__ */ -# define G_BREAKPOINT() G_STMT_START { raise( SIGTRAP ); } G_STMT_END -#endif /* __i386__ */ - -G_END_DECLS - -#endif /* __G_BACKTRACE_H__ */ diff --git a/tools/urt/tools/quake3/common/glib/gcache.h b/tools/urt/tools/quake3/common/glib/gcache.h deleted file mode 100644 index 345fedd..0000000 --- a/tools/urt/tools/quake3/common/glib/gcache.h +++ /dev/null @@ -1,63 +0,0 @@ -/* GLIB - Library of useful routines for C programming - * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the - * Free Software Foundation, Inc., 59 Temple Place - Suite 330, - * Boston, MA 02111-1307, USA. - */ - -/* - * Modified by the GLib Team and others 1997-2000. See the AUTHORS - * file for a list of people on the GLib Team. See the ChangeLog - * files for a list of changes. These files are distributed with - * GLib at ftp://ftp.gtk.org/pub/gtk/. - */ - -#ifndef __G_CACHE_H__ -#define __G_CACHE_H__ - -#include - -G_BEGIN_DECLS - -typedef struct _GCache GCache; - -typedef gpointer ( *GCacheNewFunc )( gpointer key ); -typedef gpointer ( *GCacheDupFunc )( gpointer value ); -typedef void ( *GCacheDestroyFunc )( gpointer value ); - -/* Caches - */ -GCache* g_cache_new( GCacheNewFunc value_new_func, - GCacheDestroyFunc value_destroy_func, - GCacheDupFunc key_dup_func, - GCacheDestroyFunc key_destroy_func, - GHashFunc hash_key_func, - GHashFunc hash_value_func, - GEqualFunc key_equal_func ); -void g_cache_destroy( GCache *cache ); -gpointer g_cache_insert( GCache *cache, - gpointer key ); -void g_cache_remove( GCache *cache, - gconstpointer value ); -void g_cache_key_foreach( GCache *cache, - GHFunc func, - gpointer user_data ); -void g_cache_value_foreach( GCache *cache, - GHFunc func, - gpointer user_data ); - -G_END_DECLS - -#endif /* __G_CACHE_H__ */ diff --git a/tools/urt/tools/quake3/common/glib/gcompletion.h b/tools/urt/tools/quake3/common/glib/gcompletion.h deleted file mode 100644 index 048b35f..0000000 --- a/tools/urt/tools/quake3/common/glib/gcompletion.h +++ /dev/null @@ -1,73 +0,0 @@ -/* GLIB - Library of useful routines for C programming - * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the - * Free Software Foundation, Inc., 59 Temple Place - Suite 330, - * Boston, MA 02111-1307, USA. - */ - -/* - * Modified by the GLib Team and others 1997-2000. See the AUTHORS - * file for a list of people on the GLib Team. See the ChangeLog - * files for a list of changes. These files are distributed with - * GLib at ftp://ftp.gtk.org/pub/gtk/. - */ - -#ifndef __G_COMPLETION_H__ -#define __G_COMPLETION_H__ - -#include - -G_BEGIN_DECLS - -typedef struct _GCompletion GCompletion; - -typedef gchar* ( *GCompletionFunc )( gpointer ); - -/* GCompletion - */ - -typedef gint ( *GCompletionStrncmpFunc )( const gchar *s1, - const gchar *s2, - gsize n ); - -struct _GCompletion -{ - GList* items; - GCompletionFunc func; - - gchar* prefix; - GList* cache; - GCompletionStrncmpFunc strncmp_func; -}; - -GCompletion* g_completion_new( GCompletionFunc func ); -void g_completion_add_items( GCompletion* cmp, - GList* items ); -void g_completion_remove_items( GCompletion* cmp, - GList* items ); -void g_completion_clear_items( GCompletion* cmp ); -GList* g_completion_complete( GCompletion* cmp, - const gchar* prefix, - gchar** new_prefix ); -GList* g_completion_complete_utf8( GCompletion *cmp, - const gchar* prefix, - gchar** new_prefix ); -void g_completion_set_compare( GCompletion *cmp, - GCompletionStrncmpFunc strncmp_func ); -void g_completion_free( GCompletion* cmp ); - -G_END_DECLS - -#endif /* __G_COMPLETION_H__ */ diff --git a/tools/urt/tools/quake3/common/glib/gconvert.h b/tools/urt/tools/quake3/common/glib/gconvert.h deleted file mode 100644 index a9153ca..0000000 --- a/tools/urt/tools/quake3/common/glib/gconvert.h +++ /dev/null @@ -1,123 +0,0 @@ -/* GLIB - Library of useful routines for C programming - * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the - * Free Software Foundation, Inc., 59 Temple Place - Suite 330, - * Boston, MA 02111-1307, USA. - */ - -/* - * Modified by the GLib Team and others 1997-2000. See the AUTHORS - * file for a list of people on the GLib Team. See the ChangeLog - * files for a list of changes. These files are distributed with - * GLib at ftp://ftp.gtk.org/pub/gtk/. - */ - -#ifndef __G_CONVERT_H__ -#define __G_CONVERT_H__ - -#include /* For size_t */ -#include - -G_BEGIN_DECLS - -typedef enum -{ - G_CONVERT_ERROR_NO_CONVERSION, - G_CONVERT_ERROR_ILLEGAL_SEQUENCE, - G_CONVERT_ERROR_FAILED, - G_CONVERT_ERROR_PARTIAL_INPUT, - G_CONVERT_ERROR_BAD_URI, - G_CONVERT_ERROR_NOT_ABSOLUTE_PATH -} GConvertError; - -#define G_CONVERT_ERROR g_convert_error_quark() -GQuark g_convert_error_quark( void ); - -/* Thin wrappers around iconv - */ -typedef struct _GIConv *GIConv; - -GIConv g_iconv_open( const gchar *to_codeset, - const gchar *from_codeset ); -size_t g_iconv( GIConv converter, - gchar **inbuf, - gsize *inbytes_left, - gchar **outbuf, - gsize *outbytes_left ); -gint g_iconv_close( GIConv converter ); - - -gchar* g_convert( const gchar *str, - gssize len, - const gchar *to_codeset, - const gchar *from_codeset, - gsize *bytes_read, - gsize *bytes_written, - GError **error ); -gchar* g_convert_with_iconv( const gchar *str, - gssize len, - GIConv converter, - gsize *bytes_read, - gsize *bytes_written, - GError **error ); -gchar* g_convert_with_fallback( const gchar *str, - gssize len, - const gchar *to_codeset, - const gchar *from_codeset, - gchar *fallback, - gsize *bytes_read, - gsize *bytes_written, - GError **error ); - - -/* Convert between libc's idea of strings and UTF-8. - */ -gchar* g_locale_to_utf8( const gchar *opsysstring, - gssize len, - gsize *bytes_read, - gsize *bytes_written, - GError **error ); -gchar* g_locale_from_utf8( const gchar *utf8string, - gssize len, - gsize *bytes_read, - gsize *bytes_written, - GError **error ); - -/* Convert between the operating system (or C runtime) - * representation of file names and UTF-8. - */ -gchar* g_filename_to_utf8( const gchar *opsysstring, - gssize len, - gsize *bytes_read, - gsize *bytes_written, - GError **error ); -gchar* g_filename_from_utf8( const gchar *utf8string, - gssize len, - gsize *bytes_read, - gsize *bytes_written, - GError **error ); - -gchar *g_filename_from_uri( const gchar *uri, - gchar **hostname, - GError **error ); - -gchar *g_filename_to_uri( const gchar *filename, - const gchar *hostname, - GError **error ); - - -G_END_DECLS - -#endif /* __G_CONVERT_H__ */ diff --git a/tools/urt/tools/quake3/common/glib/gdataset.h b/tools/urt/tools/quake3/common/glib/gdataset.h deleted file mode 100644 index a8a9baf..0000000 --- a/tools/urt/tools/quake3/common/glib/gdataset.h +++ /dev/null @@ -1,102 +0,0 @@ -/* GLIB - Library of useful routines for C programming - * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the - * Free Software Foundation, Inc., 59 Temple Place - Suite 330, - * Boston, MA 02111-1307, USA. - */ - -/* - * Modified by the GLib Team and others 1997-2000. See the AUTHORS - * file for a list of people on the GLib Team. See the ChangeLog - * files for a list of changes. These files are distributed with - * GLib at ftp://ftp.gtk.org/pub/gtk/. - */ - -#ifndef __G_DATASET_H__ -#define __G_DATASET_H__ - -#include - -G_BEGIN_DECLS - -typedef struct _GData GData; - -typedef void ( *GDataForeachFunc )( GQuark key_id, - gpointer data, - gpointer user_data ); - -/* Keyed Data List - */ -void g_datalist_init( GData **datalist ); -void g_datalist_clear( GData **datalist ); -gpointer g_datalist_id_get_data( GData **datalist, - GQuark key_id ); -void g_datalist_id_set_data_full( GData **datalist, - GQuark key_id, - gpointer data, - GDestroyNotify destroy_func ); -gpointer g_datalist_id_remove_no_notify( GData **datalist, - GQuark key_id ); -void g_datalist_foreach( GData **datalist, - GDataForeachFunc func, - gpointer user_data ); -#define g_datalist_id_set_data( dl, q, d ) \ - g_datalist_id_set_data_full( ( dl ), ( q ), ( d ), NULL ) -#define g_datalist_id_remove_data( dl, q ) \ - g_datalist_id_set_data( ( dl ), ( q ), NULL ) -#define g_datalist_get_data( dl, k ) \ - ( g_datalist_id_get_data( ( dl ), g_quark_try_string( k ) ) ) -#define g_datalist_set_data_full( dl, k, d, f ) \ - g_datalist_id_set_data_full( ( dl ), g_quark_from_string( k ), ( d ), ( f ) ) -#define g_datalist_remove_no_notify( dl, k ) \ - g_datalist_id_remove_no_notify( ( dl ), g_quark_try_string( k ) ) -#define g_datalist_set_data( dl, k, d ) \ - g_datalist_set_data_full( ( dl ), ( k ), ( d ), NULL ) -#define g_datalist_remove_data( dl, k ) \ - g_datalist_id_set_data( ( dl ), g_quark_try_string( k ), NULL ) - - -/* Location Associated Keyed Data - */ -void g_dataset_destroy( gconstpointer dataset_location ); -gpointer g_dataset_id_get_data( gconstpointer dataset_location, - GQuark key_id ); -void g_dataset_id_set_data_full( gconstpointer dataset_location, - GQuark key_id, - gpointer data, - GDestroyNotify destroy_func ); -gpointer g_dataset_id_remove_no_notify( gconstpointer dataset_location, - GQuark key_id ); -void g_dataset_foreach( gconstpointer dataset_location, - GDataForeachFunc func, - gpointer user_data ); -#define g_dataset_id_set_data( l, k, d ) \ - g_dataset_id_set_data_full( ( l ), ( k ), ( d ), NULL ) -#define g_dataset_id_remove_data( l, k ) \ - g_dataset_id_set_data( ( l ), ( k ), NULL ) -#define g_dataset_get_data( l, k ) \ - ( g_dataset_id_get_data( ( l ), g_quark_try_string( k ) ) ) -#define g_dataset_set_data_full( l, k, d, f ) \ - g_dataset_id_set_data_full( ( l ), g_quark_from_string( k ), ( d ), ( f ) ) -#define g_dataset_remove_no_notify( l, k ) \ - g_dataset_id_remove_no_notify( ( l ), g_quark_try_string( k ) ) -#define g_dataset_set_data( l, k, d ) \ - g_dataset_set_data_full( ( l ), ( k ), ( d ), NULL ) -#define g_dataset_remove_data( l, k ) \ - g_dataset_id_set_data( ( l ), g_quark_try_string( k ), NULL ) - -G_END_DECLS - -#endif /* __G_DATASET_H__ */ diff --git a/tools/urt/tools/quake3/common/glib/gdate.h b/tools/urt/tools/quake3/common/glib/gdate.h deleted file mode 100644 index 3e8a45d..0000000 --- a/tools/urt/tools/quake3/common/glib/gdate.h +++ /dev/null @@ -1,251 +0,0 @@ -/* GLIB - Library of useful routines for C programming - * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the - * Free Software Foundation, Inc., 59 Temple Place - Suite 330, - * Boston, MA 02111-1307, USA. - */ - -/* - * Modified by the GLib Team and others 1997-2000. See the AUTHORS - * file for a list of people on the GLib Team. See the ChangeLog - * files for a list of changes. These files are distributed with - * GLib at ftp://ftp.gtk.org/pub/gtk/. - */ - -#ifndef __G_DATE_H__ -#define __G_DATE_H__ - -#include - -G_BEGIN_DECLS - -/* GDate - * - * Date calculations (not time for now, to be resolved). These are a - * mutant combination of Steffen Beyer's DateCalc routines - * (http://www.perl.com/CPAN/authors/id/STBEY/) and Jon Trowbridge's - * date routines (written for in-house software). Written by Havoc - * Pennington - */ - -typedef gint32 GTime; -typedef guint16 GDateYear; -typedef guint8 GDateDay; /* day of the month */ -typedef struct _GDate GDate; -/* make struct tm known without having to include time.h */ -struct tm; - -/* enum used to specify order of appearance in parsed date strings */ -typedef enum -{ - G_DATE_DAY = 0, - G_DATE_MONTH = 1, - G_DATE_YEAR = 2 -} GDateDMY; - -/* actual week and month values */ -typedef enum -{ - G_DATE_BAD_WEEKDAY = 0, - G_DATE_MONDAY = 1, - G_DATE_TUESDAY = 2, - G_DATE_WEDNESDAY = 3, - G_DATE_THURSDAY = 4, - G_DATE_FRIDAY = 5, - G_DATE_SATURDAY = 6, - G_DATE_SUNDAY = 7 -} GDateWeekday; -typedef enum -{ - G_DATE_BAD_MONTH = 0, - G_DATE_JANUARY = 1, - G_DATE_FEBRUARY = 2, - G_DATE_MARCH = 3, - G_DATE_APRIL = 4, - G_DATE_MAY = 5, - G_DATE_JUNE = 6, - G_DATE_JULY = 7, - G_DATE_AUGUST = 8, - G_DATE_SEPTEMBER = 9, - G_DATE_OCTOBER = 10, - G_DATE_NOVEMBER = 11, - G_DATE_DECEMBER = 12 -} GDateMonth; - -#define G_DATE_BAD_JULIAN 0U -#define G_DATE_BAD_DAY 0U -#define G_DATE_BAD_YEAR 0U - -/* Note: directly manipulating structs is generally a bad idea, but - * in this case it's an *incredibly* bad idea, because all or part - * of this struct can be invalid at any given time. Use the functions, - * or you will get hosed, I promise. - */ -struct _GDate -{ - guint julian_days : 32; /* julian days representation - we use a - * bitfield hoping that 64 bit platforms - * will pack this whole struct in one big - * int - */ - - guint julian : 1; /* julian is valid */ - guint dmy : 1; /* dmy is valid */ - - /* DMY representation */ - guint day : 6; - guint month : 4; - guint year : 16; -}; - -/* g_date_new() returns an invalid date, you then have to _set() stuff - * to get a usable object. You can also allocate a GDate statically, - * then call g_date_clear() to initialize. - */ -GDate* g_date_new( void ); -GDate* g_date_new_dmy( GDateDay day, - GDateMonth month, - GDateYear year ); -GDate* g_date_new_julian( guint32 julian_day ); -void g_date_free( GDate *date ); - -/* check g_date_valid() after doing an operation that might fail, like - * _parse. Almost all g_date operations are undefined on invalid - * dates (the exceptions are the mutators, since you need those to - * return to validity). - */ -gboolean g_date_valid( const GDate *date ); -gboolean g_date_valid_day( GDateDay day ) G_GNUC_CONST; -gboolean g_date_valid_month( GDateMonth month ) G_GNUC_CONST; -gboolean g_date_valid_year( GDateYear year ) G_GNUC_CONST; -gboolean g_date_valid_weekday( GDateWeekday weekday ) G_GNUC_CONST; -gboolean g_date_valid_julian( guint32 julian_date ) G_GNUC_CONST; -gboolean g_date_valid_dmy( GDateDay day, - GDateMonth month, - GDateYear year ) G_GNUC_CONST; - -GDateWeekday g_date_get_weekday( const GDate *date ); -GDateMonth g_date_get_month( const GDate *date ); -GDateYear g_date_get_year( const GDate *date ); -GDateDay g_date_get_day( const GDate *date ); -guint32 g_date_get_julian( const GDate *date ); -guint g_date_get_day_of_year( const GDate *date ); -/* First monday/sunday is the start of week 1; if we haven't reached - * that day, return 0. These are not ISO weeks of the year; that - * routine needs to be added. - * these functions return the number of weeks, starting on the - * corrsponding day - */ -guint g_date_get_monday_week_of_year( const GDate *date ); -guint g_date_get_sunday_week_of_year( const GDate *date ); - -/* If you create a static date struct you need to clear it to get it - * in a sane state before use. You can clear a whole array at - * once with the ndates argument. - */ -void g_date_clear( GDate *date, - guint n_dates ); - -/* The parse routine is meant for dates typed in by a user, so it - * permits many formats but tries to catch common typos. If your data - * needs to be strictly validated, it is not an appropriate function. - */ -void g_date_set_parse( GDate *date, - const gchar *str ); -void g_date_set_time( GDate *date, - GTime time_ ); -void g_date_set_month( GDate *date, - GDateMonth month ); -void g_date_set_day( GDate *date, - GDateDay day ); -void g_date_set_year( GDate *date, - GDateYear year ); -void g_date_set_dmy( GDate *date, - GDateDay day, - GDateMonth month, - GDateYear y ); -void g_date_set_julian( GDate *date, - guint32 julian_date ); -gboolean g_date_is_first_of_month( const GDate *date ); -gboolean g_date_is_last_of_month( const GDate *date ); - -/* To go forward by some number of weeks just go forward weeks*7 days */ -void g_date_add_days( GDate *date, - guint n_days ); -void g_date_subtract_days( GDate *date, - guint n_days ); - -/* If you add/sub months while day > 28, the day might change */ -void g_date_add_months( GDate *date, - guint n_months ); -void g_date_subtract_months( GDate *date, - guint n_months ); - -/* If it's feb 29, changing years can move you to the 28th */ -void g_date_add_years( GDate *date, - guint n_years ); -void g_date_subtract_years( GDate *date, - guint n_years ); -gboolean g_date_is_leap_year( GDateYear year ) G_GNUC_CONST; -guint8 g_date_get_days_in_month( GDateMonth month, - GDateYear year ) G_GNUC_CONST; -guint8 g_date_get_monday_weeks_in_year( GDateYear year ) G_GNUC_CONST; -guint8 g_date_get_sunday_weeks_in_year( GDateYear year ) G_GNUC_CONST; - -/* Returns the number of days between the two dates. If date2 comes - before date1, a negative value is return. */ -gint g_date_days_between( const GDate *date1, - const GDate *date2 ); - -/* qsort-friendly (with a cast...) */ -gint g_date_compare( const GDate *lhs, - const GDate *rhs ); -void g_date_to_struct_tm( const GDate *date, - struct tm *tm ); - -void g_date_clamp( GDate *date, - const GDate *min_date, - const GDate *max_date ); - -/* Swap date1 and date2's values if date1 > date2. */ -void g_date_order( GDate *date1, GDate *date2 ); - -/* Just like strftime() except you can only use date-related formats. - * Using a time format is undefined. - */ -gsize g_date_strftime( gchar *s, - gsize slen, - const gchar *format, - const GDate *date ); - -#ifndef G_DISABLE_DEPRECATED - -#define g_date_weekday g_date_get_weekday -#define g_date_month g_date_get_month -#define g_date_year g_date_get_year -#define g_date_day g_date_get_day -#define g_date_julian g_date_get_julian -#define g_date_day_of_year g_date_get_day_of_year -#define g_date_monday_week_of_year g_date_get_monday_week_of_year -#define g_date_sunday_week_of_year g_date_get_sunday_week_of_year -#define g_date_days_in_month g_date_get_days_in_month -#define g_date_monday_weeks_in_year g_date_get_monday_weeks_in_year -#define g_date_sunday_weeks_in_year g_date_get_sunday_weeks_in_year - -#endif /* G_DISABLE_DEPRECATED */ - -G_END_DECLS - -#endif /* __G_DATE_H__ */ diff --git a/tools/urt/tools/quake3/common/glib/gdir.h b/tools/urt/tools/quake3/common/glib/gdir.h deleted file mode 100644 index c20a5c9..0000000 --- a/tools/urt/tools/quake3/common/glib/gdir.h +++ /dev/null @@ -1,41 +0,0 @@ -/* GLIB - Library of useful routines for C programming - * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald - * - * gdir.c: Simplified wrapper around the DIRENT functions. - * - * Copyright 2001 Hans Breuer - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the - * Free Software Foundation, Inc., 59 Temple Place - Suite 330, - * Boston, MA 02111-1307, USA. - */ -#ifndef __G_DIR_H__ -#define __G_DIR_H__ - -#include - -G_BEGIN_DECLS - -typedef struct _GDir GDir; - -GDir * g_dir_open( const gchar *path, - guint flags, - GError **error ); -G_CONST_RETURN gchar *g_dir_read_name( GDir *dir ); -void g_dir_rewind( GDir *dir ); -void g_dir_close( GDir *dir ); - -G_END_DECLS - -#endif /* __G_DIR_H__ */ diff --git a/tools/urt/tools/quake3/common/glib/gerror.h b/tools/urt/tools/quake3/common/glib/gerror.h deleted file mode 100644 index b10a34a..0000000 --- a/tools/urt/tools/quake3/common/glib/gerror.h +++ /dev/null @@ -1,73 +0,0 @@ -/* gerror.h - Error reporting system - * - * Copyright 2000 Red Hat, Inc. - * - * The Gnome Library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 of the - * License, or (at your option) any later version. - * - * The Gnome Library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with the Gnome Library; see the file COPYING.LIB. If not, - * write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, - * Boston, MA 02111-1307, USA. - */ - -#ifndef __G_ERROR_H__ -#define __G_ERROR_H__ - -#include - -G_BEGIN_DECLS - -typedef struct _GError GError; - -struct _GError -{ - GQuark domain; - gint code; - gchar *message; -}; - -GError* g_error_new( GQuark domain, - gint code, - const gchar *format, - ... ) G_GNUC_PRINTF( 3, 4 ); - -GError* g_error_new_literal( GQuark domain, - gint code, - const gchar *message ); - -void g_error_free( GError *error ); -GError* g_error_copy( const GError *error ); - -gboolean g_error_matches( const GError *error, - GQuark domain, - gint code ); - -/* if (err) *err = g_error_new(domain, code, format, ...), also has - * some sanity checks. - */ -void g_set_error( GError **err, - GQuark domain, - gint code, - const gchar *format, - ... ) G_GNUC_PRINTF( 4, 5 ); - -/* if (dest) *dest = src; also has some sanity checks. - */ -void g_propagate_error( GError **dest, - GError *src ); - -/* if (err && *err) { g_error_free(*err); *err = NULL; } */ -void g_clear_error( GError **err ); - - -G_END_DECLS - -#endif /* __G_ERROR_H__ */ diff --git a/tools/urt/tools/quake3/common/glib/gfileutils.h b/tools/urt/tools/quake3/common/glib/gfileutils.h deleted file mode 100644 index 942100f..0000000 --- a/tools/urt/tools/quake3/common/glib/gfileutils.h +++ /dev/null @@ -1,100 +0,0 @@ -/* gfileutils.h - File utility functions - * - * Copyright 2000 Red Hat, Inc. - * - * GLib is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 of the - * License, or (at your option) any later version. - * - * GLib is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with GLib; see the file COPYING.LIB. If not, - * write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, - * Boston, MA 02111-1307, USA. - */ - -#ifndef __G_FILEUTILS_H__ -#define __G_FILEUTILS_H__ - -#include - -G_BEGIN_DECLS - -#define G_FILE_ERROR g_file_error_quark() - -typedef enum -{ - G_FILE_ERROR_EXIST, - G_FILE_ERROR_ISDIR, - G_FILE_ERROR_ACCES, - G_FILE_ERROR_NAMETOOLONG, - G_FILE_ERROR_NOENT, - G_FILE_ERROR_NOTDIR, - G_FILE_ERROR_NXIO, - G_FILE_ERROR_NODEV, - G_FILE_ERROR_ROFS, - G_FILE_ERROR_TXTBSY, - G_FILE_ERROR_FAULT, - G_FILE_ERROR_LOOP, - G_FILE_ERROR_NOSPC, - G_FILE_ERROR_NOMEM, - G_FILE_ERROR_MFILE, - G_FILE_ERROR_NFILE, - G_FILE_ERROR_BADF, - G_FILE_ERROR_INVAL, - G_FILE_ERROR_PIPE, - G_FILE_ERROR_AGAIN, - G_FILE_ERROR_INTR, - G_FILE_ERROR_IO, - G_FILE_ERROR_PERM, - G_FILE_ERROR_FAILED -} GFileError; - -/* For backward-compat reasons, these are synced to an old - * anonymous enum in libgnome. But don't use that enum - * in new code. - */ -typedef enum -{ - G_FILE_TEST_IS_REGULAR = 1 << 0, - G_FILE_TEST_IS_SYMLINK = 1 << 1, - G_FILE_TEST_IS_DIR = 1 << 2, - G_FILE_TEST_IS_EXECUTABLE = 1 << 3, - G_FILE_TEST_EXISTS = 1 << 4 -} GFileTest; - -GQuark g_file_error_quark( void ); -/* So other code can generate a GFileError */ -GFileError g_file_error_from_errno( gint err_no ); - -gboolean g_file_test( const gchar *filename, - GFileTest test ); -gboolean g_file_get_contents( const gchar *filename, - gchar **contents, - gsize *length, - GError **error ); -gchar *g_file_read_link( const gchar *filename, - GError **error ); - -/* Wrapper / workalike for mkstemp() */ -gint g_mkstemp( gchar *tmpl ); - -/* Wrapper for g_mkstemp */ -gint g_file_open_tmp( const gchar *tmpl, - gchar **name_used, - GError **error ); - -gchar *g_build_path( const gchar *separator, - const gchar *first_element, - ... ); -gchar *g_build_filename( const gchar *first_element, - ... ); - -G_END_DECLS - -#endif /* __G_FILEUTILS_H__ */ diff --git a/tools/urt/tools/quake3/common/glib/ghash.h b/tools/urt/tools/quake3/common/glib/ghash.h deleted file mode 100644 index 3f9d010..0000000 --- a/tools/urt/tools/quake3/common/glib/ghash.h +++ /dev/null @@ -1,110 +0,0 @@ -/* GLIB - Library of useful routines for C programming - * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the - * Free Software Foundation, Inc., 59 Temple Place - Suite 330, - * Boston, MA 02111-1307, USA. - */ - -/* - * Modified by the GLib Team and others 1997-2000. See the AUTHORS - * file for a list of people on the GLib Team. See the ChangeLog - * files for a list of changes. These files are distributed with - * GLib at ftp://ftp.gtk.org/pub/gtk/. - */ - -#ifndef __G_HASH_H__ -#define __G_HASH_H__ - -#include - -G_BEGIN_DECLS - -typedef struct _GHashTable GHashTable; - -typedef gboolean ( *GHRFunc )( gpointer key, - gpointer value, - gpointer user_data ); - -/* Hash tables - */ -GHashTable* g_hash_table_new( GHashFunc hash_func, - GEqualFunc key_equal_func ); -GHashTable* g_hash_table_new_full( GHashFunc hash_func, - GEqualFunc key_equal_func, - GDestroyNotify key_destroy_func, - GDestroyNotify value_destroy_func ); -void g_hash_table_destroy( GHashTable *hash_table ); -void g_hash_table_insert( GHashTable *hash_table, - gpointer key, - gpointer value ); -void g_hash_table_replace( GHashTable *hash_table, - gpointer key, - gpointer value ); -gboolean g_hash_table_remove( GHashTable *hash_table, - gconstpointer key ); -gboolean g_hash_table_steal( GHashTable *hash_table, - gconstpointer key ); -gpointer g_hash_table_lookup( GHashTable *hash_table, - gconstpointer key ); -gboolean g_hash_table_lookup_extended( GHashTable *hash_table, - gconstpointer lookup_key, - gpointer *orig_key, - gpointer *value ); -void g_hash_table_foreach( GHashTable *hash_table, - GHFunc func, - gpointer user_data ); -gpointer g_hash_table_find( GHashTable *hash_table, - GHRFunc predicate, - gpointer user_data ); -guint g_hash_table_foreach_remove( GHashTable *hash_table, - GHRFunc func, - gpointer user_data ); -guint g_hash_table_foreach_steal( GHashTable *hash_table, - GHRFunc func, - gpointer user_data ); -guint g_hash_table_size( GHashTable *hash_table ); - -#ifndef G_DISABLE_DEPRECATED - -/* The following two functions are deprecated and will be removed in - * the next major release. They do no good. */ -#define g_hash_table_freeze( hash_table ) ( (void)0 ) -#define g_hash_table_thaw( hash_table ) ( (void)0 ) - -#endif /* G_DISABLE_DEPRECATED */ - -/* Hash Functions - */ -gboolean g_str_equal( gconstpointer v, - gconstpointer v2 ); -guint g_str_hash( gconstpointer v ); - -gboolean g_int_equal( gconstpointer v, - gconstpointer v2 ); -guint g_int_hash( gconstpointer v ); - -/* This "hash" function will just return the key's address as an - * unsigned integer. Useful for hashing on plain addresses or - * simple integer values. - * Passing NULL into g_hash_table_new() as GHashFunc has the - * same effect as passing g_direct_hash(). - */ -guint g_direct_hash( gconstpointer v ) G_GNUC_CONST; -gboolean g_direct_equal( gconstpointer v, - gconstpointer v2 ) G_GNUC_CONST; - -G_END_DECLS - -#endif /* __G_HASH_H__ */ diff --git a/tools/urt/tools/quake3/common/glib/ghook.h b/tools/urt/tools/quake3/common/glib/ghook.h deleted file mode 100644 index cfd7d58..0000000 --- a/tools/urt/tools/quake3/common/glib/ghook.h +++ /dev/null @@ -1,177 +0,0 @@ -/* GLIB - Library of useful routines for C programming - * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the - * Free Software Foundation, Inc., 59 Temple Place - Suite 330, - * Boston, MA 02111-1307, USA. - */ - -/* - * Modified by the GLib Team and others 1997-2000. See the AUTHORS - * file for a list of people on the GLib Team. See the ChangeLog - * files for a list of changes. These files are distributed with - * GLib at ftp://ftp.gtk.org/pub/gtk/. - */ - -#ifndef __G_HOOK_H__ -#define __G_HOOK_H__ - -#include - -G_BEGIN_DECLS - - -/* --- typedefs --- */ -typedef struct _GHook GHook; -typedef struct _GHookList GHookList; - -typedef gint ( *GHookCompareFunc )( GHook *new_hook, - GHook *sibling ); -typedef gboolean ( *GHookFindFunc )( GHook *hook, - gpointer data ); -typedef void ( *GHookMarshaller )( GHook *hook, - gpointer marshal_data ); -typedef gboolean ( *GHookCheckMarshaller )( GHook *hook, - gpointer marshal_data ); -typedef void ( *GHookFunc )( gpointer data ); -typedef gboolean ( *GHookCheckFunc )( gpointer data ); -typedef void ( *GHookFinalizeFunc )( GHookList *hook_list, - GHook *hook ); -typedef enum -{ - G_HOOK_FLAG_ACTIVE = 1 << 0, - G_HOOK_FLAG_IN_CALL = 1 << 1, - G_HOOK_FLAG_MASK = 0x0f -} GHookFlagMask; -#define G_HOOK_FLAG_USER_SHIFT ( 4 ) - - -/* --- structures --- */ -struct _GHookList -{ - gulong seq_id; - guint hook_size : 16; - guint is_setup : 1; - GHook *hooks; - GMemChunk *hook_memchunk; - GHookFinalizeFunc finalize_hook; - gpointer dummy[2]; -}; -struct _GHook -{ - gpointer data; - GHook *next; - GHook *prev; - guint ref_count; - gulong hook_id; - guint flags; - gpointer func; - GDestroyNotify destroy; -}; - - -/* --- macros --- */ -#define G_HOOK( hook ) ( (GHook*) ( hook ) ) -#define G_HOOK_FLAGS( hook ) ( G_HOOK( hook )->flags ) -#define G_HOOK_ACTIVE( hook ) ( ( G_HOOK_FLAGS( hook ) & \ - G_HOOK_FLAG_ACTIVE ) != 0 ) -#define G_HOOK_IN_CALL( hook ) ( ( G_HOOK_FLAGS( hook ) & \ - G_HOOK_FLAG_IN_CALL ) != 0 ) -#define G_HOOK_IS_VALID( hook ) ( G_HOOK( hook )->hook_id != 0 && \ - ( G_HOOK_FLAGS( hook ) & \ - G_HOOK_FLAG_ACTIVE ) ) -#define G_HOOK_IS_UNLINKED( hook ) ( G_HOOK( hook )->next == NULL && \ - G_HOOK( hook )->prev == NULL && \ - G_HOOK( hook )->hook_id == 0 && \ - G_HOOK( hook )->ref_count == 0 ) - - -/* --- prototypes --- */ -/* callback maintenance functions */ -void g_hook_list_init( GHookList *hook_list, - guint hook_size ); -void g_hook_list_clear( GHookList *hook_list ); -GHook* g_hook_alloc( GHookList *hook_list ); -void g_hook_free( GHookList *hook_list, - GHook *hook ); -void g_hook_ref( GHookList *hook_list, - GHook *hook ); -void g_hook_unref( GHookList *hook_list, - GHook *hook ); -gboolean g_hook_destroy( GHookList *hook_list, - gulong hook_id ); -void g_hook_destroy_link( GHookList *hook_list, - GHook *hook ); -void g_hook_prepend( GHookList *hook_list, - GHook *hook ); -void g_hook_insert_before( GHookList *hook_list, - GHook *sibling, - GHook *hook ); -void g_hook_insert_sorted( GHookList *hook_list, - GHook *hook, - GHookCompareFunc func ); -GHook* g_hook_get( GHookList *hook_list, - gulong hook_id ); -GHook* g_hook_find( GHookList *hook_list, - gboolean need_valids, - GHookFindFunc func, - gpointer data ); -GHook* g_hook_find_data( GHookList *hook_list, - gboolean need_valids, - gpointer data ); -GHook* g_hook_find_func( GHookList *hook_list, - gboolean need_valids, - gpointer func ); -GHook* g_hook_find_func_data( GHookList *hook_list, - gboolean need_valids, - gpointer func, - gpointer data ); -/* return the first valid hook, and increment its reference count */ -GHook* g_hook_first_valid( GHookList *hook_list, - gboolean may_be_in_call ); -/* return the next valid hook with incremented reference count, and - * decrement the reference count of the original hook - */ -GHook* g_hook_next_valid( GHookList *hook_list, - GHook *hook, - gboolean may_be_in_call ); -/* GHookCompareFunc implementation to insert hooks sorted by their id */ -gint g_hook_compare_ids( GHook *new_hook, - GHook *sibling ); -/* convenience macros */ -#define g_hook_append( hook_list, hook ) \ - g_hook_insert_before( ( hook_list ), NULL, ( hook ) ) -/* invoke all valid hooks with the (*GHookFunc) signature. - */ -void g_hook_list_invoke( GHookList *hook_list, - gboolean may_recurse ); -/* invoke all valid hooks with the (*GHookCheckFunc) signature, - * and destroy the hook if FALSE is returned. - */ -void g_hook_list_invoke_check( GHookList *hook_list, - gboolean may_recurse ); -/* invoke a marshaller on all valid hooks. - */ -void g_hook_list_marshal( GHookList *hook_list, - gboolean may_recurse, - GHookMarshaller marshaller, - gpointer marshal_data ); -void g_hook_list_marshal_check( GHookList *hook_list, - gboolean may_recurse, - GHookCheckMarshaller marshaller, - gpointer marshal_data ); - -G_END_DECLS - -#endif /* __G_HOOK_H__ */ diff --git a/tools/urt/tools/quake3/common/glib/gi18n-lib.h b/tools/urt/tools/quake3/common/glib/gi18n-lib.h deleted file mode 100644 index 8f00588..0000000 --- a/tools/urt/tools/quake3/common/glib/gi18n-lib.h +++ /dev/null @@ -1,53 +0,0 @@ -/* GLIB - Library of useful routines for C programming - * Copyright (C) 1995-1997, 2002 Peter Mattis, Red Hat, Inc. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the - * Free Software Foundation, Inc., 59 Temple Place - Suite 330, - * Boston, MA 02111-1307, USA. - */ -#ifndef __G_I18N_LIB_H__ -#define __G_I18N_LIB_H__ - -#include - -#ifdef ENABLE_NLS - -#include - -#ifndef GETTEXT_PACKAGE -#error You must define GETTEXT_PACKAGE before including gi18n-lib.h. -#endif - -#define _( String ) dgettext( GETTEXT_PACKAGE, String ) -#define Q_( String ) g_strip_context( ( String ), dgettext( GETTEXT_PACKAGE, String ) ) -#ifdef gettext_noop -#define N_( String ) gettext_noop( String ) -#else -#define N_( String ) ( String ) -#endif - -#else /* NLS is disabled */ - -#define _( String ) ( String ) -#define Q_( String ) ( String ) -#define N_( String ) ( String ) -#define textdomain( String ) ( String ) -#define gettext( String ) ( String ) -#define dgettext( Domain,String ) ( String ) -#define dcgettext( Domain,String,Type ) ( String ) -#define bindtextdomain( Domain,Directory ) ( Domain ) - -#endif - -#endif /* __G_I18N_LIB_H__ */ diff --git a/tools/urt/tools/quake3/common/glib/gi18n.h b/tools/urt/tools/quake3/common/glib/gi18n.h deleted file mode 100644 index 3f3f924..0000000 --- a/tools/urt/tools/quake3/common/glib/gi18n.h +++ /dev/null @@ -1,48 +0,0 @@ -/* GLIB - Library of useful routines for C programming - * Copyright (C) 1995-1997, 2002 Peter Mattis, Red Hat, Inc. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the - * Free Software Foundation, Inc., 59 Temple Place - Suite 330, - * Boston, MA 02111-1307, USA. - */ -#ifndef __G_I18N_H__ -#define __G_I18N_H__ - -#include - -#ifdef ENABLE_NLS - -#include -#define _( String ) gettext( String ) -#define Q_( String ) g_strip_context( ( String ), gettext( String ) ) -#ifdef gettext_noop -#define N_( String ) gettext_noop( String ) -#else -#define N_( String ) ( String ) -#endif - -#else /* NLS is disabled */ - -#define _( String ) ( String ) -#define Q_( String ) ( String ) -#define N_( String ) ( String ) -#define textdomain( String ) ( String ) -#define gettext( String ) ( String ) -#define dgettext( Domain,String ) ( String ) -#define dcgettext( Domain,String,Type ) ( String ) -#define bindtextdomain( Domain,Directory ) ( Domain ) - -#endif - -#endif /* __G_I18N_H__ */ diff --git a/tools/urt/tools/quake3/common/glib/giochannel.h b/tools/urt/tools/quake3/common/glib/giochannel.h deleted file mode 100644 index 3ddca48..0000000 --- a/tools/urt/tools/quake3/common/glib/giochannel.h +++ /dev/null @@ -1,350 +0,0 @@ -/* GLIB - Library of useful routines for C programming - * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the - * Free Software Foundation, Inc., 59 Temple Place - Suite 330, - * Boston, MA 02111-1307, USA. - */ - -/* - * Modified by the GLib Team and others 1997-2000. See the AUTHORS - * file for a list of people on the GLib Team. See the ChangeLog - * files for a list of changes. These files are distributed with - * GLib at ftp://ftp.gtk.org/pub/gtk/. - */ - -#ifndef __G_IOCHANNEL_H__ -#define __G_IOCHANNEL_H__ - -#include -#include -#include - -G_BEGIN_DECLS - -/* GIOChannel - */ - -typedef struct _GIOChannel GIOChannel; -typedef struct _GIOFuncs GIOFuncs; - -typedef enum -{ - G_IO_ERROR_NONE, - G_IO_ERROR_AGAIN, - G_IO_ERROR_INVAL, - G_IO_ERROR_UNKNOWN -} GIOError; - -#define G_IO_CHANNEL_ERROR g_io_channel_error_quark() - -typedef enum -{ - /* Derived from errno */ - G_IO_CHANNEL_ERROR_FBIG, - G_IO_CHANNEL_ERROR_INVAL, - G_IO_CHANNEL_ERROR_IO, - G_IO_CHANNEL_ERROR_ISDIR, - G_IO_CHANNEL_ERROR_NOSPC, - G_IO_CHANNEL_ERROR_NXIO, - G_IO_CHANNEL_ERROR_OVERFLOW, - G_IO_CHANNEL_ERROR_PIPE, - /* Other */ - G_IO_CHANNEL_ERROR_FAILED -} GIOChannelError; - -typedef enum -{ - G_IO_STATUS_ERROR, - G_IO_STATUS_NORMAL, - G_IO_STATUS_EOF, - G_IO_STATUS_AGAIN -} GIOStatus; - -typedef enum -{ - G_SEEK_CUR, - G_SEEK_SET, - G_SEEK_END -} GSeekType; - -typedef enum -{ - G_IO_IN GLIB_SYSDEF_POLLIN, - G_IO_OUT GLIB_SYSDEF_POLLOUT, - G_IO_PRI GLIB_SYSDEF_POLLPRI, - G_IO_ERR GLIB_SYSDEF_POLLERR, - G_IO_HUP GLIB_SYSDEF_POLLHUP, - G_IO_NVAL GLIB_SYSDEF_POLLNVAL -} GIOCondition; - -typedef enum -{ - G_IO_FLAG_APPEND = 1 << 0, - G_IO_FLAG_NONBLOCK = 1 << 1, - G_IO_FLAG_IS_READABLE = 1 << 2, /* Read only flag */ - G_IO_FLAG_IS_WRITEABLE = 1 << 3, /* Read only flag */ - G_IO_FLAG_IS_SEEKABLE = 1 << 4, /* Read only flag */ - G_IO_FLAG_MASK = ( 1 << 5 ) - 1, - G_IO_FLAG_GET_MASK = G_IO_FLAG_MASK, - G_IO_FLAG_SET_MASK = G_IO_FLAG_APPEND | G_IO_FLAG_NONBLOCK -} GIOFlags; - -struct _GIOChannel -{ - /*< private >*/ - guint ref_count; - GIOFuncs *funcs; - - gchar *encoding; - GIConv read_cd; - GIConv write_cd; - gchar *line_term; /* String which indicates the end of a line of text */ - guint line_term_len; /* So we can have null in the line term */ - - gsize buf_size; - GString *read_buf; /* Raw data from the channel */ - GString *encoded_read_buf; /* Channel data converted to UTF-8 */ - GString *write_buf; /* Data ready to be written to the file */ - gchar partial_write_buf[6]; /* UTF-8 partial characters, null terminated */ - - /* Group the flags together, immediately after partial_write_buf, to save memory */ - - guint use_buffer : 1; /* The encoding uses the buffers */ - guint do_encode : 1; /* The encoding uses the GIConv coverters */ - guint close_on_unref : 1; /* Close the channel on final unref */ - guint is_readable : 1; /* Cached GIOFlag */ - guint is_writeable : 1; /* ditto */ - guint is_seekable : 1; /* ditto */ - - gpointer reserved1; - gpointer reserved2; -}; - -typedef gboolean ( *GIOFunc )( GIOChannel *source, - GIOCondition condition, - gpointer data ); -struct _GIOFuncs -{ - GIOStatus ( *io_read )( GIOChannel *channel, - gchar *buf, - gsize count, - gsize *bytes_read, - GError **err ); - GIOStatus ( *io_write )( GIOChannel *channel, - const gchar *buf, - gsize count, - gsize *bytes_written, - GError **err ); - GIOStatus ( *io_seek )( GIOChannel *channel, - gint64 offset, - GSeekType type, - GError **err ); - GIOStatus ( *io_close )( GIOChannel *channel, - GError **err ); - GSource* ( *io_create_watch )( GIOChannel * channel, - GIOCondition condition ); - void ( *io_free )( GIOChannel *channel ); - GIOStatus ( *io_set_flags )( GIOChannel *channel, - GIOFlags flags, - GError **err ); - GIOFlags ( *io_get_flags )( GIOChannel *channel ); -}; - -void g_io_channel_init( GIOChannel *channel ); -void g_io_channel_ref( GIOChannel *channel ); -void g_io_channel_unref( GIOChannel *channel ); - -#ifndef G_DISABLE_DEPRECATED -GIOError g_io_channel_read( GIOChannel *channel, - gchar *buf, - gsize count, - gsize *bytes_read ); -GIOError g_io_channel_write( GIOChannel *channel, - const gchar *buf, - gsize count, - gsize *bytes_written ); -GIOError g_io_channel_seek( GIOChannel *channel, - gint64 offset, - GSeekType type ); -void g_io_channel_close( GIOChannel *channel ); -#endif /* G_DISABLE_DEPRECATED */ - -GIOStatus g_io_channel_shutdown( GIOChannel *channel, - gboolean flush, - GError **err ); -guint g_io_add_watch_full( GIOChannel *channel, - gint priority, - GIOCondition condition, - GIOFunc func, - gpointer user_data, - GDestroyNotify notify ); -GSource * g_io_create_watch( GIOChannel *channel, - GIOCondition condition ); -guint g_io_add_watch( GIOChannel *channel, - GIOCondition condition, - GIOFunc func, - gpointer user_data ); - -/* character encoding conversion involved functions. - */ - -void g_io_channel_set_buffer_size( GIOChannel *channel, - gsize size ); -gsize g_io_channel_get_buffer_size( GIOChannel *channel ); -GIOCondition g_io_channel_get_buffer_condition( GIOChannel *channel ); -GIOStatus g_io_channel_set_flags( GIOChannel *channel, - GIOFlags flags, - GError **error ); -GIOFlags g_io_channel_get_flags( GIOChannel *channel ); -void g_io_channel_set_line_term( GIOChannel *channel, - const gchar *line_term, - gint length ); -G_CONST_RETURN gchar* g_io_channel_get_line_term( GIOChannel *channel, - gint *length ); -void g_io_channel_set_buffered( GIOChannel *channel, - gboolean buffered ); -gboolean g_io_channel_get_buffered( GIOChannel *channel ); -GIOStatus g_io_channel_set_encoding( GIOChannel *channel, - const gchar *encoding, - GError **error ); -G_CONST_RETURN gchar* g_io_channel_get_encoding( GIOChannel *channel ); -void g_io_channel_set_close_on_unref( GIOChannel *channel, - gboolean do_close ); -gboolean g_io_channel_get_close_on_unref( GIOChannel *channel ); - - -GIOStatus g_io_channel_flush( GIOChannel *channel, - GError **error ); -GIOStatus g_io_channel_read_line( GIOChannel *channel, - gchar **str_return, - gsize *length, - gsize *terminator_pos, - GError **error ); -GIOStatus g_io_channel_read_line_string( GIOChannel *channel, - GString *buffer, - gsize *terminator_pos, - GError **error ); -GIOStatus g_io_channel_read_to_end( GIOChannel *channel, - gchar **str_return, - gsize *length, - GError **error ); -GIOStatus g_io_channel_read_chars( GIOChannel *channel, - gchar *buf, - gsize count, - gsize *bytes_read, - GError **error ); -GIOStatus g_io_channel_read_unichar( GIOChannel *channel, - gunichar *thechar, - GError **error ); -GIOStatus g_io_channel_write_chars( GIOChannel *channel, - const gchar *buf, - gssize count, - gsize *bytes_written, - GError **error ); -GIOStatus g_io_channel_write_unichar( GIOChannel *channel, - gunichar thechar, - GError **error ); -GIOStatus g_io_channel_seek_position( GIOChannel *channel, - gint64 offset, - GSeekType type, - GError **error ); -GIOChannel* g_io_channel_new_file( const gchar *filename, - const gchar *mode, - GError **error ); - -/* Error handling */ - -GQuark g_io_channel_error_quark( void ); -GIOChannelError g_io_channel_error_from_errno( gint en ); - -/* On Unix, IO channels created with this function for any file - * descriptor or socket. - * - * On Win32, this can be used either for files opened with the MSVCRT - * (the Microsoft run-time C library) _open() or _pipe, including file - * descriptors 0, 1 and 2 (corresponding to stdin, stdout and stderr), - * or for Winsock SOCKETs. If the parameter is a legal file - * descriptor, it is assumed to be such, otherwise it should be a - * SOCKET. This relies on SOCKETs and file descriptors not - * overlapping. If you want to be certain, call either - * g_io_channel_win32_new_fd() or g_io_channel_win32_new_socket() - * instead as appropriate. - * - * The term file descriptor as used in the context of Win32 refers to - * the emulated Unix-like file descriptors MSVCRT provides. The native - * corresponding concept is file HANDLE. There isn't as of yet a way to - * get GIOChannels for Win32 file HANDLEs. - */ -GIOChannel* g_io_channel_unix_new( int fd ); -gint g_io_channel_unix_get_fd( GIOChannel *channel ); - - -/* Hook for GClosure / GSource integration. Don't touch */ -GLIB_VAR GSourceFuncs g_io_watch_funcs; - -#ifdef G_OS_WIN32 - -/* You can use this "pseudo file descriptor" in a GPollFD to add - * polling for Windows messages. GTK applications should not do that. - */ - -#define G_WIN32_MSG_HANDLE 19981206 - -/* Use this to get a GPollFD from a GIOChannel, so that you can call - * g_io_channel_win32_poll(). After calling this you should only use - * g_io_channel_read() to read from the GIOChannel, i.e. never read() - * from the underlying file descriptor. For SOCKETs, it is possible to call - * recv(). - */ -void g_io_channel_win32_make_pollfd( GIOChannel *channel, - GIOCondition condition, - GPollFD *fd ); - -/* This can be used to wait a until at least one of the channels is readable. - * On Unix you would do a select() on the file descriptors of the channels. - */ -gint g_io_channel_win32_poll( GPollFD *fds, - gint n_fds, - gint timeout_ ); - -/* Create an IO channel for Windows messages for window handle hwnd. */ -GIOChannel *g_io_channel_win32_new_messages( guint hwnd ); - -/* Create an IO channel for C runtime (emulated Unix-like) file - * descriptors. After calling g_io_add_watch() on a IO channel - * returned by this function, you shouldn't call read() on the file - * descriptor. This is because adding polling for a file descriptor is - * implemented on Win32 by starting a thread that sits blocked in a - * read() from the file descriptor most of the time. All reads from - * the file descriptor should be done by this internal GLib - * thread. Your code should call only g_io_channel_read(). - */ -GIOChannel* g_io_channel_win32_new_fd( gint fd ); - -/* Get the C runtime file descriptor of a channel. */ -gint g_io_channel_win32_get_fd( GIOChannel *channel ); - -/* Create an IO channel for a winsock socket. The parameter should be - * a SOCKET. Contrary to IO channels for file descriptors (on *Win32), - * you can use normal recv() or recvfrom() on sockets even if GLib - * is polling them. - */ -GIOChannel *g_io_channel_win32_new_socket( gint socket ); - -#endif - -G_END_DECLS - -#endif /* __G_IOCHANNEL_H__ */ diff --git a/tools/urt/tools/quake3/common/glib/glib-2.0.lib b/tools/urt/tools/quake3/common/glib/glib-2.0.lib deleted file mode 100644 index a191cdc..0000000 Binary files a/tools/urt/tools/quake3/common/glib/glib-2.0.lib and /dev/null differ diff --git a/tools/urt/tools/quake3/common/glib/glist.h b/tools/urt/tools/quake3/common/glib/glist.h deleted file mode 100644 index 591c896..0000000 --- a/tools/urt/tools/quake3/common/glib/glist.h +++ /dev/null @@ -1,107 +0,0 @@ -/* GLIB - Library of useful routines for C programming - * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the - * Free Software Foundation, Inc., 59 Temple Place - Suite 330, - * Boston, MA 02111-1307, USA. - */ - -/* - * Modified by the GLib Team and others 1997-2000. See the AUTHORS - * file for a list of people on the GLib Team. See the ChangeLog - * files for a list of changes. These files are distributed with - * GLib at ftp://ftp.gtk.org/pub/gtk/. - */ - -#ifndef __G_LIST_H__ -#define __G_LIST_H__ - -#include - -G_BEGIN_DECLS - -typedef struct _GList GList; - -struct _GList -{ - gpointer data; - GList *next; - GList *prev; -}; - -/* Doubly linked lists - */ -void g_list_push_allocator( GAllocator *allocator ); -void g_list_pop_allocator( void ); -GList* g_list_alloc( void ); -void g_list_free( GList *list ); -void g_list_free_1( GList *list ); -GList* g_list_append( GList *list, - gpointer data ); -GList* g_list_prepend( GList *list, - gpointer data ); -GList* g_list_insert( GList *list, - gpointer data, - gint position ); -GList* g_list_insert_sorted( GList *list, - gpointer data, - GCompareFunc func ); -GList* g_list_insert_before( GList *list, - GList *sibling, - gpointer data ); -GList* g_list_concat( GList *list1, - GList *list2 ); -GList* g_list_remove( GList *list, - gconstpointer data ); -GList* g_list_remove_all( GList *list, - gconstpointer data ); -GList* g_list_remove_link( GList *list, - GList *llink ); -GList* g_list_delete_link( GList *list, - GList *link_ ); -GList* g_list_reverse( GList *list ); -GList* g_list_copy( GList *list ); -GList* g_list_nth( GList *list, - guint n ); -GList* g_list_nth_prev( GList *list, - guint n ); -GList* g_list_find( GList *list, - gconstpointer data ); -GList* g_list_find_custom( GList *list, - gconstpointer data, - GCompareFunc func ); -gint g_list_position( GList *list, - GList *llink ); -gint g_list_index( GList *list, - gconstpointer data ); -GList* g_list_last( GList *list ); -GList* g_list_first( GList *list ); -guint g_list_length( GList *list ); -void g_list_foreach( GList *list, - GFunc func, - gpointer user_data ); -GList* g_list_sort( GList *list, - GCompareFunc compare_func ); -GList* g_list_sort_with_data( GList *list, - GCompareDataFunc compare_func, - gpointer user_data ); -gpointer g_list_nth_data( GList *list, - guint n ); - -#define g_list_previous( list ) ( ( list ) ? ( ( (GList *)( list ) )->prev ) : NULL ) -#define g_list_next( list ) ( ( list ) ? ( ( (GList *)( list ) )->next ) : NULL ) - -G_END_DECLS - -#endif /* __G_LIST_H__ */ diff --git a/tools/urt/tools/quake3/common/glib/gmacros.h b/tools/urt/tools/quake3/common/glib/gmacros.h deleted file mode 100644 index a7c9c10..0000000 --- a/tools/urt/tools/quake3/common/glib/gmacros.h +++ /dev/null @@ -1,242 +0,0 @@ -/* GLIB - Library of useful routines for C programming - * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the - * Free Software Foundation, Inc., 59 Temple Place - Suite 330, - * Boston, MA 02111-1307, USA. - */ - -/* - * Modified by the GLib Team and others 1997-2000. See the AUTHORS - * file for a list of people on the GLib Team. See the ChangeLog - * files for a list of changes. These files are distributed with - * GLib at ftp://ftp.gtk.org/pub/gtk/. - */ - -/* This file must not include any other glib header file and must thus - * not refer to variables from glibconfig.h - */ - -#ifndef __G_MACROS_H__ -#define __G_MACROS_H__ - -/* We include stddef.h to get the system's definition of NULL - */ -#include - -/* Here we provide G_GNUC_EXTENSION as an alias for __extension__, - * where this is valid. This allows for warningless compilation of - * "long long" types even in the presence of '-ansi -pedantic'. - */ -#if __GNUC__ > 2 || ( __GNUC__ == 2 && __GNUC_MINOR__ >= 8 ) -# define G_GNUC_EXTENSION __extension__ -#else -# define G_GNUC_EXTENSION -#endif - -/* Provide macros to feature the GCC function attribute. - */ -#if __GNUC__ > 2 || ( __GNUC__ == 2 && __GNUC_MINOR__ >= 96 ) -#define G_GNUC_PURE \ - __attribute__( ( __pure__ ) ) -#else -#define G_GNUC_PURE -#endif - -#if __GNUC__ > 2 || ( __GNUC__ == 2 && __GNUC_MINOR__ > 4 ) -#define G_GNUC_PRINTF( format_idx, arg_idx ) \ - __attribute__( ( __format__( __printf__, format_idx, arg_idx ) ) ) -#define G_GNUC_SCANF( format_idx, arg_idx ) \ - __attribute__( ( __format__( __scanf__, format_idx, arg_idx ) ) ) -#define G_GNUC_FORMAT( arg_idx ) \ - __attribute__( ( __format_arg__( arg_idx ) ) ) -#define G_GNUC_NORETURN \ - __attribute__( ( __noreturn__ ) ) -#define G_GNUC_CONST \ - __attribute__( ( __const__ ) ) -#define G_GNUC_UNUSED \ - __attribute__( ( __unused__ ) ) -#define G_GNUC_NO_INSTRUMENT \ - __attribute__( ( __no_instrument_function__ ) ) -#else /* !__GNUC__ */ -#define G_GNUC_PRINTF( format_idx, arg_idx ) -#define G_GNUC_SCANF( format_idx, arg_idx ) -#define G_GNUC_FORMAT( arg_idx ) -#define G_GNUC_NORETURN -#define G_GNUC_CONST -#define G_GNUC_UNUSED -#define G_GNUC_NO_INSTRUMENT -#endif /* !__GNUC__ */ - -#if __GNUC__ > 3 || ( __GNUC__ == 3 && __GNUC_MINOR__ >= 1 ) -#define G_GNUC_DEPRECATED \ - __attribute__( ( __deprecated__ ) ) -#else -#define G_GNUC_DEPRECATED -#endif /* __GNUC__ */ - -/* Wrap the gcc __PRETTY_FUNCTION__ and __FUNCTION__ variables with - * macros, so we can refer to them as strings unconditionally. - * usage not-recommended since gcc-3.0 - */ -#if defined ( __GNUC__ ) && ( __GNUC__ < 3 ) -#define G_GNUC_FUNCTION __FUNCTION__ -#define G_GNUC_PRETTY_FUNCTION __PRETTY_FUNCTION__ -#else /* !__GNUC__ */ -#define G_GNUC_FUNCTION "" -#define G_GNUC_PRETTY_FUNCTION "" -#endif /* !__GNUC__ */ - -#define G_STRINGIFY( macro_or_string ) G_STRINGIFY_ARG( macro_or_string ) -#define G_STRINGIFY_ARG( contents ) # contents - -/* Provide a string identifying the current code position */ -#if defined( __GNUC__ ) && ( __GNUC__ < 3 ) && !defined( __cplusplus ) -# define G_STRLOC __FILE__ ":" G_STRINGIFY( __LINE__ ) ":" __PRETTY_FUNCTION__ "()" -#else -# define G_STRLOC __FILE__ ":" G_STRINGIFY( __LINE__ ) -#endif - -/* Provide a string identifying the current function, non-concatenatable */ -#if defined ( __GNUC__ ) -# define G_STRFUNC ( (const char*) ( __PRETTY_FUNCTION__ ) ) -#elif defined ( G_HAVE_ISO_VARARGS ) -# define G_STRFUNC ( (const char*) ( __func__ ) ) -#else -# define G_STRFUNC ( (const char*) ( "???" ) ) -#endif - -/* Guard C code in headers, while including them from C++ */ -#ifdef __cplusplus -# define G_BEGIN_DECLS extern "C" { -# define G_END_DECLS } -#else -# define G_BEGIN_DECLS -# define G_END_DECLS -#endif - -/* Provide definitions for some commonly used macros. - * Some of them are only provided if they haven't already - * been defined. It is assumed that if they are already - * defined then the current definition is correct. - */ -#ifndef NULL -# ifdef __cplusplus -# define NULL ( 0L ) -# else /* !__cplusplus */ -# define NULL ( (void*) 0 ) -# endif /* !__cplusplus */ -#endif - -#ifndef FALSE -#define FALSE ( 0 ) -#endif - -#ifndef TRUE -#define TRUE ( !FALSE ) -#endif - -#undef MAX -#define MAX( a, b ) ( ( ( a ) > ( b ) ) ? ( a ) : ( b ) ) - -#undef MIN -#define MIN( a, b ) ( ( ( a ) < ( b ) ) ? ( a ) : ( b ) ) - -#undef ABS -#define ABS( a ) ( ( ( a ) < 0 ) ? -( a ) : ( a ) ) - -#undef CLAMP -#define CLAMP( x, low, high ) ( ( ( x ) > ( high ) ) ? ( high ) : ( ( ( x ) < ( low ) ) ? ( low ) : ( x ) ) ) - -/* Count the number of elements in an array. The array must be defined - * as such; using this with a dynamically allocated array will give - * incorrect results. - */ -#define G_N_ELEMENTS( arr ) ( sizeof( arr ) / sizeof( ( arr )[0] ) ) - -/* Macros by analogy to GINT_TO_POINTER, GPOINTER_TO_INT - */ -#define GPOINTER_TO_SIZE( p ) ( (gsize) ( p ) ) -#define GSIZE_TO_POINTER( s ) ( (gpointer) (gsize) ( s ) ) - -/* Provide convenience macros for handling structure - * fields through their offsets. - */ -#define G_STRUCT_OFFSET( struct_type, member ) \ - ( (glong) ( (guint8*) &( (struct_type*) 0 )->member ) ) -#define G_STRUCT_MEMBER_P( struct_p, struct_offset ) \ - ( (gpointer) ( (guint8*) ( struct_p ) + (glong) ( struct_offset ) ) ) -#define G_STRUCT_MEMBER( member_type, struct_p, struct_offset ) \ - ( *(member_type*) G_STRUCT_MEMBER_P( ( struct_p ), ( struct_offset ) ) ) - -/* Provide simple macro statement wrappers (adapted from Perl): - * G_STMT_START { statements; } G_STMT_END; - * can be used as a single statement, as in - * if (x) G_STMT_START { ... } G_STMT_END; else ... - * - * For gcc we will wrap the statements within `({' and `})' braces. - * For SunOS they will be wrapped within `if (1)' and `else (void) 0', - * and otherwise within `do' and `while (0)'. - */ -#if !( defined ( G_STMT_START ) && defined ( G_STMT_END ) ) -# if defined ( __GNUC__ ) && !defined ( __STRICT_ANSI__ ) && !defined ( __cplusplus ) -# define G_STMT_START (void) __extension__( -# define G_STMT_END ) -# else -# if ( defined ( sun ) || defined ( __sun__ ) ) -# define G_STMT_START if ( 1 ) -# define G_STMT_END else (void)0 -# else -# define G_STMT_START do -# define G_STMT_END while ( 0 ) -# endif -# endif -#endif - -/* Allow the app programmer to select whether or not return values - * (usually char*) are const or not. Don't try using this feature for - * functions with C++ linkage. - */ -#ifdef G_DISABLE_CONST_RETURNS -#define G_CONST_RETURN -#else -#define G_CONST_RETURN const -#endif - -/* - * The G_LIKELY and G_UNLIKELY macros let the programmer give hints to - * the compiler about the expected result of an expression. Some compilers - * can use this information for optimizations. - * - * The _G_BOOLEAN_EXPR macro is intended to trigger a gcc warning when - * putting assignments in g_return_if_fail (). - */ -#if defined( __GNUC__ ) && ( __GNUC__ > 2 ) && defined( __OPTIMIZE__ ) -#define _G_BOOLEAN_EXPR( expr ) \ - __extension__( { \ - int _g_boolean_var_; \ - if ( expr ) { \ - _g_boolean_var_ = 1; } \ - else{ \ - _g_boolean_var_ = 0; } \ - _g_boolean_var_; \ - } ) -#define G_LIKELY( expr ) ( __builtin_expect( _G_BOOLEAN_EXPR( expr ), 1 ) ) -#define G_UNLIKELY( expr ) ( __builtin_expect( _G_BOOLEAN_EXPR( expr ), 0 ) ) -#else -#define G_LIKELY( expr ) ( expr ) -#define G_UNLIKELY( expr ) ( expr ) -#endif - -#endif /* __G_MACROS_H__ */ diff --git a/tools/urt/tools/quake3/common/glib/gmain.h b/tools/urt/tools/quake3/common/glib/gmain.h deleted file mode 100644 index 24368b1..0000000 --- a/tools/urt/tools/quake3/common/glib/gmain.h +++ /dev/null @@ -1,318 +0,0 @@ -/* gmain.h - the GLib Main loop - * Copyright (C) 1998-2000 Red Hat, Inc. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public - * License along with this library; if not, write to the - * Free Software Foundation, Inc., 59 Temple Place - Suite 330, - * Boston, MA 02111-1307, USA. - */ - -#ifndef __G_MAIN_H__ -#define __G_MAIN_H__ - -#include -#include - -G_BEGIN_DECLS - -typedef struct _GMainContext GMainContext; /* Opaque */ -typedef struct _GMainLoop GMainLoop; /* Opaque */ -typedef struct _GSource GSource; -typedef struct _GSourceCallbackFuncs GSourceCallbackFuncs; -typedef struct _GSourceFuncs GSourceFuncs; - -typedef gboolean ( *GSourceFunc )( gpointer data ); -typedef void ( *GChildWatchFunc )( GPid pid, - gint status, - gpointer data ); -struct _GSource -{ - /*< private >*/ - gpointer callback_data; - GSourceCallbackFuncs *callback_funcs; - - GSourceFuncs *source_funcs; - guint ref_count; - - GMainContext *context; - - gint priority; - guint flags; - guint source_id; - - GSList *poll_fds; - - GSource *prev; - GSource *next; - - gpointer reserved1; - gpointer reserved2; -}; - -struct _GSourceCallbackFuncs -{ - void ( *ref )( gpointer cb_data ); - void ( *unref )( gpointer cb_data ); - void ( *get )( gpointer cb_data, - GSource *source, - GSourceFunc *func, - gpointer *data ); -}; - -typedef void ( *GSourceDummyMarshal )( void ); - -struct _GSourceFuncs -{ - gboolean ( *prepare )( GSource *source, - gint *timeout_ ); - gboolean ( *check )( GSource *source ); - gboolean ( *dispatch )( GSource *source, - GSourceFunc callback, - gpointer user_data ); - void ( *finalize )( GSource *source ); /* Can be NULL */ - - /* For use by g_source_set_closure */ - GSourceFunc closure_callback; - GSourceDummyMarshal closure_marshal; /* Really is of type GClosureMarshal */ -}; - -/* Any definitions using GPollFD or GPollFunc are primarily - * for Unix and not guaranteed to be the compatible on all - * operating systems on which GLib runs. Right now, the - * GLib does use these functions on Win32 as well, but interprets - * them in a fairly different way than on Unix. If you use - * these definitions, you are should be prepared to recode - * for different operating systems. - * - * - * On Win32, the fd in a GPollFD should be Win32 HANDLE (*not* a file - * descriptor as provided by the C runtime) that can be used by - * MsgWaitForMultipleObjects. This does *not* include file handles - * from CreateFile, SOCKETs, nor pipe handles. (But you can use - * WSAEventSelect to signal events when a SOCKET is readable). - * - * On Win32, fd can also be the special value G_WIN32_MSG_HANDLE to - * indicate polling for messages. - * - * But note that G_WIN32_MSG_HANDLE GPollFDs should not be used by GDK - * (GTK) programs, as GDK itself wants to read messages and convert them - * to GDK events. - * - * So, unless you really know what you are doing, it's best not to try - * to use the main loop polling stuff for your own needs on - * Win32. It's really only written for the GIMP's needs so - * far. - */ -typedef struct _GPollFD GPollFD; -typedef gint ( *GPollFunc )( GPollFD *ufds, - guint nfsd, - gint timeout_ ); - -struct _GPollFD -{ - gint fd; - gushort events; - gushort revents; -}; - -/* Standard priorities */ - -#define G_PRIORITY_HIGH -100 -#define G_PRIORITY_DEFAULT 0 -#define G_PRIORITY_HIGH_IDLE 100 -#define G_PRIORITY_DEFAULT_IDLE 200 -#define G_PRIORITY_LOW 300 - -/* GMainContext: */ - -GMainContext *g_main_context_new( void ); -void g_main_context_ref( GMainContext *context ); -void g_main_context_unref( GMainContext *context ); -GMainContext *g_main_context_default( void ); - -gboolean g_main_context_iteration( GMainContext *context, - gboolean may_block ); -gboolean g_main_context_pending( GMainContext *context ); - -/* For implementation of legacy interfaces - */ -GSource *g_main_context_find_source_by_id( GMainContext *context, - guint source_id ); -GSource *g_main_context_find_source_by_user_data( GMainContext *context, - gpointer user_data ); -GSource *g_main_context_find_source_by_funcs_user_data( GMainContext *context, - GSourceFuncs *funcs, - gpointer user_data ); - -/* Low level functions for implementing custom main loops. - */ -void g_main_context_wakeup( GMainContext *context ); -gboolean g_main_context_acquire( GMainContext *context ); -void g_main_context_release( GMainContext *context ); -gboolean g_main_context_wait( GMainContext *context, - GCond *cond, - GMutex *mutex ); - -gboolean g_main_context_prepare( GMainContext *context, - gint *priority ); -gint g_main_context_query( GMainContext *context, - gint max_priority, - gint *timeout_, - GPollFD *fds, - gint n_fds ); -gint g_main_context_check( GMainContext *context, - gint max_priority, - GPollFD *fds, - gint n_fds ); -void g_main_context_dispatch( GMainContext *context ); - -void g_main_context_set_poll_func( GMainContext *context, - GPollFunc func ); -GPollFunc g_main_context_get_poll_func( GMainContext *context ); - -/* Low level functions for use by source implementations - */ -void g_main_context_add_poll( GMainContext *context, - GPollFD *fd, - gint priority ); -void g_main_context_remove_poll( GMainContext *context, - GPollFD *fd ); - -int g_main_depth( void ); - -/* GMainLoop: */ - -GMainLoop *g_main_loop_new( GMainContext *context, - gboolean is_running ); -void g_main_loop_run( GMainLoop *loop ); -void g_main_loop_quit( GMainLoop *loop ); -GMainLoop *g_main_loop_ref( GMainLoop *loop ); -void g_main_loop_unref( GMainLoop *loop ); -gboolean g_main_loop_is_running( GMainLoop *loop ); -GMainContext *g_main_loop_get_context( GMainLoop *loop ); - -/* GSource: */ - -GSource *g_source_new( GSourceFuncs *source_funcs, - guint struct_size ); -GSource *g_source_ref( GSource *source ); -void g_source_unref( GSource *source ); - -guint g_source_attach( GSource *source, - GMainContext *context ); -void g_source_destroy( GSource *source ); - -void g_source_set_priority( GSource *source, - gint priority ); -gint g_source_get_priority( GSource *source ); -void g_source_set_can_recurse( GSource *source, - gboolean can_recurse ); -gboolean g_source_get_can_recurse( GSource *source ); -guint g_source_get_id( GSource *source ); - -GMainContext *g_source_get_context( GSource *source ); - -void g_source_set_callback( GSource *source, - GSourceFunc func, - gpointer data, - GDestroyNotify notify ); - - -/* Used to implement g_source_connect_closure and internally*/ -void g_source_set_callback_indirect( GSource *source, - gpointer callback_data, - GSourceCallbackFuncs *callback_funcs ); - -void g_source_add_poll( GSource *source, - GPollFD *fd ); -void g_source_remove_poll( GSource *source, - GPollFD *fd ); - -void g_source_get_current_time( GSource *source, - GTimeVal *timeval ); - -/* void g_source_connect_closure (GSource *source, - GClosure *closure); - */ - -/* Specific source types - */ -GSource *g_idle_source_new( void ); -GSource *g_child_watch_source_new( GPid pid ); -GSource *g_timeout_source_new( guint interval ); - -/* Miscellaneous functions - */ -void g_get_current_time( GTimeVal *result ); - -/* ============== Compat main loop stuff ================== */ - -#ifndef G_DISABLE_DEPRECATED - -/* Legacy names for GMainLoop functions - */ -#define g_main_new( is_running ) g_main_loop_new( NULL, is_running ); -#define g_main_run( loop ) g_main_loop_run( loop ) -#define g_main_quit( loop ) g_main_loop_quit( loop ) -#define g_main_destroy( loop ) g_main_loop_unref( loop ) -#define g_main_is_running( loop ) g_main_loop_is_running( loop ) - -/* Functions to manipulate the default main loop - */ - -#define g_main_iteration( may_block ) g_main_context_iteration( NULL, may_block ) -#define g_main_pending() g_main_context_pending( NULL ) - -#define g_main_set_poll_func( func ) g_main_context_set_poll_func( NULL, func ) - -#endif /* G_DISABLE_DEPRECATED */ - -/* Source manipulation by ID */ -gboolean g_source_remove( guint tag ); -gboolean g_source_remove_by_user_data( gpointer user_data ); -gboolean g_source_remove_by_funcs_user_data( GSourceFuncs *funcs, - gpointer user_data ); - -/* Idles, child watchers and timeouts */ -guint g_timeout_add_full( gint priority, - guint interval, - GSourceFunc function, - gpointer data, - GDestroyNotify notify ); -guint g_timeout_add( guint interval, - GSourceFunc function, - gpointer data ); -guint g_child_watch_add_full( gint priority, - GPid pid, - GChildWatchFunc function, - gpointer data, - GDestroyNotify notify ); -guint g_child_watch_add( GPid pid, - GChildWatchFunc function, - gpointer data ); -guint g_idle_add( GSourceFunc function, - gpointer data ); -guint g_idle_add_full( gint priority, - GSourceFunc function, - gpointer data, - GDestroyNotify notify ); -gboolean g_idle_remove_by_data( gpointer data ); - -/* Hook for GClosure / GSource integration. Don't touch */ -GLIB_VAR GSourceFuncs g_timeout_funcs; -GLIB_VAR GSourceFuncs g_child_watch_funcs; -GLIB_VAR GSourceFuncs g_idle_funcs; - -G_END_DECLS - -#endif /* __G_MAIN_H__ */ diff --git a/tools/urt/tools/quake3/common/glib/gmarkup.h b/tools/urt/tools/quake3/common/glib/gmarkup.h deleted file mode 100644 index 8330fec..0000000 --- a/tools/urt/tools/quake3/common/glib/gmarkup.h +++ /dev/null @@ -1,130 +0,0 @@ -/* gmarkup.h - Simple XML-like string parser/writer - * - * Copyright 2000 Red Hat, Inc. - * - * GLib is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 of the - * License, or (at your option) any later version. - * - * GLib is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with GLib; see the file COPYING.LIB. If not, - * write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, - * Boston, MA 02111-1307, USA. - */ - -#ifndef __G_MARKUP_H__ -#define __G_MARKUP_H__ - -#include - -#include - -G_BEGIN_DECLS - -typedef enum -{ - G_MARKUP_ERROR_BAD_UTF8, - G_MARKUP_ERROR_EMPTY, - G_MARKUP_ERROR_PARSE, - /* These three are primarily intended for specific GMarkupParser - * implementations to set. - */ - G_MARKUP_ERROR_UNKNOWN_ELEMENT, - G_MARKUP_ERROR_UNKNOWN_ATTRIBUTE, - G_MARKUP_ERROR_INVALID_CONTENT -} GMarkupError; - -#define G_MARKUP_ERROR g_markup_error_quark() - -GQuark g_markup_error_quark( void ); - -typedef enum -{ - /* Hmm, can't think of any at the moment */ - G_MARKUP_DO_NOT_USE_THIS_UNSUPPORTED_FLAG = 1 << 0 - -} GMarkupParseFlags; - -typedef struct _GMarkupParseContext GMarkupParseContext; -typedef struct _GMarkupParser GMarkupParser; - -struct _GMarkupParser -{ - /* Called for open tags */ - void ( *start_element )( GMarkupParseContext *context, - const gchar *element_name, - const gchar **attribute_names, - const gchar **attribute_values, - gpointer user_data, - GError **error ); - - /* Called for close tags */ - void ( *end_element )( GMarkupParseContext *context, - const gchar *element_name, - gpointer user_data, - GError **error ); - - /* Called for character data */ - /* text is not nul-terminated */ - void ( *text )( GMarkupParseContext *context, - const gchar *text, - gsize text_len, - gpointer user_data, - GError **error ); - - /* Called for strings that should be re-saved verbatim in this same - * position, but are not otherwise interpretable. At the moment - * this includes comments and processing instructions. - */ - /* text is not nul-terminated. */ - void ( *passthrough )( GMarkupParseContext *context, - const gchar *passthrough_text, - gsize text_len, - gpointer user_data, - GError **error ); - - /* Called on error, including one set by other - * methods in the vtable. The GError should not be freed. - */ - void ( *error )( GMarkupParseContext *context, - GError *error, - gpointer user_data ); -}; - -GMarkupParseContext *g_markup_parse_context_new( const GMarkupParser *parser, - GMarkupParseFlags flags, - gpointer user_data, - GDestroyNotify user_data_dnotify ); -void g_markup_parse_context_free( GMarkupParseContext *context ); -gboolean g_markup_parse_context_parse( GMarkupParseContext *context, - const gchar *text, - gssize text_len, - GError **error ); - -gboolean g_markup_parse_context_end_parse( GMarkupParseContext *context, - GError **error ); -G_CONST_RETURN gchar *g_markup_parse_context_get_element( GMarkupParseContext *context ); - -/* For user-constructed error messages, has no precise semantics */ -void g_markup_parse_context_get_position( GMarkupParseContext *context, - gint *line_number, - gint *char_number ); - -/* useful when saving */ -gchar* g_markup_escape_text( const gchar *text, - gssize length ); - -gchar *g_markup_printf_escaped( const char *format, - ... ) G_GNUC_PRINTF( 1, 2 ); -gchar *g_markup_vprintf_escaped( const char *format, - va_list args ); - -G_END_DECLS - -#endif /* __G_MARKUP_H__ */ diff --git a/tools/urt/tools/quake3/common/glib/gmem.h b/tools/urt/tools/quake3/common/glib/gmem.h deleted file mode 100644 index a9ab7e2..0000000 --- a/tools/urt/tools/quake3/common/glib/gmem.h +++ /dev/null @@ -1,174 +0,0 @@ -/* GLIB - Library of useful routines for C programming - * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the - * Free Software Foundation, Inc., 59 Temple Place - Suite 330, - * Boston, MA 02111-1307, USA. - */ - -/* - * Modified by the GLib Team and others 1997-2000. See the AUTHORS - * file for a list of people on the GLib Team. See the ChangeLog - * files for a list of changes. These files are distributed with - * GLib at ftp://ftp.gtk.org/pub/gtk/. - */ - -#ifndef __G_MEM_H__ -#define __G_MEM_H__ - -#include - -G_BEGIN_DECLS - -typedef struct _GAllocator GAllocator; -typedef struct _GMemChunk GMemChunk; -typedef struct _GMemVTable GMemVTable; - - -#if GLIB_SIZEOF_VOID_P > GLIB_SIZEOF_LONG -# define G_MEM_ALIGN GLIB_SIZEOF_VOID_P -#else /* GLIB_SIZEOF_VOID_P <= GLIB_SIZEOF_LONG */ -# define G_MEM_ALIGN GLIB_SIZEOF_LONG -#endif /* GLIB_SIZEOF_VOID_P <= GLIB_SIZEOF_LONG */ - - -/* Memory allocation functions - */ -gpointer g_malloc( gulong n_bytes ); -gpointer g_malloc0( gulong n_bytes ); -gpointer g_realloc( gpointer mem, - gulong n_bytes ); -void g_free( gpointer mem ); -gpointer g_try_malloc( gulong n_bytes ); -gpointer g_try_realloc( gpointer mem, - gulong n_bytes ); - - -/* Convenience memory allocators - */ -#define g_new( struct_type, n_structs ) \ - ( (struct_type *) g_malloc( ( (gsize) sizeof( struct_type ) ) * ( (gsize) ( n_structs ) ) ) ) -#define g_new0( struct_type, n_structs ) \ - ( (struct_type *) g_malloc0( ( (gsize) sizeof( struct_type ) ) * ( (gsize) ( n_structs ) ) ) ) -#define g_renew( struct_type, mem, n_structs ) \ - ( (struct_type *) g_realloc( ( mem ), ( (gsize) sizeof( struct_type ) ) * ( (gsize) ( n_structs ) ) ) ) - - -/* Memory allocation virtualization for debugging purposes - * g_mem_set_vtable() has to be the very first GLib function called - * if being used - */ -struct _GMemVTable -{ - gpointer ( *malloc )( gsize n_bytes ); - gpointer ( *realloc )( gpointer mem, - gsize n_bytes ); - void ( *free )( gpointer mem ); - /* optional; set to NULL if not used ! */ - gpointer ( *calloc )( gsize n_blocks, - gsize n_block_bytes ); - gpointer ( *try_malloc )( gsize n_bytes ); - gpointer ( *try_realloc )( gpointer mem, - gsize n_bytes ); -}; -void g_mem_set_vtable( GMemVTable *vtable ); -gboolean g_mem_is_system_malloc( void ); - -/* Memory profiler and checker, has to be enabled via g_mem_set_vtable() - */ -GLIB_VAR GMemVTable *glib_mem_profiler_table; -void g_mem_profile( void ); - - -/* Memchunk convenience functions - */ -#define g_mem_chunk_create( type, pre_alloc, alloc_type ) ( \ - g_mem_chunk_new( # type " mem chunks (" # pre_alloc ")", \ - sizeof( type ), \ - sizeof( type ) * ( pre_alloc ), \ - ( alloc_type ) ) \ - ) -#define g_chunk_new( type, chunk ) ( \ - (type *) g_mem_chunk_alloc( chunk ) \ - ) -#define g_chunk_new0( type, chunk ) ( \ - (type *) g_mem_chunk_alloc0( chunk ) \ - ) -#define g_chunk_free( mem, mem_chunk ) G_STMT_START { \ - g_mem_chunk_free( ( mem_chunk ), ( mem ) ); \ -} G_STMT_END - - -/* "g_mem_chunk_new" creates a new memory chunk. - * Memory chunks are used to allocate pieces of memory which are - * always the same size. Lists are a good example of such a data type. - * The memory chunk allocates and frees blocks of memory as needed. - * Just be sure to call "g_mem_chunk_free" and not "g_free" on data - * allocated in a mem chunk. ("g_free" will most likely cause a seg - * fault...somewhere). - * - * Oh yeah, GMemChunk is an opaque data type. (You don't really - * want to know what's going on inside do you?) - */ - -/* ALLOC_ONLY MemChunks can only allocate memory. The free operation - * is interpreted as a no op. ALLOC_ONLY MemChunks save 4 bytes per - * atom. (They are also useful for lists which use MemChunk to allocate - * memory but are also part of the MemChunk implementation). - * ALLOC_AND_FREE MemChunks can allocate and free memory. - */ - -#define G_ALLOC_ONLY 1 -#define G_ALLOC_AND_FREE 2 - -GMemChunk* g_mem_chunk_new( const gchar *name, - gint atom_size, - gulong area_size, - gint type ); -void g_mem_chunk_destroy( GMemChunk *mem_chunk ); -gpointer g_mem_chunk_alloc( GMemChunk *mem_chunk ); -gpointer g_mem_chunk_alloc0( GMemChunk *mem_chunk ); -void g_mem_chunk_free( GMemChunk *mem_chunk, - gpointer mem ); -void g_mem_chunk_clean( GMemChunk *mem_chunk ); -void g_mem_chunk_reset( GMemChunk *mem_chunk ); -void g_mem_chunk_print( GMemChunk *mem_chunk ); -void g_mem_chunk_info( void ); - -/* Ah yes...we have a "g_blow_chunks" function. - * "g_blow_chunks" simply compresses all the chunks. This operation - * consists of freeing every memory area that should be freed (but - * which we haven't gotten around to doing yet). And, no, - * "g_blow_chunks" doesn't follow the naming scheme, but it is a - * much better name than "g_mem_chunk_clean_all" or something - * similar. - */ -void g_blow_chunks( void ); - - -/* Generic allocators - */ -GAllocator* g_allocator_new( const gchar *name, - guint n_preallocs ); -void g_allocator_free( GAllocator *allocator ); - -/* internal */ -#define G_ALLOCATOR_LIST ( 1 ) -#define G_ALLOCATOR_SLIST ( 2 ) -#define G_ALLOCATOR_NODE ( 3 ) - - -G_END_DECLS - -#endif /* __G_MEM_H__ */ diff --git a/tools/urt/tools/quake3/common/glib/gmessages.h b/tools/urt/tools/quake3/common/glib/gmessages.h deleted file mode 100644 index 06445bf..0000000 --- a/tools/urt/tools/quake3/common/glib/gmessages.h +++ /dev/null @@ -1,343 +0,0 @@ -/* GLIB - Library of useful routines for C programming - * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the - * Free Software Foundation, Inc., 59 Temple Place - Suite 330, - * Boston, MA 02111-1307, USA. - */ - -/* - * Modified by the GLib Team and others 1997-2000. See the AUTHORS - * file for a list of people on the GLib Team. See the ChangeLog - * files for a list of changes. These files are distributed with - * GLib at ftp://ftp.gtk.org/pub/gtk/. - */ - -#ifndef __G_MESSAGES_H__ -#define __G_MESSAGES_H__ - -#include -#include -#include - -/* Suppress warnings when GCC is in -pedantic mode and not -std=c99 - */ -#if ( __GNUC__ >= 3 || ( __GNUC__ == 2 && __GNUC_MINOR__ >= 96 ) ) -#pragma GCC system_header -#endif - -G_BEGIN_DECLS - -/* calculate a string size, guaranteed to fit format + args. - */ -gsize g_printf_string_upper_bound( const gchar* format, - va_list args ); - -/* Log level shift offset for user defined - * log levels (0-7 are used by GLib). - */ -#define G_LOG_LEVEL_USER_SHIFT ( 8 ) - -/* Glib log levels and flags. - */ -typedef enum -{ - /* log flags */ - G_LOG_FLAG_RECURSION = 1 << 0, - G_LOG_FLAG_FATAL = 1 << 1, - - /* GLib log levels */ - G_LOG_LEVEL_ERROR = 1 << 2, /* always fatal */ - G_LOG_LEVEL_CRITICAL = 1 << 3, - G_LOG_LEVEL_WARNING = 1 << 4, - G_LOG_LEVEL_MESSAGE = 1 << 5, - G_LOG_LEVEL_INFO = 1 << 6, - G_LOG_LEVEL_DEBUG = 1 << 7, - - G_LOG_LEVEL_MASK = ~( G_LOG_FLAG_RECURSION | G_LOG_FLAG_FATAL ) -} GLogLevelFlags; - -/* GLib log levels that are considered fatal by default */ -#define G_LOG_FATAL_MASK ( G_LOG_FLAG_RECURSION | G_LOG_LEVEL_ERROR ) - -typedef void ( *GLogFunc )( const gchar *log_domain, - GLogLevelFlags log_level, - const gchar *message, - gpointer user_data ); - -/* Logging mechanism - */ -guint g_log_set_handler( const gchar *log_domain, - GLogLevelFlags log_levels, - GLogFunc log_func, - gpointer user_data ); -void g_log_remove_handler( const gchar *log_domain, - guint handler_id ); -void g_log_default_handler( const gchar *log_domain, - GLogLevelFlags log_level, - const gchar *message, - gpointer unused_data ); -void g_log( const gchar *log_domain, - GLogLevelFlags log_level, - const gchar *format, - ... ) G_GNUC_PRINTF( 3, 4 ); -void g_logv( const gchar *log_domain, - GLogLevelFlags log_level, - const gchar *format, - va_list args ); -GLogLevelFlags g_log_set_fatal_mask( const gchar *log_domain, - GLogLevelFlags fatal_mask ); -GLogLevelFlags g_log_set_always_fatal( GLogLevelFlags fatal_mask ); - -/* internal */ -void _g_log_fallback_handler( const gchar *log_domain, - GLogLevelFlags log_level, - const gchar *message, - gpointer unused_data ); - - -#ifndef G_LOG_DOMAIN -#define G_LOG_DOMAIN ( (gchar*) 0 ) -#endif /* G_LOG_DOMAIN */ -#ifdef G_HAVE_ISO_VARARGS -#define g_error( ... ) g_log( G_LOG_DOMAIN, \ - G_LOG_LEVEL_ERROR, \ - __VA_ARGS__ ) -#define g_message( ... ) g_log( G_LOG_DOMAIN, \ - G_LOG_LEVEL_MESSAGE, \ - __VA_ARGS__ ) -#define g_critical( ... ) g_log( G_LOG_DOMAIN, \ - G_LOG_LEVEL_CRITICAL, \ - __VA_ARGS__ ) -#define g_warning( ... ) g_log( G_LOG_DOMAIN, \ - G_LOG_LEVEL_WARNING, \ - __VA_ARGS__ ) -#elif defined( G_HAVE_GNUC_VARARGS ) -#define g_error( format ... ) g_log( G_LOG_DOMAIN, \ - G_LOG_LEVEL_ERROR, \ - format ) -#define g_message( format ... ) g_log( G_LOG_DOMAIN, \ - G_LOG_LEVEL_MESSAGE, \ - format ) -#define g_critical( format ... ) g_log( G_LOG_DOMAIN, \ - G_LOG_LEVEL_CRITICAL, \ - format ) -#define g_warning( format ... ) g_log( G_LOG_DOMAIN, \ - G_LOG_LEVEL_WARNING, \ - format ) -#else /* no varargs macros */ -static void -g_error( const gchar *format, - ... ){ - va_list args; - va_start( args, format ); - g_logv( G_LOG_DOMAIN, G_LOG_LEVEL_ERROR, format, args ); - va_end( args ); -} -static void -g_message( const gchar *format, - ... ){ - va_list args; - va_start( args, format ); - g_logv( G_LOG_DOMAIN, G_LOG_LEVEL_MESSAGE, format, args ); - va_end( args ); -} -static void -g_critical( const gchar *format, - ... ){ - va_list args; - va_start( args, format ); - g_logv( G_LOG_DOMAIN, G_LOG_LEVEL_CRITICAL, format, args ); - va_end( args ); -} -static void -g_warning( const gchar *format, - ... ){ - va_list args; - va_start( args, format ); - g_logv( G_LOG_DOMAIN, G_LOG_LEVEL_WARNING, format, args ); - va_end( args ); -} -#endif /* !__GNUC__ */ - -typedef void ( *GPrintFunc )( const gchar *string ); -void g_print( const gchar *format, - ... ) G_GNUC_PRINTF( 1, 2 ); -GPrintFunc g_set_print_handler( GPrintFunc func ); -void g_printerr( const gchar *format, - ... ) G_GNUC_PRINTF( 1, 2 ); -GPrintFunc g_set_printerr_handler( GPrintFunc func ); - - -/* Provide macros for error handling. The "assert" macros will - * exit on failure. The "return" macros will exit the current - * function. Two different definitions are given for the macros - * if G_DISABLE_ASSERT is not defined, in order to support gcc's - * __PRETTY_FUNCTION__ capability. - */ - -#ifdef G_DISABLE_ASSERT - -#define g_assert( expr ) G_STMT_START { (void)0; } G_STMT_END -#define g_assert_not_reached() G_STMT_START { (void)0; } G_STMT_END - -#else /* !G_DISABLE_ASSERT */ - -#ifdef __GNUC__ - -#define g_assert( expr ) G_STMT_START { \ - if G_LIKELY( expr ) { } else{ \ - g_log( G_LOG_DOMAIN, \ - G_LOG_LEVEL_ERROR, \ - "file %s: line %d (%s): assertion failed: (%s)", \ - __FILE__, \ - __LINE__, \ - __PRETTY_FUNCTION__, \ - # expr ); } } G_STMT_END - -#define g_assert_not_reached() G_STMT_START { \ - g_log( G_LOG_DOMAIN, \ - G_LOG_LEVEL_ERROR, \ - "file %s: line %d (%s): should not be reached", \ - __FILE__, \ - __LINE__, \ - __PRETTY_FUNCTION__ ); } G_STMT_END - -#else /* !__GNUC__ */ - -#define g_assert( expr ) G_STMT_START { \ - if ( expr ) { } else{ \ - g_log( G_LOG_DOMAIN, \ - G_LOG_LEVEL_ERROR, \ - "file %s: line %d: assertion failed: (%s)", \ - __FILE__, \ - __LINE__, \ - # expr ); } } G_STMT_END - -#define g_assert_not_reached() G_STMT_START { \ - g_log( G_LOG_DOMAIN, \ - G_LOG_LEVEL_ERROR, \ - "file %s: line %d: should not be reached", \ - __FILE__, \ - __LINE__ ); } G_STMT_END - -#endif /* __GNUC__ */ - -#endif /* !G_DISABLE_ASSERT */ - - -#ifdef G_DISABLE_CHECKS - -#define g_return_if_fail( expr ) G_STMT_START { (void)0; } G_STMT_END -#define g_return_val_if_fail( expr,val ) G_STMT_START { (void)0; } G_STMT_END -#define g_return_if_reached() G_STMT_START { return; } G_STMT_END -#define g_return_val_if_reached( val ) G_STMT_START { return ( val ); } G_STMT_END - -#else /* !G_DISABLE_CHECKS */ - -#ifdef __GNUC__ - -#define g_return_if_fail( expr ) G_STMT_START { \ - if G_LIKELY( expr ) { } else \ - { \ - g_log( G_LOG_DOMAIN, \ - G_LOG_LEVEL_CRITICAL, \ - "file %s: line %d (%s): assertion `%s' failed", \ - __FILE__, \ - __LINE__, \ - __PRETTY_FUNCTION__, \ - # expr ); \ - return; \ - }; } G_STMT_END - -#define g_return_val_if_fail( expr,val ) G_STMT_START { \ - if G_LIKELY( expr ) { } else \ - { \ - g_log( G_LOG_DOMAIN, \ - G_LOG_LEVEL_CRITICAL, \ - "file %s: line %d (%s): assertion `%s' failed", \ - __FILE__, \ - __LINE__, \ - __PRETTY_FUNCTION__, \ - # expr ); \ - return ( val ); \ - }; } G_STMT_END - -#define g_return_if_reached() G_STMT_START { \ - g_log( G_LOG_DOMAIN, \ - G_LOG_LEVEL_CRITICAL, \ - "file %s: line %d (%s): should not be reached", \ - __FILE__, \ - __LINE__, \ - __PRETTY_FUNCTION__ ); \ - return; } G_STMT_END - -#define g_return_val_if_reached( val ) G_STMT_START { \ - g_log( G_LOG_DOMAIN, \ - G_LOG_LEVEL_CRITICAL, \ - "file %s: line %d (%s): should not be reached", \ - __FILE__, \ - __LINE__, \ - __PRETTY_FUNCTION__ ); \ - return ( val ); } G_STMT_END - -#else /* !__GNUC__ */ - -#define g_return_if_fail( expr ) G_STMT_START { \ - if ( expr ) { } else \ - { \ - g_log( G_LOG_DOMAIN, \ - G_LOG_LEVEL_CRITICAL, \ - "file %s: line %d: assertion `%s' failed", \ - __FILE__, \ - __LINE__, \ - # expr ); \ - return; \ - }; } G_STMT_END - -#define g_return_val_if_fail( expr, val ) G_STMT_START { \ - if ( expr ) { } else \ - { \ - g_log( G_LOG_DOMAIN, \ - G_LOG_LEVEL_CRITICAL, \ - "file %s: line %d: assertion `%s' failed", \ - __FILE__, \ - __LINE__, \ - # expr ); \ - return ( val ); \ - }; } G_STMT_END - -#define g_return_if_reached() G_STMT_START { \ - g_log( G_LOG_DOMAIN, \ - G_LOG_LEVEL_CRITICAL, \ - "file %s: line %d: should not be reached", \ - __FILE__, \ - __LINE__ ); \ - return; } G_STMT_END - -#define g_return_val_if_reached( val ) G_STMT_START { \ - g_log( G_LOG_DOMAIN, \ - G_LOG_LEVEL_CRITICAL, \ - "file %s: line %d: should not be reached", \ - __FILE__, \ - __LINE__ ); \ - return ( val ); } G_STMT_END - -#endif /* !__GNUC__ */ - -#endif /* !G_DISABLE_CHECKS */ - -G_END_DECLS - -#endif /* __G_MESSAGES_H__ */ diff --git a/tools/urt/tools/quake3/common/glib/gnode.h b/tools/urt/tools/quake3/common/glib/gnode.h deleted file mode 100644 index 0a3c57c..0000000 --- a/tools/urt/tools/quake3/common/glib/gnode.h +++ /dev/null @@ -1,168 +0,0 @@ -/* GLIB - Library of useful routines for C programming - * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the - * Free Software Foundation, Inc., 59 Temple Place - Suite 330, - * Boston, MA 02111-1307, USA. - */ - -/* - * Modified by the GLib Team and others 1997-2000. See the AUTHORS - * file for a list of people on the GLib Team. See the ChangeLog - * files for a list of changes. These files are distributed with - * GLib at ftp://ftp.gtk.org/pub/gtk/. - */ - -#ifndef __G_NODE_H__ -#define __G_NODE_H__ - -#include - -G_BEGIN_DECLS - -typedef struct _GNode GNode; - -/* Tree traverse flags */ -typedef enum -{ - G_TRAVERSE_LEAFS = 1 << 0, - G_TRAVERSE_NON_LEAFS = 1 << 1, - G_TRAVERSE_ALL = G_TRAVERSE_LEAFS | G_TRAVERSE_NON_LEAFS, - G_TRAVERSE_MASK = 0x03 -} GTraverseFlags; - -/* Tree traverse orders */ -typedef enum -{ - G_IN_ORDER, - G_PRE_ORDER, - G_POST_ORDER, - G_LEVEL_ORDER -} GTraverseType; - -typedef gboolean ( *GNodeTraverseFunc )( GNode *node, - gpointer data ); -typedef void ( *GNodeForeachFunc )( GNode *node, - gpointer data ); -typedef gpointer ( *GCopyFunc )( gconstpointer src, - gpointer data ); - -/* N-way tree implementation - */ -struct _GNode -{ - gpointer data; - GNode *next; - GNode *prev; - GNode *parent; - GNode *children; -}; - -#define G_NODE_IS_ROOT( node ) ( ( (GNode*) ( node ) )->parent == NULL && \ - ( (GNode*) ( node ) )->prev == NULL && \ - ( (GNode*) ( node ) )->next == NULL ) -#define G_NODE_IS_LEAF( node ) ( ( (GNode*) ( node ) )->children == NULL ) - -void g_node_push_allocator( GAllocator *allocator ); -void g_node_pop_allocator( void ); -GNode* g_node_new( gpointer data ); -void g_node_destroy( GNode *root ); -void g_node_unlink( GNode *node ); -GNode* g_node_copy_deep( GNode *node, - GCopyFunc copy_func, - gpointer data ); -GNode* g_node_copy( GNode *node ); -GNode* g_node_insert( GNode *parent, - gint position, - GNode *node ); -GNode* g_node_insert_before( GNode *parent, - GNode *sibling, - GNode *node ); -GNode* g_node_insert_after( GNode *parent, - GNode *sibling, - GNode *node ); -GNode* g_node_prepend( GNode *parent, - GNode *node ); -guint g_node_n_nodes( GNode *root, - GTraverseFlags flags ); -GNode* g_node_get_root( GNode *node ); -gboolean g_node_is_ancestor( GNode *node, - GNode *descendant ); -guint g_node_depth( GNode *node ); -GNode* g_node_find( GNode *root, - GTraverseType order, - GTraverseFlags flags, - gpointer data ); - -/* convenience macros */ -#define g_node_append( parent, node ) \ - g_node_insert_before( ( parent ), NULL, ( node ) ) -#define g_node_insert_data( parent, position, data ) \ - g_node_insert( ( parent ), ( position ), g_node_new( data ) ) -#define g_node_insert_data_before( parent, sibling, data ) \ - g_node_insert_before( ( parent ), ( sibling ), g_node_new( data ) ) -#define g_node_prepend_data( parent, data ) \ - g_node_prepend( ( parent ), g_node_new( data ) ) -#define g_node_append_data( parent, data ) \ - g_node_insert_before( ( parent ), NULL, g_node_new( data ) ) - -/* traversal function, assumes that `node' is root - * (only traverses `node' and its subtree). - * this function is just a high level interface to - * low level traversal functions, optimized for speed. - */ -void g_node_traverse( GNode *root, - GTraverseType order, - GTraverseFlags flags, - gint max_depth, - GNodeTraverseFunc func, - gpointer data ); - -/* return the maximum tree height starting with `node', this is an expensive - * operation, since we need to visit all nodes. this could be shortened by - * adding `guint height' to struct _GNode, but then again, this is not very - * often needed, and would make g_node_insert() more time consuming. - */ -guint g_node_max_height( GNode *root ); - -void g_node_children_foreach( GNode *node, - GTraverseFlags flags, - GNodeForeachFunc func, - gpointer data ); -void g_node_reverse_children( GNode *node ); -guint g_node_n_children( GNode *node ); -GNode* g_node_nth_child( GNode *node, - guint n ); -GNode* g_node_last_child( GNode *node ); -GNode* g_node_find_child( GNode *node, - GTraverseFlags flags, - gpointer data ); -gint g_node_child_position( GNode *node, - GNode *child ); -gint g_node_child_index( GNode *node, - gpointer data ); - -GNode* g_node_first_sibling( GNode *node ); -GNode* g_node_last_sibling( GNode *node ); - -#define g_node_prev_sibling( node ) ( ( node ) ? \ - ( (GNode*) ( node ) )->prev : NULL ) -#define g_node_next_sibling( node ) ( ( node ) ? \ - ( (GNode*) ( node ) )->next : NULL ) -#define g_node_first_child( node ) ( ( node ) ? \ - ( (GNode*) ( node ) )->children : NULL ) - -G_END_DECLS - -#endif /* __G_NODE_H__ */ diff --git a/tools/urt/tools/quake3/common/glib/gpattern.h b/tools/urt/tools/quake3/common/glib/gpattern.h deleted file mode 100644 index 2873f69..0000000 --- a/tools/urt/tools/quake3/common/glib/gpattern.h +++ /dev/null @@ -1,44 +0,0 @@ -/* GLIB - Library of useful routines for C programming - * Copyright (C) 1995-1997, 1999 Peter Mattis, Red Hat, Inc. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the - * Free Software Foundation, Inc., 59 Temple Place - Suite 330, - * Boston, MA 02111-1307, USA. - */ -#ifndef __G_PATTERN_H__ -#define __G_PATTERN_H__ - -#include - -G_BEGIN_DECLS - - -typedef struct _GPatternSpec GPatternSpec; - -GPatternSpec* g_pattern_spec_new( const gchar *pattern ); -void g_pattern_spec_free( GPatternSpec *pspec ); -gboolean g_pattern_spec_equal( GPatternSpec *pspec1, - GPatternSpec *pspec2 ); -gboolean g_pattern_match( GPatternSpec *pspec, - guint string_length, - const gchar *string, - const gchar *string_reversed ); -gboolean g_pattern_match_string( GPatternSpec *pspec, - const gchar *string ); -gboolean g_pattern_match_simple( const gchar *pattern, - const gchar *string ); - -G_END_DECLS - -#endif /* __G_PATTERN_H__ */ diff --git a/tools/urt/tools/quake3/common/glib/gprimes.h b/tools/urt/tools/quake3/common/glib/gprimes.h deleted file mode 100644 index 055f023..0000000 --- a/tools/urt/tools/quake3/common/glib/gprimes.h +++ /dev/null @@ -1,47 +0,0 @@ -/* GLIB - Library of useful routines for C programming - * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the - * Free Software Foundation, Inc., 59 Temple Place - Suite 330, - * Boston, MA 02111-1307, USA. - */ - -/* - * Modified by the GLib Team and others 1997-2000. See the AUTHORS - * file for a list of people on the GLib Team. See the ChangeLog - * files for a list of changes. These files are distributed with - * GLib at ftp://ftp.gtk.org/pub/gtk/. - */ - -#ifndef __G_PRIMES_H__ -#define __G_PRIMES_H__ - -#include - -G_BEGIN_DECLS - -/* Prime numbers. - */ - -/* This function returns prime numbers spaced by approximately 1.5-2.0 - * and is for use in resizing data structures which prefer - * prime-valued sizes. The closest spaced prime function returns the - * next largest prime, or the highest it knows about which is about - * MAXINT/4. - */ -guint g_spaced_primes_closest( guint num ) G_GNUC_CONST; - -G_END_DECLS - -#endif /* __G_PRIMES_H__ */ diff --git a/tools/urt/tools/quake3/common/glib/gprintf.h b/tools/urt/tools/quake3/common/glib/gprintf.h deleted file mode 100644 index 97b0fc0..0000000 --- a/tools/urt/tools/quake3/common/glib/gprintf.h +++ /dev/null @@ -1,59 +0,0 @@ -/* GLIB - Library of useful routines for C programming - * Copyright (C) 1995-1997, 2002 Peter Mattis, Red Hat, Inc. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the - * Free Software Foundation, Inc., 59 Temple Place - Suite 330, - * Boston, MA 02111-1307, USA. - */ -#ifndef __G_PRINTF_H__ -#define __G_PRINTF_H__ - -#include -#include -#include - -G_BEGIN_DECLS - -gint g_printf( gchar const *format, - ... ) G_GNUC_PRINTF( 1, 2 ); -gint g_fprintf( FILE *file, - gchar const *format, - ... ) G_GNUC_PRINTF( 2, 3 ); -gint g_sprintf( gchar *string, - gchar const *format, - ... ) G_GNUC_PRINTF( 2, 3 ); -gint g_snprintf( gchar *string, - gulong n, - gchar const *format, - ... ) G_GNUC_PRINTF( 3, 4 ); - -gint g_vprintf( gchar const *format, - va_list args ); -gint g_vfprintf( FILE *file, - gchar const *format, - va_list args ); -gint g_vsprintf( gchar *string, - gchar const *format, - va_list args ); -gint g_vsnprintf( gchar *string, - gulong n, - gchar const *format, - va_list args ); -gint g_vasprintf( gchar **string, - gchar const *format, - va_list args ); - -G_END_DECLS - -#endif /* __G_PRINTF_H__ */ diff --git a/tools/urt/tools/quake3/common/glib/gqsort.h b/tools/urt/tools/quake3/common/glib/gqsort.h deleted file mode 100644 index 7e88ad8..0000000 --- a/tools/urt/tools/quake3/common/glib/gqsort.h +++ /dev/null @@ -1,43 +0,0 @@ -/* GLIB - Library of useful routines for C programming - * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the - * Free Software Foundation, Inc., 59 Temple Place - Suite 330, - * Boston, MA 02111-1307, USA. - */ - -/* - * Modified by the GLib Team and others 1997-2000. See the AUTHORS - * file for a list of people on the GLib Team. See the ChangeLog - * files for a list of changes. These files are distributed with - * GLib at ftp://ftp.gtk.org/pub/gtk/. - */ - - -#ifndef __G_QSORT_H__ -#define __G_QSORT_H__ - -#include - -G_BEGIN_DECLS - -void g_qsort_with_data( gconstpointer pbase, - gint total_elems, - gsize size, - GCompareDataFunc compare_func, - gpointer user_data ); - -G_END_DECLS - -#endif /* __G_QSORT_H__ */ diff --git a/tools/urt/tools/quake3/common/glib/gquark.h b/tools/urt/tools/quake3/common/glib/gquark.h deleted file mode 100644 index ef5084b..0000000 --- a/tools/urt/tools/quake3/common/glib/gquark.h +++ /dev/null @@ -1,45 +0,0 @@ -/* GLIB - Library of useful routines for C programming - * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the - * Free Software Foundation, Inc., 59 Temple Place - Suite 330, - * Boston, MA 02111-1307, USA. - */ - -/* - * Modified by the GLib Team and others 1997-2000. See the AUTHORS - * file for a list of people on the GLib Team. See the ChangeLog - * files for a list of changes. These files are distributed with - * GLib at ftp://ftp.gtk.org/pub/gtk/. - */ - -#ifndef __G_QUARK_H__ -#define __G_QUARK_H__ - -#include - -G_BEGIN_DECLS - -typedef guint32 GQuark; - -/* Quarks (string<->id association) - */ -GQuark g_quark_try_string( const gchar *string ); -GQuark g_quark_from_static_string( const gchar *string ); -GQuark g_quark_from_string( const gchar *string ); -G_CONST_RETURN gchar* g_quark_to_string( GQuark quark ) G_GNUC_CONST; - -G_END_DECLS - -#endif /* __G_QUARK_H__ */ diff --git a/tools/urt/tools/quake3/common/glib/gqueue.h b/tools/urt/tools/quake3/common/glib/gqueue.h deleted file mode 100644 index 48e96ed..0000000 --- a/tools/urt/tools/quake3/common/glib/gqueue.h +++ /dev/null @@ -1,119 +0,0 @@ -/* GLIB - Library of useful routines for C programming - * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the - * Free Software Foundation, Inc., 59 Temple Place - Suite 330, - * Boston, MA 02111-1307, USA. - */ - -/* - * Modified by the GLib Team and others 1997-2000. See the AUTHORS - * file for a list of people on the GLib Team. See the ChangeLog - * files for a list of changes. These files are distributed with - * GLib at ftp://ftp.gtk.org/pub/gtk/. - */ - -#ifndef __G_QUEUE_H__ -#define __G_QUEUE_H__ - -#include - -G_BEGIN_DECLS - -typedef struct _GQueue GQueue; - -struct _GQueue -{ - GList *head; - GList *tail; - guint length; -}; - -/* Queues - */ -GQueue* g_queue_new( void ); -void g_queue_free( GQueue *queue ); -gboolean g_queue_is_empty( GQueue *queue ); -guint g_queue_get_length( GQueue *queue ); -void g_queue_reverse( GQueue *queue ); -GQueue * g_queue_copy( GQueue *queue ); -void g_queue_foreach( GQueue *queue, - GFunc func, - gpointer user_data ); -GList * g_queue_find( GQueue *queue, - gconstpointer data ); -GList * g_queue_find_custom( GQueue *queue, - gconstpointer data, - GCompareFunc func ); -void g_queue_sort( GQueue *queue, - GCompareDataFunc compare_func, - gpointer user_data ); - -void g_queue_push_head( GQueue *queue, - gpointer data ); -void g_queue_push_tail( GQueue *queue, - gpointer data ); -void g_queue_push_nth( GQueue *queue, - gpointer data, - gint n ); -gpointer g_queue_pop_head( GQueue *queue ); -gpointer g_queue_pop_tail( GQueue *queue ); -gpointer g_queue_pop_nth( GQueue *queue, - guint n ); -gpointer g_queue_peek_head( GQueue *queue ); -gpointer g_queue_peek_tail( GQueue *queue ); -gpointer g_queue_peek_nth( GQueue *queue, - guint n ); -gint g_queue_index( GQueue *queue, - gconstpointer data ); -void g_queue_remove( GQueue *queue, - gconstpointer data ); -void g_queue_remove_all( GQueue *queue, - gconstpointer data ); -void g_queue_insert_before( GQueue *queue, - GList *sibling, - gpointer data ); -void g_queue_insert_after( GQueue *queue, - GList *sibling, - gpointer data ); -void g_queue_insert_sorted( GQueue *queue, - gpointer data, - GCompareDataFunc func, - gpointer user_data ); - -void g_queue_push_head_link( GQueue *queue, - GList *link_ ); -void g_queue_push_tail_link( GQueue *queue, - GList *link_ ); -void g_queue_push_nth_link( GQueue *queue, - gint n, - GList *link_ ); -GList* g_queue_pop_head_link( GQueue *queue ); -GList* g_queue_pop_tail_link( GQueue *queue ); -GList* g_queue_pop_nth_link( GQueue *queue, - guint n ); -GList* g_queue_peek_head_link( GQueue *queue ); -GList* g_queue_peek_tail_link( GQueue *queue ); -GList* g_queue_peek_nth_link( GQueue *queue, - guint n ); -gint g_queue_link_index( GQueue *queue, - GList *link_ ); -void g_queue_unlink( GQueue *queue, - GList *link_ ); -void g_queue_delete_link( GQueue *queue, - GList *link_ ); - -G_END_DECLS - -#endif /* __G_QUEUE_H__ */ diff --git a/tools/urt/tools/quake3/common/glib/grand.h b/tools/urt/tools/quake3/common/glib/grand.h deleted file mode 100644 index 717b532..0000000 --- a/tools/urt/tools/quake3/common/glib/grand.h +++ /dev/null @@ -1,81 +0,0 @@ -/* GLIB - Library of useful routines for C programming - * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the - * Free Software Foundation, Inc., 59 Temple Place - Suite 330, - * Boston, MA 02111-1307, USA. - */ - -/* - * Modified by the GLib Team and others 1997-2000. See the AUTHORS - * file for a list of people on the GLib Team. See the ChangeLog - * files for a list of changes. These files are distributed with - * GLib at ftp://ftp.gtk.org/pub/gtk/. - */ - -#ifndef __G_RAND_H__ -#define __G_RAND_H__ - -#include - -G_BEGIN_DECLS - -typedef struct _GRand GRand; - -/* GRand - a good and fast random number generator: Mersenne Twister - * see http://www.math.keio.ac.jp/~matumoto/emt.html for more info. - * The range functions return a value in the intervall [begin, end). - * int -> [0..2^32-1] - * int_range -> [begin..end-1] - * double -> [0..1) - * double_range -> [begin..end) - */ - -GRand* g_rand_new_with_seed( guint32 seed ); -GRand* g_rand_new_with_seed_array( const guint32 *seed, - guint seed_length ); -GRand* g_rand_new( void ); -void g_rand_free( GRand *rand_ ); -GRand* g_rand_copy( GRand *rand_ ); -void g_rand_set_seed( GRand *rand_, - guint32 seed ); -void g_rand_set_seed_array( GRand *rand_, - const guint32 *seed, - guint seed_length ); - -#define g_rand_boolean( rand_ ) ( ( g_rand_int( rand_ ) & ( 1 << 15 ) ) != 0 ) - -guint32 g_rand_int( GRand *rand_ ); -gint32 g_rand_int_range( GRand *rand_, - gint32 begin, - gint32 end ); -gdouble g_rand_double( GRand *rand_ ); -gdouble g_rand_double_range( GRand *rand_, - gdouble begin, - gdouble end ); -void g_random_set_seed( guint32 seed ); - -#define g_random_boolean() ( ( g_random_int() & ( 1 << 15 ) ) != 0 ) - -guint32 g_random_int( void ); -gint32 g_random_int_range( gint32 begin, - gint32 end ); -gdouble g_random_double( void ); -gdouble g_random_double_range( gdouble begin, - gdouble end ); - - -G_END_DECLS - -#endif /* __G_RAND_H__ */ diff --git a/tools/urt/tools/quake3/common/glib/grel.h b/tools/urt/tools/quake3/common/glib/grel.h deleted file mode 100644 index 1db7cf1..0000000 --- a/tools/urt/tools/quake3/common/glib/grel.h +++ /dev/null @@ -1,93 +0,0 @@ -/* GLIB - Library of useful routines for C programming - * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the - * Free Software Foundation, Inc., 59 Temple Place - Suite 330, - * Boston, MA 02111-1307, USA. - */ - -/* - * Modified by the GLib Team and others 1997-2000. See the AUTHORS - * file for a list of people on the GLib Team. See the ChangeLog - * files for a list of changes. These files are distributed with - * GLib at ftp://ftp.gtk.org/pub/gtk/. - */ - -#ifndef __G_REL_H__ -#define __G_REL_H__ - -#include - -G_BEGIN_DECLS - -typedef struct _GRelation GRelation; -typedef struct _GTuples GTuples; - -struct _GTuples -{ - guint len; -}; - -/* GRelation - * - * Indexed Relations. Imagine a really simple table in a - * database. Relations are not ordered. This data type is meant for - * maintaining a N-way mapping. - * - * g_relation_new() creates a relation with FIELDS fields - * - * g_relation_destroy() frees all resources - * g_tuples_destroy() frees the result of g_relation_select() - * - * g_relation_index() indexes relation FIELD with the provided - * equality and hash functions. this must be done before any - * calls to insert are made. - * - * g_relation_insert() inserts a new tuple. you are expected to - * provide the right number of fields. - * - * g_relation_delete() deletes all relations with KEY in FIELD - * g_relation_select() returns ... - * g_relation_count() counts ... - */ - -GRelation* g_relation_new( gint fields ); -void g_relation_destroy( GRelation *relation ); -void g_relation_index( GRelation *relation, - gint field, - GHashFunc hash_func, - GEqualFunc key_equal_func ); -void g_relation_insert( GRelation *relation, - ... ); -gint g_relation_delete( GRelation *relation, - gconstpointer key, - gint field ); -GTuples* g_relation_select( GRelation *relation, - gconstpointer key, - gint field ); -gint g_relation_count( GRelation *relation, - gconstpointer key, - gint field ); -gboolean g_relation_exists( GRelation *relation, - ... ); -void g_relation_print( GRelation *relation ); - -void g_tuples_destroy( GTuples *tuples ); -gpointer g_tuples_index( GTuples *tuples, - gint index_, - gint field ); - -G_END_DECLS - -#endif /* __G_REL_H__ */ diff --git a/tools/urt/tools/quake3/common/glib/gscanner.h b/tools/urt/tools/quake3/common/glib/gscanner.h deleted file mode 100644 index f89fc47..0000000 --- a/tools/urt/tools/quake3/common/glib/gscanner.h +++ /dev/null @@ -1,273 +0,0 @@ -/* GLIB - Library of useful routines for C programming - * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the - * Free Software Foundation, Inc., 59 Temple Place - Suite 330, - * Boston, MA 02111-1307, USA. - */ - -/* - * Modified by the GLib Team and others 1997-2000. See the AUTHORS - * file for a list of people on the GLib Team. See the ChangeLog - * files for a list of changes. These files are distributed with - * GLib at ftp://ftp.gtk.org/pub/gtk/. - */ - -#ifndef __G_SCANNER_H__ -#define __G_SCANNER_H__ - -#include - -G_BEGIN_DECLS - -typedef struct _GScanner GScanner; -typedef struct _GScannerConfig GScannerConfig; -typedef union _GTokenValue GTokenValue; - -typedef void ( *GScannerMsgFunc )( GScanner *scanner, - gchar *message, - gboolean error ); - -/* GScanner: Flexible lexical scanner for general purpose. - */ - -/* Character sets */ -#define G_CSET_A_2_Z "ABCDEFGHIJKLMNOPQRSTUVWXYZ" -#define G_CSET_a_2_z "abcdefghijklmnopqrstuvwxyz" -#define G_CSET_DIGITS "0123456789" -#define G_CSET_LATINC "\300\301\302\303\304\305\306" \ - "\307\310\311\312\313\314\315\316\317\320" \ - "\321\322\323\324\325\326" \ - "\330\331\332\333\334\335\336" -#define G_CSET_LATINS "\337\340\341\342\343\344\345\346" \ - "\347\350\351\352\353\354\355\356\357\360" \ - "\361\362\363\364\365\366" \ - "\370\371\372\373\374\375\376\377" - -/* Error types */ -typedef enum -{ - G_ERR_UNKNOWN, - G_ERR_UNEXP_EOF, - G_ERR_UNEXP_EOF_IN_STRING, - G_ERR_UNEXP_EOF_IN_COMMENT, - G_ERR_NON_DIGIT_IN_CONST, - G_ERR_DIGIT_RADIX, - G_ERR_FLOAT_RADIX, - G_ERR_FLOAT_MALFORMED -} GErrorType; - -/* Token types */ -typedef enum -{ - G_TOKEN_EOF = 0, - - G_TOKEN_LEFT_PAREN = '(', - G_TOKEN_RIGHT_PAREN = ')', - G_TOKEN_LEFT_CURLY = '{', - G_TOKEN_RIGHT_CURLY = '}', - G_TOKEN_LEFT_BRACE = '[', - G_TOKEN_RIGHT_BRACE = ']', - G_TOKEN_EQUAL_SIGN = '=', - G_TOKEN_COMMA = ',', - - G_TOKEN_NONE = 256, - - G_TOKEN_ERROR, - - G_TOKEN_CHAR, - G_TOKEN_BINARY, - G_TOKEN_OCTAL, - G_TOKEN_INT, - G_TOKEN_HEX, - G_TOKEN_FLOAT, - G_TOKEN_STRING, - - G_TOKEN_SYMBOL, - G_TOKEN_IDENTIFIER, - G_TOKEN_IDENTIFIER_NULL, - - G_TOKEN_COMMENT_SINGLE, - G_TOKEN_COMMENT_MULTI, - G_TOKEN_LAST -} GTokenType; - -union _GTokenValue -{ - gpointer v_symbol; - gchar *v_identifier; - gulong v_binary; - gulong v_octal; - gulong v_int; - guint64 v_int64; - gdouble v_float; - gulong v_hex; - gchar *v_string; - gchar *v_comment; - guchar v_char; - guint v_error; -}; - -struct _GScannerConfig -{ - /* Character sets - */ - gchar *cset_skip_characters; /* default: " \t\n" */ - gchar *cset_identifier_first; - gchar *cset_identifier_nth; - gchar *cpair_comment_single; /* default: "#\n" */ - - /* Should symbol lookup work case sensitive? - */ - guint case_sensitive : 1; - - /* Boolean values to be adjusted "on the fly" - * to configure scanning behaviour. - */ - guint skip_comment_multi : 1; /* C like comment */ - guint skip_comment_single : 1; /* single line comment */ - guint scan_comment_multi : 1; /* scan multi line comments? */ - guint scan_identifier : 1; - guint scan_identifier_1char : 1; - guint scan_identifier_NULL : 1; - guint scan_symbols : 1; - guint scan_binary : 1; - guint scan_octal : 1; - guint scan_float : 1; - guint scan_hex : 1; /* `0x0ff0' */ - guint scan_hex_dollar : 1; /* `$0ff0' */ - guint scan_string_sq : 1; /* string: 'anything' */ - guint scan_string_dq : 1; /* string: "\\-escapes!\n" */ - guint numbers_2_int : 1; /* bin, octal, hex => int */ - guint int_2_float : 1; /* int => G_TOKEN_FLOAT? */ - guint identifier_2_string : 1; - guint char_2_token : 1; /* return G_TOKEN_CHAR? */ - guint symbol_2_token : 1; - guint scope_0_fallback : 1; /* try scope 0 on lookups? */ - guint store_int64 : 1; /* use value.v_int64 rather than v_int */ - guint padding_dummy; -}; - -struct _GScanner -{ - /* unused fields */ - gpointer user_data; - guint max_parse_errors; - - /* g_scanner_error() increments this field */ - guint parse_errors; - - /* name of input stream, featured by the default message handler */ - const gchar *input_name; - - /* quarked data */ - GData *qdata; - - /* link into the scanner configuration */ - GScannerConfig *config; - - /* fields filled in after g_scanner_get_next_token() */ - GTokenType token; - GTokenValue value; - guint line; - guint position; - - /* fields filled in after g_scanner_peek_next_token() */ - GTokenType next_token; - GTokenValue next_value; - guint next_line; - guint next_position; - - /* to be considered private */ - GHashTable *symbol_table; - gint input_fd; - const gchar *text; - const gchar *text_end; - gchar *buffer; - guint scope_id; - - /* handler function for _warn and _error */ - GScannerMsgFunc msg_handler; -}; - -GScanner* g_scanner_new( const GScannerConfig *config_templ ); -void g_scanner_destroy( GScanner *scanner ); -void g_scanner_input_file( GScanner *scanner, - gint input_fd ); -void g_scanner_sync_file_offset( GScanner *scanner ); -void g_scanner_input_text( GScanner *scanner, - const gchar *text, - guint text_len ); -GTokenType g_scanner_get_next_token( GScanner *scanner ); -GTokenType g_scanner_peek_next_token( GScanner *scanner ); -GTokenType g_scanner_cur_token( GScanner *scanner ); -GTokenValue g_scanner_cur_value( GScanner *scanner ); -guint g_scanner_cur_line( GScanner *scanner ); -guint g_scanner_cur_position( GScanner *scanner ); -gboolean g_scanner_eof( GScanner *scanner ); -guint g_scanner_set_scope( GScanner *scanner, - guint scope_id ); -void g_scanner_scope_add_symbol( GScanner *scanner, - guint scope_id, - const gchar *symbol, - gpointer value ); -void g_scanner_scope_remove_symbol( GScanner *scanner, - guint scope_id, - const gchar *symbol ); -gpointer g_scanner_scope_lookup_symbol( GScanner *scanner, - guint scope_id, - const gchar *symbol ); -void g_scanner_scope_foreach_symbol( GScanner *scanner, - guint scope_id, - GHFunc func, - gpointer user_data ); -gpointer g_scanner_lookup_symbol( GScanner *scanner, - const gchar *symbol ); -void g_scanner_unexp_token( GScanner *scanner, - GTokenType expected_token, - const gchar *identifier_spec, - const gchar *symbol_spec, - const gchar *symbol_name, - const gchar *message, - gint is_error ); -void g_scanner_error( GScanner *scanner, - const gchar *format, - ... ) G_GNUC_PRINTF( 2,3 ); -void g_scanner_warn( GScanner *scanner, - const gchar *format, - ... ) G_GNUC_PRINTF( 2,3 ); - -#ifndef G_DISABLE_DEPRECATED - -/* keep downward source compatibility */ -#define g_scanner_add_symbol( scanner, symbol, value ) G_STMT_START { \ - g_scanner_scope_add_symbol( ( scanner ), 0, ( symbol ), ( value ) ); \ -} G_STMT_END -#define g_scanner_remove_symbol( scanner, symbol ) G_STMT_START { \ - g_scanner_scope_remove_symbol( ( scanner ), 0, ( symbol ) ); \ -} G_STMT_END -#define g_scanner_foreach_symbol( scanner, func, data ) G_STMT_START { \ - g_scanner_scope_foreach_symbol( ( scanner ), 0, ( func ), ( data ) ); \ -} G_STMT_END - -/* The following two functions are deprecated and will be removed in - * the next major release. They do no good. */ -#define g_scanner_freeze_symbol_table( scanner ) ( (void)0 ) -#define g_scanner_thaw_symbol_table( scanner ) ( (void)0 ) - -#endif /* G_DISABLE_DEPRECATED */ - -G_END_DECLS - -#endif /* __G_SCANNER_H__ */ diff --git a/tools/urt/tools/quake3/common/glib/gshell.h b/tools/urt/tools/quake3/common/glib/gshell.h deleted file mode 100644 index f813d9d..0000000 --- a/tools/urt/tools/quake3/common/glib/gshell.h +++ /dev/null @@ -1,51 +0,0 @@ -/* gshell.h - Shell-related utilities - * - * Copyright 2000 Red Hat, Inc. - * - * GLib is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 of the - * License, or (at your option) any later version. - * - * GLib is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with GLib; see the file COPYING.LIB. If not, write - * to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, - * Boston, MA 02111-1307, USA. - */ - -#ifndef __G_SHELL_H__ -#define __G_SHELL_H__ - -#include - -G_BEGIN_DECLS - -#define G_SHELL_ERROR g_shell_error_quark() - -typedef enum -{ - /* mismatched or otherwise mangled quoting */ - G_SHELL_ERROR_BAD_QUOTING, - /* string to be parsed was empty */ - G_SHELL_ERROR_EMPTY_STRING, - G_SHELL_ERROR_FAILED -} GShellError; - -GQuark g_shell_error_quark( void ); - -gchar* g_shell_quote( const gchar *unquoted_string ); -gchar* g_shell_unquote( const gchar *quoted_string, - GError **error ); -gboolean g_shell_parse_argv( const gchar *command_line, - gint *argcp, - gchar ***argvp, - GError **error ); - -G_END_DECLS - -#endif /* __G_SHELL_H__ */ diff --git a/tools/urt/tools/quake3/common/glib/gslist.h b/tools/urt/tools/quake3/common/glib/gslist.h deleted file mode 100644 index 3b439e8..0000000 --- a/tools/urt/tools/quake3/common/glib/gslist.h +++ /dev/null @@ -1,101 +0,0 @@ -/* GLIB - Library of useful routines for C programming - * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the - * Free Software Foundation, Inc., 59 Temple Place - Suite 330, - * Boston, MA 02111-1307, USA. - */ - -/* - * Modified by the GLib Team and others 1997-2000. See the AUTHORS - * file for a list of people on the GLib Team. See the ChangeLog - * files for a list of changes. These files are distributed with - * GLib at ftp://ftp.gtk.org/pub/gtk/. - */ - -#ifndef __G_SLIST_H__ -#define __G_SLIST_H__ - -#include - -G_BEGIN_DECLS - -typedef struct _GSList GSList; - -struct _GSList -{ - gpointer data; - GSList *next; -}; - -/* Singly linked lists - */ -void g_slist_push_allocator( GAllocator *allocator ); -void g_slist_pop_allocator( void ); -GSList* g_slist_alloc( void ); -void g_slist_free( GSList *list ); -void g_slist_free_1( GSList *list ); -GSList* g_slist_append( GSList *list, - gpointer data ); -GSList* g_slist_prepend( GSList *list, - gpointer data ); -GSList* g_slist_insert( GSList *list, - gpointer data, - gint position ); -GSList* g_slist_insert_sorted( GSList *list, - gpointer data, - GCompareFunc func ); -GSList* g_slist_insert_before( GSList *slist, - GSList *sibling, - gpointer data ); -GSList* g_slist_concat( GSList *list1, - GSList *list2 ); -GSList* g_slist_remove( GSList *list, - gconstpointer data ); -GSList* g_slist_remove_all( GSList *list, - gconstpointer data ); -GSList* g_slist_remove_link( GSList *list, - GSList *link_ ); -GSList* g_slist_delete_link( GSList *list, - GSList *link_ ); -GSList* g_slist_reverse( GSList *list ); -GSList* g_slist_copy( GSList *list ); -GSList* g_slist_nth( GSList *list, - guint n ); -GSList* g_slist_find( GSList *list, - gconstpointer data ); -GSList* g_slist_find_custom( GSList *list, - gconstpointer data, - GCompareFunc func ); -gint g_slist_position( GSList *list, - GSList *llink ); -gint g_slist_index( GSList *list, - gconstpointer data ); -GSList* g_slist_last( GSList *list ); -guint g_slist_length( GSList *list ); -void g_slist_foreach( GSList *list, - GFunc func, - gpointer user_data ); -GSList* g_slist_sort( GSList *list, - GCompareFunc compare_func ); -GSList* g_slist_sort_with_data( GSList *list, - GCompareDataFunc compare_func, - gpointer user_data ); -gpointer g_slist_nth_data( GSList *list, - guint n ); -#define g_slist_next( slist ) ( ( slist ) ? ( ( (GSList *)( slist ) )->next ) : NULL ) - -G_END_DECLS - -#endif /* __G_SLIST_H__ */ diff --git a/tools/urt/tools/quake3/common/glib/gspawn.h b/tools/urt/tools/quake3/common/glib/gspawn.h deleted file mode 100644 index bdc922f..0000000 --- a/tools/urt/tools/quake3/common/glib/gspawn.h +++ /dev/null @@ -1,128 +0,0 @@ -/* gspawn.h - Process launching - * - * Copyright 2000 Red Hat, Inc. - * - * GLib is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 of the - * License, or (at your option) any later version. - * - * GLib is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with GLib; see the file COPYING.LIB. If not, write - * to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, - * Boston, MA 02111-1307, USA. - */ - -#ifndef __G_SPAWN_H__ -#define __G_SPAWN_H__ - -#include - -G_BEGIN_DECLS - -/* I'm not sure I remember our proposed naming convention here. */ -#define G_SPAWN_ERROR g_spawn_error_quark() - -typedef enum -{ - G_SPAWN_ERROR_FORK, /* fork failed due to lack of memory */ - G_SPAWN_ERROR_READ, /* read or select on pipes failed */ - G_SPAWN_ERROR_CHDIR, /* changing to working dir failed */ - G_SPAWN_ERROR_ACCES, /* execv() returned EACCES */ - G_SPAWN_ERROR_PERM, /* execv() returned EPERM */ - G_SPAWN_ERROR_2BIG, /* execv() returned E2BIG */ - G_SPAWN_ERROR_NOEXEC, /* execv() returned ENOEXEC */ - G_SPAWN_ERROR_NAMETOOLONG, /* "" "" ENAMETOOLONG */ - G_SPAWN_ERROR_NOENT, /* "" "" ENOENT */ - G_SPAWN_ERROR_NOMEM, /* "" "" ENOMEM */ - G_SPAWN_ERROR_NOTDIR, /* "" "" ENOTDIR */ - G_SPAWN_ERROR_LOOP, /* "" "" ELOOP */ - G_SPAWN_ERROR_TXTBUSY, /* "" "" ETXTBUSY */ - G_SPAWN_ERROR_IO, /* "" "" EIO */ - G_SPAWN_ERROR_NFILE, /* "" "" ENFILE */ - G_SPAWN_ERROR_MFILE, /* "" "" EMFLE */ - G_SPAWN_ERROR_INVAL, /* "" "" EINVAL */ - G_SPAWN_ERROR_ISDIR, /* "" "" EISDIR */ - G_SPAWN_ERROR_LIBBAD, /* "" "" ELIBBAD */ - G_SPAWN_ERROR_FAILED /* other fatal failure, error->message - * should explain - */ -} GSpawnError; - -typedef void ( *GSpawnChildSetupFunc )( gpointer user_data ); - -typedef enum -{ - G_SPAWN_LEAVE_DESCRIPTORS_OPEN = 1 << 0, - G_SPAWN_DO_NOT_REAP_CHILD = 1 << 1, - /* look for argv[0] in the path i.e. use execvp() */ - G_SPAWN_SEARCH_PATH = 1 << 2, - /* Dump output to /dev/null */ - G_SPAWN_STDOUT_TO_DEV_NULL = 1 << 3, - G_SPAWN_STDERR_TO_DEV_NULL = 1 << 4, - G_SPAWN_CHILD_INHERITS_STDIN = 1 << 5, - G_SPAWN_FILE_AND_ARGV_ZERO = 1 << 6 -} GSpawnFlags; - -GQuark g_spawn_error_quark( void ); - -gboolean g_spawn_async( const gchar *working_directory, - gchar **argv, - gchar **envp, - GSpawnFlags flags, - GSpawnChildSetupFunc child_setup, - gpointer user_data, - GPid *child_pid, - GError **error ); - - -/* Opens pipes for non-NULL standard_output, standard_input, standard_error, - * and returns the parent's end of the pipes. - */ -gboolean g_spawn_async_with_pipes( const gchar *working_directory, - gchar **argv, - gchar **envp, - GSpawnFlags flags, - GSpawnChildSetupFunc child_setup, - gpointer user_data, - GPid *child_pid, - gint *standard_input, - gint *standard_output, - gint *standard_error, - GError **error ); - - -/* If standard_output or standard_error are non-NULL, the full - * standard output or error of the command will be placed there. - */ - -gboolean g_spawn_sync( const gchar *working_directory, - gchar **argv, - gchar **envp, - GSpawnFlags flags, - GSpawnChildSetupFunc child_setup, - gpointer user_data, - gchar **standard_output, - gchar **standard_error, - gint *exit_status, - GError **error ); - -gboolean g_spawn_command_line_sync( const gchar *command_line, - gchar **standard_output, - gchar **standard_error, - gint *exit_status, - GError **error ); -gboolean g_spawn_command_line_async( const gchar *command_line, - GError **error ); - -void g_spawn_close_pid( GPid pid ); - - -G_END_DECLS - -#endif /* __G_SPAWN_H__ */ diff --git a/tools/urt/tools/quake3/common/glib/gstrfuncs.h b/tools/urt/tools/quake3/common/glib/gstrfuncs.h deleted file mode 100644 index a331dec..0000000 --- a/tools/urt/tools/quake3/common/glib/gstrfuncs.h +++ /dev/null @@ -1,242 +0,0 @@ -/* GLIB - Library of useful routines for C programming - * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the - * Free Software Foundation, Inc., 59 Temple Place - Suite 330, - * Boston, MA 02111-1307, USA. - */ - -/* - * Modified by the GLib Team and others 1997-2000. See the AUTHORS - * file for a list of people on the GLib Team. See the ChangeLog - * files for a list of changes. These files are distributed with - * GLib at ftp://ftp.gtk.org/pub/gtk/. - */ - -#ifndef __G_STRFUNCS_H__ -#define __G_STRFUNCS_H__ - -#include -#include - -G_BEGIN_DECLS - -/* Functions like the ones in that are not affected by locale. */ -typedef enum { - G_ASCII_ALNUM = 1 << 0, - G_ASCII_ALPHA = 1 << 1, - G_ASCII_CNTRL = 1 << 2, - G_ASCII_DIGIT = 1 << 3, - G_ASCII_GRAPH = 1 << 4, - G_ASCII_LOWER = 1 << 5, - G_ASCII_PRINT = 1 << 6, - G_ASCII_PUNCT = 1 << 7, - G_ASCII_SPACE = 1 << 8, - G_ASCII_UPPER = 1 << 9, - G_ASCII_XDIGIT = 1 << 10 -} GAsciiType; - -GLIB_VAR const guint16 * const g_ascii_table; - -#define g_ascii_isalnum( c ) \ - ( ( g_ascii_table[(guchar) ( c )] & G_ASCII_ALNUM ) != 0 ) - -#define g_ascii_isalpha( c ) \ - ( ( g_ascii_table[(guchar) ( c )] & G_ASCII_ALPHA ) != 0 ) - -#define g_ascii_iscntrl( c ) \ - ( ( g_ascii_table[(guchar) ( c )] & G_ASCII_CNTRL ) != 0 ) - -#define g_ascii_isdigit( c ) \ - ( ( g_ascii_table[(guchar) ( c )] & G_ASCII_DIGIT ) != 0 ) - -#define g_ascii_isgraph( c ) \ - ( ( g_ascii_table[(guchar) ( c )] & G_ASCII_GRAPH ) != 0 ) - -#define g_ascii_islower( c ) \ - ( ( g_ascii_table[(guchar) ( c )] & G_ASCII_LOWER ) != 0 ) - -#define g_ascii_isprint( c ) \ - ( ( g_ascii_table[(guchar) ( c )] & G_ASCII_PRINT ) != 0 ) - -#define g_ascii_ispunct( c ) \ - ( ( g_ascii_table[(guchar) ( c )] & G_ASCII_PUNCT ) != 0 ) - -#define g_ascii_isspace( c ) \ - ( ( g_ascii_table[(guchar) ( c )] & G_ASCII_SPACE ) != 0 ) - -#define g_ascii_isupper( c ) \ - ( ( g_ascii_table[(guchar) ( c )] & G_ASCII_UPPER ) != 0 ) - -#define g_ascii_isxdigit( c ) \ - ( ( g_ascii_table[(guchar) ( c )] & G_ASCII_XDIGIT ) != 0 ) - -gchar g_ascii_tolower( gchar c ) G_GNUC_CONST; -gchar g_ascii_toupper( gchar c ) G_GNUC_CONST; - -gint g_ascii_digit_value( gchar c ) G_GNUC_CONST; -gint g_ascii_xdigit_value( gchar c ) G_GNUC_CONST; - -/* String utility functions that modify a string argument or - * return a constant string that must not be freed. - */ -#define G_STR_DELIMITERS "_-|> <." -gchar* g_strdelimit( gchar *string, - const gchar *delimiters, - gchar new_delimiter ); -gchar* g_strcanon( gchar *string, - const gchar *valid_chars, - gchar substitutor ); -G_CONST_RETURN gchar* g_strerror( gint errnum ) G_GNUC_CONST; -G_CONST_RETURN gchar* g_strsignal( gint signum ) G_GNUC_CONST; -gchar* g_strreverse( gchar *string ); -gsize g_strlcpy( gchar *dest, - const gchar *src, - gsize dest_size ); -gsize g_strlcat( gchar *dest, - const gchar *src, - gsize dest_size ); -gchar * g_strstr_len( const gchar *haystack, - gssize haystack_len, - const gchar *needle ); -gchar * g_strrstr( const gchar *haystack, - const gchar *needle ); -gchar * g_strrstr_len( const gchar *haystack, - gssize haystack_len, - const gchar *needle ); - -gboolean g_str_has_suffix( const gchar *str, - const gchar *suffix ); -gboolean g_str_has_prefix( const gchar *str, - const gchar *prefix ); - -/* String to/from double conversion functions */ - -gdouble g_strtod( const gchar *nptr, - gchar **endptr ); -gdouble g_ascii_strtod( const gchar *nptr, - gchar **endptr ); -guint64 g_ascii_strtoull( const gchar *nptr, - gchar **endptr, - guint base ); -/* 29 bytes should enough for all possible values that - * g_ascii_dtostr can produce. - * Then add 10 for good measure */ -#define G_ASCII_DTOSTR_BUF_SIZE ( 29 + 10 ) -gchar * g_ascii_dtostr( gchar *buffer, - gint buf_len, - gdouble d ); -gchar * g_ascii_formatd( gchar *buffer, - gint buf_len, - const gchar *format, - gdouble d ); - -/* removes leading spaces */ -gchar* g_strchug( gchar *string ); -/* removes trailing spaces */ -gchar* g_strchomp( gchar *string ); -/* removes leading & trailing spaces */ -#define g_strstrip( string ) g_strchomp( g_strchug( string ) ) - -gint g_ascii_strcasecmp( const gchar *s1, - const gchar *s2 ); -gint g_ascii_strncasecmp( const gchar *s1, - const gchar *s2, - gsize n ); -gchar* g_ascii_strdown( const gchar *str, - gssize len ); -gchar* g_ascii_strup( const gchar *str, - gssize len ); - -#ifndef G_DISABLE_DEPRECATED - -/* The following four functions are deprecated and will be removed in - * the next major release. They use the locale-specific tolower and - * toupper, which is almost never the right thing. - */ - -gint g_strcasecmp( const gchar *s1, - const gchar *s2 ); -gint g_strncasecmp( const gchar *s1, - const gchar *s2, - guint n ); -gchar* g_strdown( gchar *string ); -gchar* g_strup( gchar *string ); - -#endif /* G_DISABLE_DEPRECATED */ - -/* String utility functions that return a newly allocated string which - * ought to be freed with g_free from the caller at some point. - */ -gchar* g_strdup( const gchar *str ); -gchar* g_strdup_printf( const gchar *format, - ... ) G_GNUC_PRINTF( 1, 2 ); -gchar* g_strdup_vprintf( const gchar *format, - va_list args ); -gchar* g_strndup( const gchar *str, - gsize n ); -gchar* g_strnfill( gsize length, - gchar fill_char ); -gchar* g_strconcat( const gchar *string1, - ... ); /* NULL terminated */ -gchar* g_strjoin( const gchar *separator, - ... ); /* NULL terminated */ -/* Make a copy of a string interpreting C string -style escape - * sequences. Inverse of g_strescape. The recognized sequences are \b - * \f \n \r \t \\ \" and the octal format. - */ -gchar* g_strcompress( const gchar *source ); - -/* Copy a string escaping nonprintable characters like in C strings. - * Inverse of g_strcompress. The exceptions parameter, if non-NULL, points - * to a string containing characters that are not to be escaped. - * - * Deprecated API: gchar* g_strescape (const gchar *source); - * Luckily this function wasn't used much, using NULL as second parameter - * provides mostly identical semantics. - */ -gchar* g_strescape( const gchar *source, - const gchar *exceptions ); - -gpointer g_memdup( gconstpointer mem, - guint byte_size ); - -/* NULL terminated string arrays. - * g_strsplit(), g_strsplit_set() split up string into max_tokens tokens - * at delim and return a newly allocated string array. - * g_strjoinv() concatenates all of str_array's strings, sliding in an - * optional separator, the returned string is newly allocated. - * g_strfreev() frees the array itself and all of its strings. - * g_strdupv() copies a NULL-terminated array of strings - */ -gchar** g_strsplit( const gchar *string, - const gchar *delimiter, - gint max_tokens ); -gchar ** g_strsplit_set( const gchar *string, - const gchar *delimiters, - gint max_tokens ); -gchar* g_strjoinv( const gchar *separator, - gchar **str_array ); -void g_strfreev( gchar **str_array ); -gchar** g_strdupv( gchar **str_array ); - -gchar* g_stpcpy( gchar *dest, - const char *src ); - -G_CONST_RETURN gchar *g_strip_context( const gchar *msgid, - const gchar *msgval ); - -G_END_DECLS - -#endif /* __G_STRFUNCS_H__ */ diff --git a/tools/urt/tools/quake3/common/glib/gstring.h b/tools/urt/tools/quake3/common/glib/gstring.h deleted file mode 100644 index c430669..0000000 --- a/tools/urt/tools/quake3/common/glib/gstring.h +++ /dev/null @@ -1,155 +0,0 @@ -/* GLIB - Library of useful routines for C programming - * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the - * Free Software Foundation, Inc., 59 Temple Place - Suite 330, - * Boston, MA 02111-1307, USA. - */ - -/* - * Modified by the GLib Team and others 1997-2000. See the AUTHORS - * file for a list of people on the GLib Team. See the ChangeLog - * files for a list of changes. These files are distributed with - * GLib at ftp://ftp.gtk.org/pub/gtk/. - */ - -#ifndef __G_STRING_H__ -#define __G_STRING_H__ - -#include -#include -#include /* for G_CAN_INLINE */ - -G_BEGIN_DECLS - -typedef struct _GString GString; -typedef struct _GStringChunk GStringChunk; - -struct _GString -{ - gchar *str; - gsize len; - gsize allocated_len; -}; - -/* String Chunks - */ -GStringChunk* g_string_chunk_new( gsize size ); -void g_string_chunk_free( GStringChunk *chunk ); -gchar* g_string_chunk_insert( GStringChunk *chunk, - const gchar *string ); -gchar* g_string_chunk_insert_len( GStringChunk *chunk, - const gchar *string, - gssize len ); -gchar* g_string_chunk_insert_const( GStringChunk *chunk, - const gchar *string ); - - -/* Strings - */ -GString* g_string_new( const gchar *init ); -GString* g_string_new_len( const gchar *init, - gssize len ); -GString* g_string_sized_new( gsize dfl_size ); -gchar* g_string_free( GString *string, - gboolean free_segment ); -gboolean g_string_equal( const GString *v, - const GString *v2 ); -guint g_string_hash( const GString *str ); -GString* g_string_assign( GString *string, - const gchar *rval ); -GString* g_string_truncate( GString *string, - gsize len ); -GString* g_string_set_size( GString *string, - gsize len ); -GString* g_string_insert_len( GString *string, - gssize pos, - const gchar *val, - gssize len ); -GString* g_string_append( GString *string, - const gchar *val ); -GString* g_string_append_len( GString *string, - const gchar *val, - gssize len ); -GString* g_string_append_c( GString *string, - gchar c ); -GString* g_string_append_unichar( GString *string, - gunichar wc ); -GString* g_string_prepend( GString *string, - const gchar *val ); -GString* g_string_prepend_c( GString *string, - gchar c ); -GString* g_string_prepend_unichar( GString *string, - gunichar wc ); -GString* g_string_prepend_len( GString *string, - const gchar *val, - gssize len ); -GString* g_string_insert( GString *string, - gssize pos, - const gchar *val ); -GString* g_string_insert_c( GString *string, - gssize pos, - gchar c ); -GString* g_string_insert_unichar( GString *string, - gssize pos, - gunichar wc ); -GString* g_string_erase( GString *string, - gssize pos, - gssize len ); -GString* g_string_ascii_down( GString *string ); -GString* g_string_ascii_up( GString *string ); -void g_string_printf( GString *string, - const gchar *format, - ... ) G_GNUC_PRINTF( 2, 3 ); -void g_string_append_printf( GString *string, - const gchar *format, - ... ) G_GNUC_PRINTF( 2, 3 ); - -/* -- optimize g_strig_append_c --- */ -#ifdef G_CAN_INLINE -static inline GString* -g_string_append_c_inline( GString *gstring, - gchar c ){ - if ( gstring->len < gstring->allocated_len && 0 ) { - gstring->str[gstring->len++] = c; - gstring->str[gstring->len] = 0; - } - else{ - g_string_insert_c( gstring, -1, c ); - } - return gstring; -} -#define g_string_append_c( gstr,c ) g_string_append_c_inline( gstr, c ) -#endif /* G_CAN_INLINE */ - - -#ifndef G_DISABLE_DEPRECATED - -/* The following two functions are deprecated and will be removed in - * the next major release. They use the locale-specific tolower and - * toupper, which is almost never the right thing. - */ - -GString* g_string_down( GString *string ); -GString* g_string_up( GString *string ); - -/* These aliases are included for compatibility. */ -#define g_string_sprintf g_string_printf -#define g_string_sprintfa g_string_append_printf - -#endif /* G_DISABLE_DEPRECATED */ - -G_END_DECLS - -#endif /* __G_STRING_H__ */ diff --git a/tools/urt/tools/quake3/common/glib/gthread.h b/tools/urt/tools/quake3/common/glib/gthread.h deleted file mode 100644 index 1352406..0000000 --- a/tools/urt/tools/quake3/common/glib/gthread.h +++ /dev/null @@ -1,372 +0,0 @@ -/* GLIB - Library of useful routines for C programming - * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the - * Free Software Foundation, Inc., 59 Temple Place - Suite 330, - * Boston, MA 02111-1307, USA. - */ - -/* - * Modified by the GLib Team and others 1997-2000. See the AUTHORS - * file for a list of people on the GLib Team. See the ChangeLog - * files for a list of changes. These files are distributed with - * GLib at ftp://ftp.gtk.org/pub/gtk/. - */ - -#ifndef __G_THREAD_H__ -#define __G_THREAD_H__ - -#include -#include -#include /* for g_atomic_pointer_get */ - -G_BEGIN_DECLS - -/* GLib Thread support - */ - -extern GQuark g_thread_error_quark( void ); -#define G_THREAD_ERROR g_thread_error_quark() - -typedef enum -{ - G_THREAD_ERROR_AGAIN /* Resource temporarily unavailable */ -} GThreadError; - -typedef gpointer ( *GThreadFunc )( gpointer data ); - -typedef enum -{ - G_THREAD_PRIORITY_LOW, - G_THREAD_PRIORITY_NORMAL, - G_THREAD_PRIORITY_HIGH, - G_THREAD_PRIORITY_URGENT -} GThreadPriority; - -typedef struct _GThread GThread; -struct _GThread -{ - /*< private >*/ - GThreadFunc func; - gpointer data; - gboolean joinable; - GThreadPriority priority; -}; - -typedef struct _GMutex GMutex; -typedef struct _GCond GCond; -typedef struct _GPrivate GPrivate; -typedef struct _GStaticPrivate GStaticPrivate; - -typedef struct _GThreadFunctions GThreadFunctions; -struct _GThreadFunctions -{ - GMutex* ( *mutex_new )(void); - void ( *mutex_lock )( GMutex *mutex ); - gboolean ( *mutex_trylock )( GMutex *mutex ); - void ( *mutex_unlock )( GMutex *mutex ); - void ( *mutex_free )( GMutex *mutex ); - GCond* ( *cond_new )(void); - void ( *cond_signal )( GCond *cond ); - void ( *cond_broadcast )( GCond *cond ); - void ( *cond_wait )( GCond *cond, - GMutex *mutex ); - gboolean ( *cond_timed_wait )( GCond *cond, - GMutex *mutex, - GTimeVal *end_time ); - void ( *cond_free )( GCond *cond ); - GPrivate* ( *private_new )(GDestroyNotify destructor); - gpointer ( *private_get )( GPrivate *private_key ); - void ( *private_set )( GPrivate *private_key, - gpointer data ); - void ( *thread_create )( GThreadFunc func, - gpointer data, - gulong stack_size, - gboolean joinable, - gboolean bound, - GThreadPriority priority, - gpointer thread, - GError **error ); - void ( *thread_yield )( void ); - void ( *thread_join )( gpointer thread ); - void ( *thread_exit )( void ); - void ( *thread_set_priority )( gpointer thread, - GThreadPriority priority ); - void ( *thread_self )( gpointer thread ); - gboolean ( *thread_equal )( gpointer thread1, - gpointer thread2 ); -}; - -GLIB_VAR GThreadFunctions g_thread_functions_for_glib_use; -GLIB_VAR gboolean g_thread_use_default_impl; -GLIB_VAR gboolean g_threads_got_initialized; - -/* initializes the mutex/cond/private implementation for glib, might - * only be called once, and must not be called directly or indirectly - * from another glib-function, e.g. as a callback. - */ -void g_thread_init( GThreadFunctions *vtable ); - -/* Errorcheck mutexes. If you define G_ERRORCHECK_MUTEXES, then all - * mutexes will check for re-locking and re-unlocking */ - -/* Initialize thread system with errorcheck mutexes. vtable must be - * NULL. Do not call directly. Use #define G_ERRORCHECK_MUTEXES - * instead. - */ -void g_thread_init_with_errorcheck_mutexes( GThreadFunctions* vtable ); - -/* A random number to recognize debug calls to g_mutex_... */ -#define G_MUTEX_DEBUG_MAGIC 0xf8e18ad7 - -#ifdef G_ERRORCHECK_MUTEXES -#define g_thread_init( vtable ) g_thread_init_with_errorcheck_mutexes( vtable ) -#endif - -/* internal function for fallback static mutex implementation */ -GMutex* g_static_mutex_get_mutex_impl( GMutex **mutex ); - -#define g_static_mutex_get_mutex_impl_shortcut( mutex ) \ - ( g_atomic_pointer_get( (gpointer*)mutex ) ? *( mutex ) : \ - g_static_mutex_get_mutex_impl( mutex ) ) - -/* shorthands for conditional and unconditional function calls */ - -#define G_THREAD_UF( op, arglist ) \ - ( *g_thread_functions_for_glib_use.op ) arglist -#define G_THREAD_CF( op, fail, arg ) \ - ( g_thread_supported() ? G_THREAD_UF( op, arg ) : ( fail ) ) -#define G_THREAD_ECF( op, fail, mutex, type ) \ - ( g_thread_supported() ? ( ( type ( * )( GMutex*, gulong, gchar* ) ) \ - ( *g_thread_functions_for_glib_use.op ) ) \ - ( mutex, G_MUTEX_DEBUG_MAGIC, G_STRLOC ) : ( fail ) ) - -#ifndef G_ERRORCHECK_MUTEXES -# define g_mutex_lock( mutex ) \ - G_THREAD_CF( mutex_lock, (void)0, ( mutex ) ) -# define g_mutex_trylock( mutex ) \ - G_THREAD_CF( mutex_trylock, TRUE, ( mutex ) ) -# define g_mutex_unlock( mutex ) \ - G_THREAD_CF( mutex_unlock, (void)0, ( mutex ) ) -# define g_mutex_free( mutex ) \ - G_THREAD_CF( mutex_free, (void)0, ( mutex ) ) -# define g_cond_wait( cond, mutex ) \ - G_THREAD_CF( cond_wait, (void)0, ( cond, mutex ) ) -# define g_cond_timed_wait( cond, mutex, abs_time ) \ - G_THREAD_CF( cond_timed_wait, TRUE, ( cond, mutex, abs_time ) ) -#else /* G_ERRORCHECK_MUTEXES */ -# define g_mutex_lock( mutex ) \ - G_THREAD_ECF( mutex_lock, (void)0, ( mutex ), void ) -# define g_mutex_trylock( mutex ) \ - G_THREAD_ECF( mutex_trylock, TRUE, ( mutex ), gboolean ) -# define g_mutex_unlock( mutex ) \ - G_THREAD_ECF( mutex_unlock, (void)0, ( mutex ), void ) -# define g_mutex_free( mutex ) \ - G_THREAD_ECF( mutex_free, (void)0, ( mutex ), void ) -# define g_cond_wait( cond, mutex ) \ - ( g_thread_supported() ? ( ( void ( * )( GCond*, GMutex*, gulong, gchar* ) ) \ - g_thread_functions_for_glib_use.cond_wait ) \ - ( cond, mutex, G_MUTEX_DEBUG_MAGIC, G_STRLOC ) : (void) 0 ) -# define g_cond_timed_wait( cond, mutex, abs_time ) \ - ( g_thread_supported() ? \ - ( ( gboolean ( * )( GCond*, GMutex*, GTimeVal*, gulong, gchar* ) ) \ - g_thread_functions_for_glib_use.cond_timed_wait ) \ - ( cond, mutex, abs_time, G_MUTEX_DEBUG_MAGIC, G_STRLOC ) : TRUE ) -#endif /* G_ERRORCHECK_MUTEXES */ - -#define g_thread_supported() ( g_threads_got_initialized ) -#define g_mutex_new() G_THREAD_UF( mutex_new, ( ) ) -#define g_cond_new() G_THREAD_UF( cond_new, ( ) ) -#define g_cond_signal( cond ) G_THREAD_CF( cond_signal, (void)0, ( cond ) ) -#define g_cond_broadcast( cond ) G_THREAD_CF( cond_broadcast, (void)0, ( cond ) ) -#define g_cond_free( cond ) G_THREAD_CF( cond_free, (void)0, ( cond ) ) -#define g_private_new( destructor ) G_THREAD_UF( private_new, ( destructor ) ) -#define g_private_get( private_key ) G_THREAD_CF( private_get, \ - ( (gpointer)private_key ), \ - ( private_key ) ) -#define g_private_set( private_key, value ) G_THREAD_CF( private_set, \ - (void) ( private_key = \ - (GPrivate*) ( value ) ), \ - ( private_key, value ) ) -#define g_thread_yield() G_THREAD_CF( thread_yield, (void)0, ( ) ) - -#define g_thread_create( func, data, joinable, error ) \ - ( g_thread_create_full( func, data, 0, joinable, FALSE, \ - G_THREAD_PRIORITY_NORMAL, error ) ) - -GThread* g_thread_create_full( GThreadFunc func, - gpointer data, - gulong stack_size, - gboolean joinable, - gboolean bound, - GThreadPriority priority, - GError **error ); -GThread* g_thread_self( void ); -void g_thread_exit( gpointer retval ); -gpointer g_thread_join( GThread *thread ); - -void g_thread_set_priority( GThread *thread, - GThreadPriority priority ); - -/* GStaticMutexes can be statically initialized with the value - * G_STATIC_MUTEX_INIT, and then they can directly be used, that is - * much easier, than having to explicitly allocate the mutex before - * use - */ -#define g_static_mutex_lock( mutex ) \ - g_mutex_lock( g_static_mutex_get_mutex( mutex ) ) -#define g_static_mutex_trylock( mutex ) \ - g_mutex_trylock( g_static_mutex_get_mutex( mutex ) ) -#define g_static_mutex_unlock( mutex ) \ - g_mutex_unlock( g_static_mutex_get_mutex( mutex ) ) -void g_static_mutex_init( GStaticMutex *mutex ); -void g_static_mutex_free( GStaticMutex *mutex ); - -struct _GStaticPrivate -{ - /*< private >*/ - guint index; -}; -#define G_STATIC_PRIVATE_INIT { 0 } -void g_static_private_init( GStaticPrivate *private_key ); -gpointer g_static_private_get( GStaticPrivate *private_key ); -void g_static_private_set( GStaticPrivate *private_key, - gpointer data, - GDestroyNotify notify ); -void g_static_private_free( GStaticPrivate *private_key ); - -typedef struct _GStaticRecMutex GStaticRecMutex; -struct _GStaticRecMutex -{ - /*< private >*/ - GStaticMutex mutex; - guint depth; - GSystemThread owner; -}; - -#define G_STATIC_REC_MUTEX_INIT { G_STATIC_MUTEX_INIT } -void g_static_rec_mutex_init( GStaticRecMutex *mutex ); -void g_static_rec_mutex_lock( GStaticRecMutex *mutex ); -gboolean g_static_rec_mutex_trylock( GStaticRecMutex *mutex ); -void g_static_rec_mutex_unlock( GStaticRecMutex *mutex ); -void g_static_rec_mutex_lock_full( GStaticRecMutex *mutex, - guint depth ); -guint g_static_rec_mutex_unlock_full( GStaticRecMutex *mutex ); -void g_static_rec_mutex_free( GStaticRecMutex *mutex ); - -typedef struct _GStaticRWLock GStaticRWLock; -struct _GStaticRWLock -{ - /*< private >*/ - GStaticMutex mutex; - GCond *read_cond; - GCond *write_cond; - guint read_counter; - gboolean have_writer; - guint want_to_read; - guint want_to_write; -}; - -#define G_STATIC_RW_LOCK_INIT { G_STATIC_MUTEX_INIT, NULL, NULL, 0, FALSE, 0, 0 } - -void g_static_rw_lock_init( GStaticRWLock* lock ); -void g_static_rw_lock_reader_lock( GStaticRWLock* lock ); -gboolean g_static_rw_lock_reader_trylock( GStaticRWLock* lock ); -void g_static_rw_lock_reader_unlock( GStaticRWLock* lock ); -void g_static_rw_lock_writer_lock( GStaticRWLock* lock ); -gboolean g_static_rw_lock_writer_trylock( GStaticRWLock* lock ); -void g_static_rw_lock_writer_unlock( GStaticRWLock* lock ); -void g_static_rw_lock_free( GStaticRWLock* lock ); - -typedef enum -{ - G_ONCE_STATUS_NOTCALLED, - G_ONCE_STATUS_PROGRESS, - G_ONCE_STATUS_READY -} GOnceStatus; - -typedef struct _GOnce GOnce; -struct _GOnce -{ - volatile GOnceStatus status; - volatile gpointer retval; -}; - -#define G_ONCE_INIT { G_ONCE_STATUS_NOTCALLED, NULL } - -gpointer g_once_impl( GOnce *once, GThreadFunc func, gpointer arg ); - -#ifdef G_ATOMIC_OP_MEMORY_BARRIER_NEEDED -# define g_once( once, func, arg ) g_once_impl( ( once ), ( func ), ( arg ) ) -#else /* !G_ATOMIC_OP_MEMORY_BARRIER_NEEDED*/ -# define g_once( once, func, arg ) \ - ( ( ( once )->status == G_ONCE_STATUS_READY ) ? \ - ( once )->retval : \ - g_once_impl( ( once ), ( func ), ( arg ) ) ) -#endif /* G_ATOMIC_OP_MEMORY_BARRIER_NEEDED */ - -/* these are some convenience macros that expand to nothing if GLib - * was configured with --disable-threads. for using StaticMutexes, - * you define them with G_LOCK_DEFINE_STATIC (name) or G_LOCK_DEFINE (name) - * if you need to export the mutex. With G_LOCK_EXTERN (name) you can - * declare such an globally defined lock. name is a unique identifier - * for the protected varibale or code portion. locking, testing and - * unlocking of such mutexes can be done with G_LOCK(), G_UNLOCK() and - * G_TRYLOCK() respectively. - */ -extern void glib_dummy_decl( void ); -#define G_LOCK_NAME( name ) g__ ## name ## _lock -#ifdef G_THREADS_ENABLED -# define G_LOCK_DEFINE_STATIC( name ) static G_LOCK_DEFINE( name ) -# define G_LOCK_DEFINE( name ) \ - GStaticMutex G_LOCK_NAME( name ) = G_STATIC_MUTEX_INIT -# define G_LOCK_EXTERN( name ) extern GStaticMutex G_LOCK_NAME( name ) - -# ifdef G_DEBUG_LOCKS -# define G_LOCK( name ) G_STMT_START { \ - g_log( G_LOG_DOMAIN, G_LOG_LEVEL_DEBUG, \ - "file %s: line %d (%s): locking: %s ", \ - __FILE__, __LINE__, G_GNUC_PRETTY_FUNCTION, \ - # name ); \ - g_static_mutex_lock( &G_LOCK_NAME( name ) ); \ -} G_STMT_END -# define G_UNLOCK( name ) G_STMT_START { \ - g_log( G_LOG_DOMAIN, G_LOG_LEVEL_DEBUG, \ - "file %s: line %d (%s): unlocking: %s ", \ - __FILE__, __LINE__, G_GNUC_PRETTY_FUNCTION, \ - # name ); \ - g_static_mutex_unlock( &G_LOCK_NAME( name ) ); \ -} G_STMT_END -# define G_TRYLOCK( name ) \ - ( g_log( G_LOG_DOMAIN, G_LOG_LEVEL_DEBUG, \ - "file %s: line %d (%s): try locking: %s ", \ - __FILE__, __LINE__, G_GNUC_PRETTY_FUNCTION, \ - # name ), g_static_mutex_trylock( &G_LOCK_NAME( name ) ) ) -# else /* !G_DEBUG_LOCKS */ -# define G_LOCK( name ) g_static_mutex_lock( &G_LOCK_NAME( name ) ) -# define G_UNLOCK( name ) g_static_mutex_unlock( &G_LOCK_NAME( name ) ) -# define G_TRYLOCK( name ) g_static_mutex_trylock( &G_LOCK_NAME( name ) ) -# endif /* !G_DEBUG_LOCKS */ -#else /* !G_THREADS_ENABLED */ -# define G_LOCK_DEFINE_STATIC( name ) extern void glib_dummy_decl( void ) -# define G_LOCK_DEFINE( name ) extern void glib_dummy_decl( void ) -# define G_LOCK_EXTERN( name ) extern void glib_dummy_decl( void ) -# define G_LOCK( name ) -# define G_UNLOCK( name ) -# define G_TRYLOCK( name ) ( TRUE ) -#endif /* !G_THREADS_ENABLED */ - -G_END_DECLS - -#endif /* __G_THREAD_H__ */ diff --git a/tools/urt/tools/quake3/common/glib/gthreadpool.h b/tools/urt/tools/quake3/common/glib/gthreadpool.h deleted file mode 100644 index fae3e7d..0000000 --- a/tools/urt/tools/quake3/common/glib/gthreadpool.h +++ /dev/null @@ -1,101 +0,0 @@ -/* GLIB - Library of useful routines for C programming - * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the - * Free Software Foundation, Inc., 59 Temple Place - Suite 330, - * Boston, MA 02111-1307, USA. - */ - -/* - * Modified by the GLib Team and others 1997-2000. See the AUTHORS - * file for a list of people on the GLib Team. See the ChangeLog - * files for a list of changes. These files are distributed with - * GLib at ftp://ftp.gtk.org/pub/gtk/. - */ - -#ifndef __G_THREADPOOL_H__ -#define __G_THREADPOOL_H__ - -#include - -G_BEGIN_DECLS - -typedef struct _GThreadPool GThreadPool; - -/* Thread Pools - */ - -/* The real GThreadPool is bigger, so you may only create a thread - * pool with the constructor function */ -struct _GThreadPool -{ - GFunc func; - gpointer user_data; - gboolean exclusive; -}; - -/* Get a thread pool with the function func, at most max_threads may - * run at a time (max_threads == -1 means no limit), exclusive == TRUE - * means, that the threads shouldn't be shared and that they will be - * prestarted (otherwise they are started as needed) user_data is the - * 2nd argument to the func */ -GThreadPool* g_thread_pool_new( GFunc func, - gpointer user_data, - gint max_threads, - gboolean exclusive, - GError **error ); - -/* Push new data into the thread pool. This task is assigned to a thread later - * (when the maximal number of threads is reached for that pool) or now - * (otherwise). If necessary a new thread will be started. The function - * returns immediatly */ -void g_thread_pool_push( GThreadPool *pool, - gpointer data, - GError **error ); - -/* Set the number of threads, which can run concurrently for that pool, -1 - * means no limit. 0 means has the effect, that the pool won't process - * requests until the limit is set higher again */ -void g_thread_pool_set_max_threads( GThreadPool *pool, - gint max_threads, - GError **error ); -gint g_thread_pool_get_max_threads( GThreadPool *pool ); - -/* Get the number of threads assigned to that pool. This number doesn't - * necessarily represent the number of working threads in that pool */ -guint g_thread_pool_get_num_threads( GThreadPool *pool ); - -/* Get the number of unprocessed items in the pool */ -guint g_thread_pool_unprocessed( GThreadPool *pool ); - -/* Free the pool, immediate means, that all unprocessed items in the queue - * wont be processed, wait means, that the function doesn't return immediatly, - * but after all threads in the pool are ready processing items. immediate - * does however not mean, that threads are killed. */ -void g_thread_pool_free( GThreadPool *pool, - gboolean immediate, - gboolean wait ); - -/* Set the maximal number of unused threads before threads will be stopped by - * GLib, -1 means no limit */ -void g_thread_pool_set_max_unused_threads( gint max_threads ); -gint g_thread_pool_get_max_unused_threads( void ); -guint g_thread_pool_get_num_unused_threads( void ); - -/* Stop all currently unused threads, but leave the limit untouched */ -void g_thread_pool_stop_unused_threads( void ); - -G_END_DECLS - -#endif /* __G_THREADPOOL_H__ */ diff --git a/tools/urt/tools/quake3/common/glib/gtimer.h b/tools/urt/tools/quake3/common/glib/gtimer.h deleted file mode 100644 index 2c0809c..0000000 --- a/tools/urt/tools/quake3/common/glib/gtimer.h +++ /dev/null @@ -1,58 +0,0 @@ -/* GLIB - Library of useful routines for C programming - * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the - * Free Software Foundation, Inc., 59 Temple Place - Suite 330, - * Boston, MA 02111-1307, USA. - */ - -/* - * Modified by the GLib Team and others 1997-2000. See the AUTHORS - * file for a list of people on the GLib Team. See the ChangeLog - * files for a list of changes. These files are distributed with - * GLib at ftp://ftp.gtk.org/pub/gtk/. - */ - -#ifndef __G_TIMER_H__ -#define __G_TIMER_H__ - -#include - -G_BEGIN_DECLS - -/* Timer - */ - -/* microseconds per second */ -typedef struct _GTimer GTimer; - -#define G_USEC_PER_SEC 1000000 - -GTimer* g_timer_new( void ); -void g_timer_destroy( GTimer *timer ); -void g_timer_start( GTimer *timer ); -void g_timer_stop( GTimer *timer ); -void g_timer_reset( GTimer *timer ); -void g_timer_continue( GTimer *timer ); -gdouble g_timer_elapsed( GTimer *timer, - gulong *microseconds ); - -void g_usleep( gulong microseconds ); - -void g_time_val_add( GTimeVal *time_, - glong microseconds ); - -G_END_DECLS - -#endif /* __G_TIMER_H__ */ diff --git a/tools/urt/tools/quake3/common/glib/gtree.h b/tools/urt/tools/quake3/common/glib/gtree.h deleted file mode 100644 index 6a35e75..0000000 --- a/tools/urt/tools/quake3/common/glib/gtree.h +++ /dev/null @@ -1,87 +0,0 @@ -/* GLIB - Library of useful routines for C programming - * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the - * Free Software Foundation, Inc., 59 Temple Place - Suite 330, - * Boston, MA 02111-1307, USA. - */ - -/* - * Modified by the GLib Team and others 1997-2000. See the AUTHORS - * file for a list of people on the GLib Team. See the ChangeLog - * files for a list of changes. These files are distributed with - * GLib at ftp://ftp.gtk.org/pub/gtk/. - */ - -#ifndef __G_TREE_H__ -#define __G_TREE_H__ - -#include - -G_BEGIN_DECLS - -typedef struct _GTree GTree; - -typedef gboolean ( *GTraverseFunc )( gpointer key, - gpointer value, - gpointer data ); - -/* Balanced binary trees - */ -GTree* g_tree_new( GCompareFunc key_compare_func ); -GTree* g_tree_new_with_data( GCompareDataFunc key_compare_func, - gpointer key_compare_data ); -GTree* g_tree_new_full( GCompareDataFunc key_compare_func, - gpointer key_compare_data, - GDestroyNotify key_destroy_func, - GDestroyNotify value_destroy_func ); -void g_tree_destroy( GTree *tree ); -void g_tree_insert( GTree *tree, - gpointer key, - gpointer value ); -void g_tree_replace( GTree *tree, - gpointer key, - gpointer value ); -void g_tree_remove( GTree *tree, - gconstpointer key ); -void g_tree_steal( GTree *tree, - gconstpointer key ); -gpointer g_tree_lookup( GTree *tree, - gconstpointer key ); -gboolean g_tree_lookup_extended( GTree *tree, - gconstpointer lookup_key, - gpointer *orig_key, - gpointer *value ); -void g_tree_foreach( GTree *tree, - GTraverseFunc func, - gpointer user_data ); - -#ifndef G_DISABLE_DEPRECATED -void g_tree_traverse( GTree *tree, - GTraverseFunc traverse_func, - GTraverseType traverse_type, - gpointer user_data ); -#endif /* G_DISABLE_DEPRECATED */ - -gpointer g_tree_search( GTree *tree, - GCompareFunc search_func, - gconstpointer user_data ); -gint g_tree_height( GTree *tree ); -gint g_tree_nnodes( GTree *tree ); - - - -G_END_DECLS - -#endif /* __G_TREE_H__ */ diff --git a/tools/urt/tools/quake3/common/glib/gtypes.h b/tools/urt/tools/quake3/common/glib/gtypes.h deleted file mode 100644 index 3af4eef..0000000 --- a/tools/urt/tools/quake3/common/glib/gtypes.h +++ /dev/null @@ -1,418 +0,0 @@ -/* GLIB - Library of useful routines for C programming - * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the - * Free Software Foundation, Inc., 59 Temple Place - Suite 330, - * Boston, MA 02111-1307, USA. - */ - -/* - * Modified by the GLib Team and others 1997-2000. See the AUTHORS - * file for a list of people on the GLib Team. See the ChangeLog - * files for a list of changes. These files are distributed with - * GLib at ftp://ftp.gtk.org/pub/gtk/. - */ - -#ifndef __G_TYPES_H__ -#define __G_TYPES_H__ - -#include - -G_BEGIN_DECLS - -/* Provide type definitions for commonly used types. - * These are useful because a "gint8" can be adjusted - * to be 1 byte (8 bits) on all platforms. Similarly and - * more importantly, "gint32" can be adjusted to be - * 4 bytes (32 bits) on all platforms. - */ - -typedef char gchar; -typedef short gshort; -typedef long glong; -typedef int gint; -typedef gint gboolean; - -typedef unsigned char guchar; -typedef unsigned short gushort; -typedef unsigned long gulong; -typedef unsigned int guint; - -typedef float gfloat; -typedef double gdouble; - -/* Define min and max constants for the fixed size numerical types */ -#define G_MININT8 ( (gint8) 0x80 ) -#define G_MAXINT8 ( (gint8) 0x7f ) -#define G_MAXUINT8 ( (guint8) 0xff ) - -#define G_MININT16 ( (gint16) 0x8000 ) -#define G_MAXINT16 ( (gint16) 0x7fff ) -#define G_MAXUINT16 ( (guint16) 0xffff ) - -#define G_MININT32 ( (gint32) 0x80000000 ) -#define G_MAXINT32 ( (gint32) 0x7fffffff ) -#define G_MAXUINT32 ( (guint32) 0xffffffff ) - -#define G_MININT64 G_GINT64_CONSTANT( 0x8000000000000000 ) -#define G_MAXINT64 G_GINT64_CONSTANT( 0x7fffffffffffffff ) -#define G_MAXUINT64 G_GINT64_CONSTANT( 0xffffffffffffffffU ) - -typedef void* gpointer; -typedef const void *gconstpointer; - -typedef gint ( *GCompareFunc )( gconstpointer a, - gconstpointer b ); -typedef gint ( *GCompareDataFunc )( gconstpointer a, - gconstpointer b, - gpointer user_data ); -typedef gboolean ( *GEqualFunc )( gconstpointer a, - gconstpointer b ); -typedef void ( *GDestroyNotify )( gpointer data ); -typedef void ( *GFunc )( gpointer data, - gpointer user_data ); -typedef guint ( *GHashFunc )( gconstpointer key ); -typedef void ( *GHFunc )( gpointer key, - gpointer value, - gpointer user_data ); -typedef void ( *GFreeFunc )( gpointer data ); - -/* Define some mathematical constants that aren't available - * symbolically in some strict ISO C implementations. - */ -#define G_E 2.7182818284590452354E0 -#define G_LN2 6.9314718055994530942E-1 -#define G_LN10 2.3025850929940456840E0 -#define G_PI 3.14159265358979323846E0 -#define G_PI_2 1.57079632679489661923E0 -#define G_PI_4 0.78539816339744830962E0 -#define G_SQRT2 1.4142135623730950488E0 - -/* Portable endian checks and conversions - * - * glibconfig.h defines G_BYTE_ORDER which expands to one of - * the below macros. - */ -#define G_LITTLE_ENDIAN 1234 -#define G_BIG_ENDIAN 4321 -#define G_PDP_ENDIAN 3412 /* unused, need specific PDP check */ - - -/* Basic bit swapping functions - */ -#define GUINT16_SWAP_LE_BE_CONSTANT( val ) ( (guint16) ( \ - (guint16) ( (guint16) ( val ) >> 8 ) | \ - (guint16) ( (guint16) ( val ) << 8 ) ) ) - -#define GUINT32_SWAP_LE_BE_CONSTANT( val ) ( (guint32) ( \ - ( ( (guint32) ( val ) & (guint32) 0x000000ffU ) << 24 ) | \ - ( ( (guint32) ( val ) & (guint32) 0x0000ff00U ) << 8 ) | \ - ( ( (guint32) ( val ) & (guint32) 0x00ff0000U ) >> 8 ) | \ - ( ( (guint32) ( val ) & (guint32) 0xff000000U ) >> 24 ) ) ) - -#define GUINT64_SWAP_LE_BE_CONSTANT( val ) ( (guint64) ( \ - ( ( (guint64) ( val ) & \ - (guint64) G_GINT64_CONSTANT( 0x00000000000000ffU ) ) << 56 ) | \ - ( ( (guint64) ( val ) & \ - (guint64) G_GINT64_CONSTANT( 0x000000000000ff00U ) ) << 40 ) | \ - ( ( (guint64) ( val ) & \ - (guint64) G_GINT64_CONSTANT( 0x0000000000ff0000U ) ) << 24 ) | \ - ( ( (guint64) ( val ) & \ - (guint64) G_GINT64_CONSTANT( 0x00000000ff000000U ) ) << 8 ) | \ - ( ( (guint64) ( val ) & \ - (guint64) G_GINT64_CONSTANT( 0x000000ff00000000U ) ) >> 8 ) | \ - ( ( (guint64) ( val ) & \ - (guint64) G_GINT64_CONSTANT( 0x0000ff0000000000U ) ) >> 24 ) | \ - ( ( (guint64) ( val ) & \ - (guint64) G_GINT64_CONSTANT( 0x00ff000000000000U ) ) >> 40 ) | \ - ( ( (guint64) ( val ) & \ - (guint64) G_GINT64_CONSTANT( 0xff00000000000000U ) ) >> 56 ) ) ) - -/* Arch specific stuff for speed - */ -#if defined ( __GNUC__ ) && ( __GNUC__ >= 2 ) && defined ( __OPTIMIZE__ ) -# if defined ( __i386__ ) -# define GUINT16_SWAP_LE_BE_IA32( val ) \ - ( __extension__ \ - ( { register guint16 __v, __x = ( (guint16) ( val ) ); \ - if ( __builtin_constant_p( __x ) ) { \ - __v = GUINT16_SWAP_LE_BE_CONSTANT( __x ); } \ - else{ \ - __asm__( "rorw $8, %w0" \ - : "=r" ( __v ) \ - : "0" ( __x ) \ - : "cc" ); } \ - __v; } ) ) -# if !defined ( __i486__ ) && !defined ( __i586__ ) \ - && !defined ( __pentium__ ) && !defined ( __i686__ ) \ - && !defined ( __pentiumpro__ ) && !defined ( __pentium4__ ) -# define GUINT32_SWAP_LE_BE_IA32( val ) \ - ( __extension__ \ - ( { register guint32 __v, __x = ( (guint32) ( val ) ); \ - if ( __builtin_constant_p( __x ) ) { \ - __v = GUINT32_SWAP_LE_BE_CONSTANT( __x ); } \ - else{ \ - __asm__( "rorw $8, %w0\n\t" \ - "rorl $16, %0\n\t" \ - "rorw $8, %w0" \ - : "=r" ( __v ) \ - : "0" ( __x ) \ - : "cc" ); } \ - __v; } ) ) -# else /* 486 and higher has bswap */ -# define GUINT32_SWAP_LE_BE_IA32( val ) \ - ( __extension__ \ - ( { register guint32 __v, __x = ( (guint32) ( val ) ); \ - if ( __builtin_constant_p( __x ) ) { \ - __v = GUINT32_SWAP_LE_BE_CONSTANT( __x ); } \ - else{ \ - __asm__( "bswap %0" \ - : "=r" ( __v ) \ - : "0" ( __x ) ); } \ - __v; } ) ) -# endif /* processor specific 32-bit stuff */ -# define GUINT64_SWAP_LE_BE_IA32( val ) \ - ( __extension__ \ - ( { union { guint64 __ll; \ - guint32 __l[2]; } __w, __r; \ - __w.__ll = ( (guint64) ( val ) ); \ - if ( __builtin_constant_p( __w.__ll ) ) { \ - __r.__ll = GUINT64_SWAP_LE_BE_CONSTANT( __w.__ll ); } \ - else \ - { \ - __r.__l[0] = GUINT32_SWAP_LE_BE( __w.__l[1] ); \ - __r.__l[1] = GUINT32_SWAP_LE_BE( __w.__l[0] ); \ - } \ - __r.__ll; } ) ) -/* Possibly just use the constant version and let gcc figure it out? */ -# define GUINT16_SWAP_LE_BE( val ) ( GUINT16_SWAP_LE_BE_IA32( val ) ) -# define GUINT32_SWAP_LE_BE( val ) ( GUINT32_SWAP_LE_BE_IA32( val ) ) -# define GUINT64_SWAP_LE_BE( val ) ( GUINT64_SWAP_LE_BE_IA32( val ) ) -# elif defined ( __ia64__ ) -# define GUINT16_SWAP_LE_BE_IA64( val ) \ - ( __extension__ \ - ( { register guint16 __v, __x = ( (guint16) ( val ) ); \ - if ( __builtin_constant_p( __x ) ) { \ - __v = GUINT16_SWAP_LE_BE_CONSTANT( __x ); } \ - else{ \ - __asm__ __volatile__ ( "shl %0 = %1, 48 ;;" \ - "mux1 %0 = %0, @rev ;;" \ - : "=r" ( __v ) \ - : "r" ( __x ) ); } \ - __v; } ) ) -# define GUINT32_SWAP_LE_BE_IA64( val ) \ - ( __extension__ \ - ( { register guint32 __v, __x = ( (guint32) ( val ) ); \ - if ( __builtin_constant_p( __x ) ) { \ - __v = GUINT32_SWAP_LE_BE_CONSTANT( __x ); } \ - else{ \ - __asm__ __volatile__ ( "shl %0 = %1, 32 ;;" \ - "mux1 %0 = %0, @rev ;;" \ - : "=r" ( __v ) \ - : "r" ( __x ) ); } \ - __v; } ) ) -# define GUINT64_SWAP_LE_BE_IA64( val ) \ - ( __extension__ \ - ( { register guint64 __v, __x = ( (guint64) ( val ) ); \ - if ( __builtin_constant_p( __x ) ) { \ - __v = GUINT64_SWAP_LE_BE_CONSTANT( __x ); } \ - else{ \ - __asm__ __volatile__ ( "mux1 %0 = %1, @rev ;;" \ - : "=r" ( __v ) \ - : "r" ( __x ) ); } \ - __v; } ) ) -# define GUINT16_SWAP_LE_BE( val ) ( GUINT16_SWAP_LE_BE_IA64( val ) ) -# define GUINT32_SWAP_LE_BE( val ) ( GUINT32_SWAP_LE_BE_IA64( val ) ) -# define GUINT64_SWAP_LE_BE( val ) ( GUINT64_SWAP_LE_BE_IA64( val ) ) -# elif defined ( __x86_64__ ) -# define GUINT32_SWAP_LE_BE_X86_64( val ) \ - ( __extension__ \ - ( { register guint32 __v, __x = ( (guint32) ( val ) ); \ - if ( __builtin_constant_p( __x ) ) { \ - __v = GUINT32_SWAP_LE_BE_CONSTANT( __x ); } \ - else{ \ - __asm__( "bswapl %0" \ - : "=r" ( __v ) \ - : "0" ( __x ) ); } \ - __v; } ) ) -# define GUINT64_SWAP_LE_BE_X86_64( val ) \ - ( __extension__ \ - ( { register guint64 __v, __x = ( (guint64) ( val ) ); \ - if ( __builtin_constant_p( __x ) ) { \ - __v = GUINT64_SWAP_LE_BE_CONSTANT( __x ); } \ - else{ \ - __asm__( "bswapq %0" \ - : "=r" ( __v ) \ - : "0" ( __x ) ); } \ - __v; } ) ) -/* gcc seems to figure out optimal code for this on its own */ -# define GUINT16_SWAP_LE_BE( val ) ( GUINT16_SWAP_LE_BE_CONSTANT( val ) ) -# define GUINT32_SWAP_LE_BE( val ) ( GUINT32_SWAP_LE_BE_X86_64( val ) ) -# define GUINT64_SWAP_LE_BE( val ) ( GUINT64_SWAP_LE_BE_X86_64( val ) ) -# else /* generic gcc */ -# define GUINT16_SWAP_LE_BE( val ) ( GUINT16_SWAP_LE_BE_CONSTANT( val ) ) -# define GUINT32_SWAP_LE_BE( val ) ( GUINT32_SWAP_LE_BE_CONSTANT( val ) ) -# define GUINT64_SWAP_LE_BE( val ) ( GUINT64_SWAP_LE_BE_CONSTANT( val ) ) -# endif -#else /* generic */ -# define GUINT16_SWAP_LE_BE( val ) ( GUINT16_SWAP_LE_BE_CONSTANT( val ) ) -# define GUINT32_SWAP_LE_BE( val ) ( GUINT32_SWAP_LE_BE_CONSTANT( val ) ) -# define GUINT64_SWAP_LE_BE( val ) ( GUINT64_SWAP_LE_BE_CONSTANT( val ) ) -#endif /* generic */ - -#define GUINT16_SWAP_LE_PDP( val ) ( (guint16) ( val ) ) -#define GUINT16_SWAP_BE_PDP( val ) ( GUINT16_SWAP_LE_BE( val ) ) -#define GUINT32_SWAP_LE_PDP( val ) ( (guint32) ( \ - ( ( (guint32) ( val ) & (guint32) 0x0000ffffU ) << 16 ) | \ - ( ( (guint32) ( val ) & (guint32) 0xffff0000U ) >> 16 ) ) ) -#define GUINT32_SWAP_BE_PDP( val ) ( (guint32) ( \ - ( ( (guint32) ( val ) & (guint32) 0x00ff00ffU ) << 8 ) | \ - ( ( (guint32) ( val ) & (guint32) 0xff00ff00U ) >> 8 ) ) ) - -/* The G*_TO_?E() macros are defined in glibconfig.h. - * The transformation is symmetric, so the FROM just maps to the TO. - */ -#define GINT16_FROM_LE( val ) ( GINT16_TO_LE( val ) ) -#define GUINT16_FROM_LE( val ) ( GUINT16_TO_LE( val ) ) -#define GINT16_FROM_BE( val ) ( GINT16_TO_BE( val ) ) -#define GUINT16_FROM_BE( val ) ( GUINT16_TO_BE( val ) ) -#define GINT32_FROM_LE( val ) ( GINT32_TO_LE( val ) ) -#define GUINT32_FROM_LE( val ) ( GUINT32_TO_LE( val ) ) -#define GINT32_FROM_BE( val ) ( GINT32_TO_BE( val ) ) -#define GUINT32_FROM_BE( val ) ( GUINT32_TO_BE( val ) ) - -#define GINT64_FROM_LE( val ) ( GINT64_TO_LE( val ) ) -#define GUINT64_FROM_LE( val ) ( GUINT64_TO_LE( val ) ) -#define GINT64_FROM_BE( val ) ( GINT64_TO_BE( val ) ) -#define GUINT64_FROM_BE( val ) ( GUINT64_TO_BE( val ) ) - -#define GLONG_FROM_LE( val ) ( GLONG_TO_LE( val ) ) -#define GULONG_FROM_LE( val ) ( GULONG_TO_LE( val ) ) -#define GLONG_FROM_BE( val ) ( GLONG_TO_BE( val ) ) -#define GULONG_FROM_BE( val ) ( GULONG_TO_BE( val ) ) - -#define GINT_FROM_LE( val ) ( GINT_TO_LE( val ) ) -#define GUINT_FROM_LE( val ) ( GUINT_TO_LE( val ) ) -#define GINT_FROM_BE( val ) ( GINT_TO_BE( val ) ) -#define GUINT_FROM_BE( val ) ( GUINT_TO_BE( val ) ) - - -/* Portable versions of host-network order stuff - */ -#define g_ntohl( val ) ( GUINT32_FROM_BE( val ) ) -#define g_ntohs( val ) ( GUINT16_FROM_BE( val ) ) -#define g_htonl( val ) ( GUINT32_TO_BE( val ) ) -#define g_htons( val ) ( GUINT16_TO_BE( val ) ) - -/* IEEE Standard 754 Single Precision Storage Format (gfloat): - * - * 31 30 23 22 0 - * +--------+---------------+---------------+ - * | s 1bit | e[30:23] 8bit | f[22:0] 23bit | - * +--------+---------------+---------------+ - * B0------------------->B1------->B2-->B3--> - * - * IEEE Standard 754 Double Precision Storage Format (gdouble): - * - * 63 62 52 51 32 31 0 - * +--------+----------------+----------------+ +---------------+ - * | s 1bit | e[62:52] 11bit | f[51:32] 20bit | | f[31:0] 32bit | - * +--------+----------------+----------------+ +---------------+ - * B0--------------->B1---------->B2--->B3----> B4->B5->B6->B7-> - */ -/* subtract from biased_exponent to form base2 exponent (normal numbers) */ -typedef union _GDoubleIEEE754 GDoubleIEEE754; -typedef union _GFloatIEEE754 GFloatIEEE754; -#define G_IEEE754_FLOAT_BIAS ( 127 ) -#define G_IEEE754_DOUBLE_BIAS ( 1023 ) -/* multiply with base2 exponent to get base10 exponent (normal numbers) */ -#define G_LOG_2_BASE_10 ( 0.30102999566398119521 ) -#if G_BYTE_ORDER == G_LITTLE_ENDIAN -union _GFloatIEEE754 -{ - gfloat v_float; - struct { - guint mantissa : 23; - guint biased_exponent : 8; - guint sign : 1; - } mpn; -}; -union _GDoubleIEEE754 -{ - gdouble v_double; - struct { - guint mantissa_low : 32; - guint mantissa_high : 20; - guint biased_exponent : 11; - guint sign : 1; - } mpn; -}; -#elif G_BYTE_ORDER == G_BIG_ENDIAN -union _GFloatIEEE754 -{ - gfloat v_float; - struct { - guint sign : 1; - guint biased_exponent : 8; - guint mantissa : 23; - } mpn; -}; -union _GDoubleIEEE754 -{ - gdouble v_double; - struct { - guint sign : 1; - guint biased_exponent : 11; - guint mantissa_high : 20; - guint mantissa_low : 32; - } mpn; -}; -#else /* !G_LITTLE_ENDIAN && !G_BIG_ENDIAN */ -#error unknown ENDIAN type -#endif /* !G_LITTLE_ENDIAN && !G_BIG_ENDIAN */ - -typedef struct _GTimeVal GTimeVal; - -struct _GTimeVal -{ - glong tv_sec; - glong tv_usec; -}; - -G_END_DECLS - -/* We prefix variable declarations so they can - * properly get exported in windows dlls. - */ -#ifndef GLIB_VAR -# ifdef G_PLATFORM_WIN32 -# ifdef GLIB_STATIC_COMPILATION -# define GLIB_VAR extern -# else /* !GLIB_STATIC_COMPILATION */ -# ifdef GLIB_COMPILATION -# ifdef DLL_EXPORT -# define GLIB_VAR __declspec( dllexport ) -# else /* !DLL_EXPORT */ -# define GLIB_VAR extern -# endif /* !DLL_EXPORT */ -# else /* !GLIB_COMPILATION */ -# define GLIB_VAR extern __declspec( dllimport ) -# endif /* !GLIB_COMPILATION */ -# endif /* !GLIB_STATIC_COMPILATION */ -# else /* !G_PLATFORM_WIN32 */ -# define GLIB_VAR extern -# endif /* !G_PLATFORM_WIN32 */ -#endif /* GLIB_VAR */ - -#endif /* __G_TYPES_H__ */ diff --git a/tools/urt/tools/quake3/common/glib/gunicode.h b/tools/urt/tools/quake3/common/glib/gunicode.h deleted file mode 100644 index 30f6128..0000000 --- a/tools/urt/tools/quake3/common/glib/gunicode.h +++ /dev/null @@ -1,287 +0,0 @@ -/* gunicode.h - Unicode manipulation functions - * - * Copyright (C) 1999, 2000 Tom Tromey - * Copyright 2000 Red Hat, Inc. - * - * The Gnome Library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2 of the - * License, or (at your option) any later version. - * - * The Gnome Library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with the Gnome Library; see the file COPYING.LIB. If not, - * write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, - * Boston, MA 02111-1307, USA. - */ - -#ifndef __G_UNICODE_H__ -#define __G_UNICODE_H__ - -#include -#include - -G_BEGIN_DECLS - -typedef guint32 gunichar; -typedef guint16 gunichar2; - -/* These are the possible character classifications. - * See http://www.unicode.org/Public/UNIDATA/UnicodeData.html - */ -typedef enum -{ - G_UNICODE_CONTROL, - G_UNICODE_FORMAT, - G_UNICODE_UNASSIGNED, - G_UNICODE_PRIVATE_USE, - G_UNICODE_SURROGATE, - G_UNICODE_LOWERCASE_LETTER, - G_UNICODE_MODIFIER_LETTER, - G_UNICODE_OTHER_LETTER, - G_UNICODE_TITLECASE_LETTER, - G_UNICODE_UPPERCASE_LETTER, - G_UNICODE_COMBINING_MARK, - G_UNICODE_ENCLOSING_MARK, - G_UNICODE_NON_SPACING_MARK, - G_UNICODE_DECIMAL_NUMBER, - G_UNICODE_LETTER_NUMBER, - G_UNICODE_OTHER_NUMBER, - G_UNICODE_CONNECT_PUNCTUATION, - G_UNICODE_DASH_PUNCTUATION, - G_UNICODE_CLOSE_PUNCTUATION, - G_UNICODE_FINAL_PUNCTUATION, - G_UNICODE_INITIAL_PUNCTUATION, - G_UNICODE_OTHER_PUNCTUATION, - G_UNICODE_OPEN_PUNCTUATION, - G_UNICODE_CURRENCY_SYMBOL, - G_UNICODE_MODIFIER_SYMBOL, - G_UNICODE_MATH_SYMBOL, - G_UNICODE_OTHER_SYMBOL, - G_UNICODE_LINE_SEPARATOR, - G_UNICODE_PARAGRAPH_SEPARATOR, - G_UNICODE_SPACE_SEPARATOR -} GUnicodeType; - -/* These are the possible line break classifications. - * See http://www.unicode.org/unicode/reports/tr14/ - */ -typedef enum -{ - G_UNICODE_BREAK_MANDATORY, - G_UNICODE_BREAK_CARRIAGE_RETURN, - G_UNICODE_BREAK_LINE_FEED, - G_UNICODE_BREAK_COMBINING_MARK, - G_UNICODE_BREAK_SURROGATE, - G_UNICODE_BREAK_ZERO_WIDTH_SPACE, - G_UNICODE_BREAK_INSEPARABLE, - G_UNICODE_BREAK_NON_BREAKING_GLUE, - G_UNICODE_BREAK_CONTINGENT, - G_UNICODE_BREAK_SPACE, - G_UNICODE_BREAK_AFTER, - G_UNICODE_BREAK_BEFORE, - G_UNICODE_BREAK_BEFORE_AND_AFTER, - G_UNICODE_BREAK_HYPHEN, - G_UNICODE_BREAK_NON_STARTER, - G_UNICODE_BREAK_OPEN_PUNCTUATION, - G_UNICODE_BREAK_CLOSE_PUNCTUATION, - G_UNICODE_BREAK_QUOTATION, - G_UNICODE_BREAK_EXCLAMATION, - G_UNICODE_BREAK_IDEOGRAPHIC, - G_UNICODE_BREAK_NUMERIC, - G_UNICODE_BREAK_INFIX_SEPARATOR, - G_UNICODE_BREAK_SYMBOL, - G_UNICODE_BREAK_ALPHABETIC, - G_UNICODE_BREAK_PREFIX, - G_UNICODE_BREAK_POSTFIX, - G_UNICODE_BREAK_COMPLEX_CONTEXT, - G_UNICODE_BREAK_AMBIGUOUS, - G_UNICODE_BREAK_UNKNOWN, - G_UNICODE_BREAK_NEXT_LINE, - G_UNICODE_BREAK_WORD_JOINER -} GUnicodeBreakType; - -/* Returns TRUE if current locale uses UTF-8 charset. If CHARSET is - * not null, sets *CHARSET to the name of the current locale's - * charset. This value is statically allocated, and should be copied - * in case the locale's charset will be changed later using setlocale() - * or in some other way. - */ -gboolean g_get_charset( G_CONST_RETURN char **charset ); - -/* These are all analogs of the functions. - */ -gboolean g_unichar_isalnum( gunichar c ) G_GNUC_CONST; -gboolean g_unichar_isalpha( gunichar c ) G_GNUC_CONST; -gboolean g_unichar_iscntrl( gunichar c ) G_GNUC_CONST; -gboolean g_unichar_isdigit( gunichar c ) G_GNUC_CONST; -gboolean g_unichar_isgraph( gunichar c ) G_GNUC_CONST; -gboolean g_unichar_islower( gunichar c ) G_GNUC_CONST; -gboolean g_unichar_isprint( gunichar c ) G_GNUC_CONST; -gboolean g_unichar_ispunct( gunichar c ) G_GNUC_CONST; -gboolean g_unichar_isspace( gunichar c ) G_GNUC_CONST; -gboolean g_unichar_isupper( gunichar c ) G_GNUC_CONST; -gboolean g_unichar_isxdigit( gunichar c ) G_GNUC_CONST; -gboolean g_unichar_istitle( gunichar c ) G_GNUC_CONST; -gboolean g_unichar_isdefined( gunichar c ) G_GNUC_CONST; -gboolean g_unichar_iswide( gunichar c ) G_GNUC_CONST; - -/* More functions. These convert between the three cases. - * See the Unicode book to understand title case. */ -gunichar g_unichar_toupper( gunichar c ) G_GNUC_CONST; -gunichar g_unichar_tolower( gunichar c ) G_GNUC_CONST; -gunichar g_unichar_totitle( gunichar c ) G_GNUC_CONST; - -/* If C is a digit (according to `g_unichar_isdigit'), then return its - numeric value. Otherwise return -1. */ -gint g_unichar_digit_value( gunichar c ) G_GNUC_CONST; - -gint g_unichar_xdigit_value( gunichar c ) G_GNUC_CONST; - -/* Return the Unicode character type of a given character. */ -GUnicodeType g_unichar_type( gunichar c ) G_GNUC_CONST; - -/* Return the line break property for a given character */ -GUnicodeBreakType g_unichar_break_type( gunichar c ) G_GNUC_CONST; - - -/* Compute canonical ordering of a string in-place. This rearranges - decomposed characters in the string according to their combining - classes. See the Unicode manual for more information. */ -void g_unicode_canonical_ordering( gunichar *string, - gsize len ); - -/* Compute canonical decomposition of a character. Returns g_malloc()d - string of Unicode characters. RESULT_LEN is set to the resulting - length of the string. */ -gunichar *g_unicode_canonical_decomposition( gunichar ch, - gsize *result_len ); - -/* Array of skip-bytes-per-initial character. - */ -GLIB_VAR const gchar * const g_utf8_skip; - -#define g_utf8_next_char( p ) (char *)( ( p ) + g_utf8_skip[*(guchar *)( p )] ) - -gunichar g_utf8_get_char( const gchar *p ); -gunichar g_utf8_get_char_validated( const gchar *p, - gssize max_len ); - -gchar* g_utf8_offset_to_pointer( const gchar *str, - glong offset ); -glong g_utf8_pointer_to_offset( const gchar *str, - const gchar *pos ); -gchar* g_utf8_prev_char( const gchar *p ); -gchar* g_utf8_find_next_char( const gchar *p, - const gchar *end ); -gchar* g_utf8_find_prev_char( const gchar *str, - const gchar *p ); - -glong g_utf8_strlen( const gchar *p, - gssize max ); - -/* Copies n characters from src to dest */ -gchar* g_utf8_strncpy( gchar *dest, - const gchar *src, - gsize n ); - -/* Find the UTF-8 character corresponding to ch, in string p. These - functions are equivalants to strchr and strrchr */ -gchar* g_utf8_strchr( const gchar *p, - gssize len, - gunichar c ); -gchar* g_utf8_strrchr( const gchar *p, - gssize len, - gunichar c ); -gchar* g_utf8_strreverse( const gchar *str, - gssize len ); - -gunichar2 *g_utf8_to_utf16( const gchar *str, - glong len, - glong *items_read, - glong *items_written, - GError **error ); -gunichar * g_utf8_to_ucs4( const gchar *str, - glong len, - glong *items_read, - glong *items_written, - GError **error ); -gunichar * g_utf8_to_ucs4_fast( const gchar *str, - glong len, - glong *items_written ); -gunichar * g_utf16_to_ucs4( const gunichar2 *str, - glong len, - glong *items_read, - glong *items_written, - GError **error ); -gchar* g_utf16_to_utf8( const gunichar2 *str, - glong len, - glong *items_read, - glong *items_written, - GError **error ); -gunichar2 *g_ucs4_to_utf16( const gunichar *str, - glong len, - glong *items_read, - glong *items_written, - GError **error ); -gchar* g_ucs4_to_utf8( const gunichar *str, - glong len, - glong *items_read, - glong *items_written, - GError **error ); - -/* Convert a single character into UTF-8. outbuf must have at - * least 6 bytes of space. Returns the number of bytes in the - * result. - */ -gint g_unichar_to_utf8( gunichar c, - gchar *outbuf ); - -/* Validate a UTF8 string, return TRUE if valid, put pointer to - * first invalid char in **end - */ - -gboolean g_utf8_validate( const gchar *str, - gssize max_len, - const gchar **end ); - -/* Validate a Unicode character */ -gboolean g_unichar_validate( gunichar ch ); - -gchar *g_utf8_strup( const gchar *str, - gssize len ); -gchar *g_utf8_strdown( const gchar *str, - gssize len ); -gchar *g_utf8_casefold( const gchar *str, - gssize len ); - -typedef enum { - G_NORMALIZE_DEFAULT, - G_NORMALIZE_NFD = G_NORMALIZE_DEFAULT, - G_NORMALIZE_DEFAULT_COMPOSE, - G_NORMALIZE_NFC = G_NORMALIZE_DEFAULT_COMPOSE, - G_NORMALIZE_ALL, - G_NORMALIZE_NFKD = G_NORMALIZE_ALL, - G_NORMALIZE_ALL_COMPOSE, - G_NORMALIZE_NFKC = G_NORMALIZE_ALL_COMPOSE -} GNormalizeMode; - -gchar *g_utf8_normalize( const gchar *str, - gssize len, - GNormalizeMode mode ); - -gint g_utf8_collate( const gchar *str1, - const gchar *str2 ); -gchar *g_utf8_collate_key( const gchar *str, - gssize len ); - -gboolean g_unichar_get_mirror_char( gunichar ch, - gunichar *mirrored_ch ); - -G_END_DECLS - -#endif /* __G_UNICODE_H__ */ diff --git a/tools/urt/tools/quake3/common/glib/gutils.h b/tools/urt/tools/quake3/common/glib/gutils.h deleted file mode 100644 index e43c082..0000000 --- a/tools/urt/tools/quake3/common/glib/gutils.h +++ /dev/null @@ -1,366 +0,0 @@ -/* GLIB - Library of useful routines for C programming - * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the - * Free Software Foundation, Inc., 59 Temple Place - Suite 330, - * Boston, MA 02111-1307, USA. - */ - -/* - * Modified by the GLib Team and others 1997-2000. See the AUTHORS - * file for a list of people on the GLib Team. See the ChangeLog - * files for a list of changes. These files are distributed with - * GLib at ftp://ftp.gtk.org/pub/gtk/. - */ - -#ifndef __G_UTILS_H__ -#define __G_UTILS_H__ - -#include -#include - -G_BEGIN_DECLS - -#ifdef G_OS_WIN32 - -/* On native Win32, directory separator is the backslash, and search path - * separator is the semicolon. - */ -#define G_DIR_SEPARATOR '\\' -#define G_DIR_SEPARATOR_S "\\" -#define G_SEARCHPATH_SEPARATOR ';' -#define G_SEARCHPATH_SEPARATOR_S ";" - -#else /* !G_OS_WIN32 */ - -/* Unix */ - -#define G_DIR_SEPARATOR '/' -#define G_DIR_SEPARATOR_S "/" -#define G_SEARCHPATH_SEPARATOR ':' -#define G_SEARCHPATH_SEPARATOR_S ":" - -#endif /* !G_OS_WIN32 */ - -/* Define G_VA_COPY() to do the right thing for copying va_list variables. - * glibconfig.h may have already defined G_VA_COPY as va_copy or __va_copy. - */ -#if !defined ( G_VA_COPY ) -# if defined ( __GNUC__ ) && defined ( __PPC__ ) && ( defined ( _CALL_SYSV ) || defined ( _WIN32 ) ) -# define G_VA_COPY( ap1, ap2 ) ( *( ap1 ) = *( ap2 ) ) -# elif defined ( G_VA_COPY_AS_ARRAY ) -# define G_VA_COPY( ap1, ap2 ) g_memmove( ( ap1 ), ( ap2 ), sizeof( va_list ) ) -# else /* va_list is a pointer */ -# define G_VA_COPY( ap1, ap2 ) ( ( ap1 ) = ( ap2 ) ) -# endif /* va_list is a pointer */ -#endif /* !G_VA_COPY */ - -/* inlining hassle. for compilers that don't allow the `inline' keyword, - * mostly because of strict ANSI C compliance or dumbness, we try to fall - * back to either `__inline__' or `__inline'. - * we define G_CAN_INLINE, if the compiler seems to be actually - * *capable* to do function inlining, in which case inline function bodys - * do make sense. we also define G_INLINE_FUNC to properly export the - * function prototypes if no inlining can be performed. - * inline function bodies have to be special cased with G_CAN_INLINE and a - * .c file specific macro to allow one compiled instance with extern linkage - * of the functions by defining G_IMPLEMENT_INLINES and the .c file macro. - */ -#ifdef G_IMPLEMENT_INLINES -# define G_INLINE_FUNC extern -# undef G_CAN_INLINE -#endif -#ifndef G_INLINE_FUNC -# define G_CAN_INLINE 1 -#endif -#if defined ( G_HAVE_INLINE ) && defined ( __GNUC__ ) && defined ( __STRICT_ANSI__ ) -# undef inline -# define inline __inline__ -#elif !defined ( G_HAVE_INLINE ) -# undef inline -# if defined ( G_HAVE___INLINE__ ) -# define inline __inline__ -# elif defined ( G_HAVE___INLINE ) -# define inline __inline -# else /* !inline && !__inline__ && !__inline */ -# define inline /* don't inline, then */ -# ifndef G_INLINE_FUNC -# undef G_CAN_INLINE -# endif -# endif -#endif -#ifndef G_INLINE_FUNC -# if defined ( __GNUC__ ) && defined ( __OPTIMIZE__ ) -# define G_INLINE_FUNC extern inline -# elif defined ( G_CAN_INLINE ) && !defined ( __GNUC__ ) -# define G_INLINE_FUNC static inline -# else /* can't inline */ -# define G_INLINE_FUNC extern -# undef G_CAN_INLINE -# endif -#endif /* !G_INLINE_FUNC */ - -/* Retrive static string info - */ -G_CONST_RETURN gchar* g_get_user_name( void ); -G_CONST_RETURN gchar* g_get_real_name( void ); -G_CONST_RETURN gchar* g_get_home_dir( void ); -G_CONST_RETURN gchar* g_get_tmp_dir( void ); -gchar* g_get_prgname( void ); -void g_set_prgname( const gchar *prgname ); -G_CONST_RETURN gchar* g_get_application_name( void ); -void g_set_application_name( const gchar *application_name ); - - -typedef struct _GDebugKey GDebugKey; -struct _GDebugKey -{ - gchar *key; - guint value; -}; - -/* Miscellaneous utility functions - */ -guint g_parse_debug_string( const gchar *string, - const GDebugKey *keys, - guint nkeys ); - -gint g_snprintf( gchar *string, - gulong n, - gchar const *format, - ... ) G_GNUC_PRINTF( 3, 4 ); -gint g_vsnprintf( gchar *string, - gulong n, - gchar const *format, - va_list args ); - -/* Check if a file name is an absolute path */ -gboolean g_path_is_absolute( const gchar *file_name ); - -/* In case of absolute paths, skip the root part */ -G_CONST_RETURN gchar* g_path_skip_root( const gchar *file_name ); - -#ifndef G_DISABLE_DEPRECATED - -/* These two functions are deprecated and will be removed in the next - * major release of GLib. Use g_path_get_dirname/g_path_get_basename - * instead. Whatch out! The string returned by g_path_get_basename - * must be g_freed, while the string returned by g_basename must not.*/ -G_CONST_RETURN gchar* g_basename( const gchar *file_name ); -#define g_dirname g_path_get_dirname - -#endif /* G_DISABLE_DEPRECATED */ - -/* The returned strings are newly allocated with g_malloc() */ -gchar* g_get_current_dir( void ); -gchar* g_path_get_basename( const gchar *file_name ); -gchar* g_path_get_dirname( const gchar *file_name ); - - -/* Set the pointer at the specified location to NULL */ -void g_nullify_pointer( gpointer *nullify_location ); - -/* return the environment string for the variable. The returned memory - * must not be freed. */ -G_CONST_RETURN gchar* g_getenv( const gchar *variable ); -gboolean g_setenv( const gchar *variable, - const gchar *value, - gboolean overwrite ); -void g_unsetenv( const gchar *variable ); - - -/* we try to provide a usefull equivalent for ATEXIT if it is - * not defined, but use is actually abandoned. people should - * use g_atexit() instead. - */ -typedef void ( *GVoidFunc )( void ); -#ifndef ATEXIT -# define ATEXIT( proc ) g_ATEXIT( proc ) -#else -# define G_NATIVE_ATEXIT -#endif /* ATEXIT */ -/* we use a GLib function as a replacement for ATEXIT, so - * the programmer is not required to check the return value - * (if there is any in the implementation) and doesn't encounter - * missing include files. - */ -void g_atexit( GVoidFunc func ); - -/* Look for an executable in PATH, following execvp() rules */ -gchar* g_find_program_in_path( const gchar *program ); - -/* Bit tests - */ -G_INLINE_FUNC gint g_bit_nth_lsf( gulong mask, - gint nth_bit ); -G_INLINE_FUNC gint g_bit_nth_msf( gulong mask, - gint nth_bit ); -G_INLINE_FUNC guint g_bit_storage( gulong number ); - -/* Trash Stacks - * elements need to be >= sizeof (gpointer) - */ -typedef struct _GTrashStack GTrashStack; -struct _GTrashStack -{ - GTrashStack *next; -}; - -G_INLINE_FUNC void g_trash_stack_push( GTrashStack **stack_p, - gpointer data_p ); -G_INLINE_FUNC gpointer g_trash_stack_pop( GTrashStack **stack_p ); -G_INLINE_FUNC gpointer g_trash_stack_peek( GTrashStack **stack_p ); -G_INLINE_FUNC guint g_trash_stack_height( GTrashStack **stack_p ); - -/* inline function implementations - */ -#if defined ( G_CAN_INLINE ) || defined ( __G_UTILS_C__ ) -G_INLINE_FUNC gint -g_bit_nth_lsf( gulong mask, - gint nth_bit ){ - do - { - nth_bit++; - if ( mask & ( 1UL << nth_bit ) ) { - return nth_bit; - } - } - while ( nth_bit < ( ( GLIB_SIZEOF_LONG * 8 ) - 1 ) ); - return -1; -} -G_INLINE_FUNC gint -g_bit_nth_msf( gulong mask, - gint nth_bit ){ - if ( nth_bit < 0 ) { - nth_bit = GLIB_SIZEOF_LONG * 8; - } - do - { - nth_bit--; - if ( mask & ( 1UL << nth_bit ) ) { - return nth_bit; - } - } - while ( nth_bit > 0 ); - return -1; -} -G_INLINE_FUNC guint -g_bit_storage( gulong number ){ - register guint n_bits = 0; - - do - { - n_bits++; - number >>= 1; - } - while ( number ); - return n_bits; -} -G_INLINE_FUNC void -g_trash_stack_push( GTrashStack **stack_p, - gpointer data_p ){ - GTrashStack *data = (GTrashStack *) data_p; - - data->next = *stack_p; - *stack_p = data; -} -G_INLINE_FUNC gpointer -g_trash_stack_pop( GTrashStack **stack_p ){ - GTrashStack *data; - - data = *stack_p; - if ( data ) { - *stack_p = data->next; - /* NULLify private pointer here, most platforms store NULL as - * subsequent 0 bytes - */ - data->next = NULL; - } - - return data; -} -G_INLINE_FUNC gpointer -g_trash_stack_peek( GTrashStack **stack_p ){ - GTrashStack *data; - - data = *stack_p; - - return data; -} -G_INLINE_FUNC guint -g_trash_stack_height( GTrashStack **stack_p ){ - GTrashStack *data; - guint i = 0; - - for ( data = *stack_p; data; data = data->next ) - i++; - - return i; -} -#endif /* G_CAN_INLINE || __G_UTILS_C__ */ - -/* Glib version. - * we prefix variable declarations so they can - * properly get exported in windows dlls. - */ -GLIB_VAR const guint glib_major_version; -GLIB_VAR const guint glib_minor_version; -GLIB_VAR const guint glib_micro_version; -GLIB_VAR const guint glib_interface_age; -GLIB_VAR const guint glib_binary_age; - -#define GLIB_CHECK_VERSION( major,minor,micro ) \ - ( GLIB_MAJOR_VERSION > ( major ) || \ - ( GLIB_MAJOR_VERSION == ( major ) && GLIB_MINOR_VERSION > ( minor ) ) || \ - ( GLIB_MAJOR_VERSION == ( major ) && GLIB_MINOR_VERSION == ( minor ) && \ - GLIB_MICRO_VERSION >= ( micro ) ) ) - -G_END_DECLS - -/* - * On Windows, this macro defines a DllMain function that stores the - * actual DLL name that the code being compiled will be included in. - * STATIC should be empty or 'static'. DLL_NAME is the name of the - * (pointer to the) char array where the DLL name will be stored. If - * this is used, you must also include . If you need a more complex - * DLL entry point function, you cannot use this. - * - * On non-Windows platforms, expands to nothing. - */ - -#ifndef G_PLATFORM_WIN32 -# define G_WIN32_DLLMAIN_FOR_DLL_NAME( static, dll_name ) -#else -# define G_WIN32_DLLMAIN_FOR_DLL_NAME( static, dll_name ) \ - static char *dll_name; \ - \ - BOOL WINAPI \ - DllMain( HINSTANCE hinstDLL, \ - DWORD fdwReason, \ - LPVOID lpvReserved ) \ - { \ - char bfr[1000]; \ - switch ( fdwReason ) \ - { \ - case DLL_PROCESS_ATTACH: \ - GetModuleFileName( (HMODULE) hinstDLL, bfr, sizeof( bfr ) ); \ - dll_name = g_path_get_basename( bfr ); \ - break; \ - } \ - \ - return TRUE; \ - } -#endif /* G_PLATFORM_WIN32 */ - -#endif /* __G_UTILS_H__ */ diff --git a/tools/urt/tools/quake3/common/glib/gwin32.h b/tools/urt/tools/quake3/common/glib/gwin32.h deleted file mode 100644 index ba521a0..0000000 --- a/tools/urt/tools/quake3/common/glib/gwin32.h +++ /dev/null @@ -1,100 +0,0 @@ -/* GLIB - Library of useful routines for C programming - * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the - * Free Software Foundation, Inc., 59 Temple Place - Suite 330, - * Boston, MA 02111-1307, USA. - */ - -/* - * Modified by the GLib Team and others 1997-2000. See the AUTHORS - * file for a list of people on the GLib Team. See the ChangeLog - * files for a list of changes. These files are distributed with - * GLib at ftp://ftp.gtk.org/pub/gtk/. - */ - -#ifndef __G_WIN32_H__ -#define __G_WIN32_H__ - -#include - -#ifdef G_PLATFORM_WIN32 - -/* Windows emulation stubs for common Unix functions - */ - -G_BEGIN_DECLS - -#ifndef MAXPATHLEN -#define MAXPATHLEN 1024 -#endif - -#ifdef _MSC_VER -typedef int pid_t; -#endif - -#ifdef G_OS_WIN32 - -/* - * To get prototypes for the following POSIXish functions, you have to - * include the indicated non-POSIX headers. The functions are defined - * in OLDNAMES.LIB (MSVC) or -lmoldname-msvc (mingw32). - * - * getcwd: (MSVC), (mingw32) - * getpid: - * access: - * unlink: or - * open, read, write, lseek, close: - * rmdir: - * pipe: - */ - -/* pipe is not in OLDNAMES.LIB or -lmoldname-msvc. */ -#define pipe( phandles ) _pipe( phandles, 4096, _O_BINARY ) - -/* For some POSIX functions that are not provided by the MS runtime, - * we provide emulators in glib, which are prefixed with g_win32_. - */ -# define ftruncate( fd, size ) g_win32_ftruncate( fd, size ) - -gint g_win32_ftruncate( gint f, - guint size ); -#endif /* G_OS_WIN32 */ - -/* The MS setlocale uses locale names of the form "English_United - * States.1252" etc. We want the Unixish standard form "en", "zh_TW" - * etc. This function gets the current thread locale from Windows and - * returns it as a string of the above form for use in forming file - * names etc. The returned string should be deallocated with g_free(). - */ -gchar* g_win32_getlocale( void ); - -/* Translate a Win32 error code (as returned by GetLastError()) into - * the corresponding message. The returned string should be deallocated - * with g_free(). - */ -gchar* g_win32_error_message( gint error ); - -gchar* g_win32_get_package_installation_directory( gchar *package, - gchar *dll_name ); - -gchar* g_win32_get_package_installation_subdirectory( gchar *package, - gchar *dll_name, - gchar *subdir ); - -G_END_DECLS - -#endif /* G_PLATFORM_WIN32 */ - -#endif /* __G_WIN32_H__ */ diff --git a/tools/urt/tools/quake3/common/glibconfig.h b/tools/urt/tools/quake3/common/glibconfig.h deleted file mode 100644 index 76a9fb5..0000000 --- a/tools/urt/tools/quake3/common/glibconfig.h +++ /dev/null @@ -1,188 +0,0 @@ -/* glibconfig.h.win32.in Merged from two versions generated by configure for gcc and MSVC. */ -/* glibconfig.h - * - * This is a generated file. Please modify 'configure.in' - */ - -#ifndef __G_LIBCONFIG_H__ -#define __G_LIBCONFIG_H__ - -#include - -#include -#include - -G_BEGIN_DECLS - -#define G_MINFLOAT FLT_MIN -#define G_MAXFLOAT FLT_MAX -#define G_MINDOUBLE DBL_MIN -#define G_MAXDOUBLE DBL_MAX -#define G_MINSHORT SHRT_MIN -#define G_MAXSHORT SHRT_MAX -#define G_MAXUSHORT USHRT_MAX -#define G_MININT INT_MIN -#define G_MAXINT INT_MAX -#define G_MAXUINT UINT_MAX -#define G_MINLONG LONG_MIN -#define G_MAXLONG LONG_MAX -#define G_MAXULONG ULONG_MAX - -typedef signed char gint8; -typedef unsigned char guint8; -typedef signed short gint16; -typedef unsigned short guint16; -#define G_GINT16_MODIFIER "h" -#define G_GINT16_FORMAT "hi" -#define G_GUINT16_FORMAT "hu" -typedef signed int gint32; -typedef unsigned int guint32; -#define G_GINT32_MODIFIER "" -#define G_GINT32_FORMAT "i" -#define G_GUINT32_FORMAT "u" -#define G_HAVE_GINT64 1 /* deprecated, always true */ - -#ifndef _MSC_VER -G_GNUC_EXTENSION typedef signed long long gint64; -G_GNUC_EXTENSION typedef unsigned long long guint64; -#else /* _MSC_VER */ -typedef signed __int64 gint64; -typedef unsigned __int64 guint64; -#endif /* _MSC_VER */ - -#ifndef _MSC_VER -#define G_GINT64_CONSTANT( val ) ( G_GNUC_EXTENSION( val ## LL ) ) -#else /* _MSC_VER */ -#define G_GINT64_CONSTANT( val ) ( val ## i64 ) -#endif /* _MSC_VER */ -#define G_GINT64_MODIFIER "I64" -#define G_GINT64_FORMAT "I64i" -#define G_GUINT64_FORMAT "I64u" - -#define GLIB_SIZEOF_VOID_P 4 -#define GLIB_SIZEOF_LONG 4 -#define GLIB_SIZEOF_SIZE_T 4 - -typedef signed int gssize; -typedef unsigned int gsize; -#define G_GSIZE_MODIFIER "" -#define G_GSSIZE_FORMAT "i" -#define G_GSIZE_FORMAT "u" - -#define G_MAXSIZE G_MAXUINT - -#define GPOINTER_TO_INT( p ) ( (gint) ( p ) ) -#define GPOINTER_TO_UINT( p ) ( (guint) ( p ) ) - -#define GINT_TO_POINTER( i ) ( (gpointer) ( i ) ) -#define GUINT_TO_POINTER( u ) ( (gpointer) ( u ) ) - -#ifdef NeXT /* @#%@! NeXTStep */ -# define g_ATEXIT( proc ) ( !atexit( proc ) ) -#else -# define g_ATEXIT( proc ) ( atexit( proc ) ) -#endif - -#define g_memmove( d,s,n ) G_STMT_START { memmove( ( d ), ( s ), ( n ) ); } G_STMT_END - -#define GLIB_MAJOR_VERSION 2 -#define GLIB_MINOR_VERSION 4 -#define GLIB_MICRO_VERSION 5 - -#define G_OS_WIN32 -#define G_PLATFORM_WIN32 - -#ifndef _MSC_VER -#define G_VA_COPY va_copy -#endif /* not _MSC_VER */ - -#ifdef __cplusplus -#define G_HAVE_INLINE 1 -#else /* !__cplusplus */ -#ifndef _MSC_VER -#define G_HAVE_INLINE 1 -#else /* _MSC_VER */ - -#endif /* _MSC_VER */ -#define G_HAVE___INLINE 1 -#ifndef _MSC_VER -#define G_HAVE___INLINE__ 1 -#endif /* not _MSC_VER */ -#endif /* !__cplusplus */ - -#ifndef _MSC_VER -#ifndef __cplusplus -# define G_HAVE_ISO_VARARGS 1 -#endif -#ifdef __cplusplus -# define G_HAVE_ISO_VARARGS 1 -#endif - -/* gcc-2.95.x supports both gnu style and ISO varargs, but if -ansi - * is passed ISO vararg support is turned off, and there is no work - * around to turn it on, so we unconditionally turn it off. - */ -#if __GNUC__ == 2 && __GNUC_MINOR__ == 95 -# undef G_HAVE_ISO_VARARGS -#endif - -#define G_HAVE_GNUC_VARARGS 1 -#endif /* not _MSC_VER */ -#define G_HAVE_GROWING_STACK 0 - - -#define G_THREADS_ENABLED -#define G_THREADS_IMPL_WIN32 -typedef struct _GMutex* GStaticMutex; -#define G_STATIC_MUTEX_INIT NULL -#define g_static_mutex_get_mutex( mutex ) \ - ( g_static_mutex_get_mutex_impl_shortcut( mutex ) ) -/* This represents a system thread as used by the implementation. An - * alien implementaion, as loaded by g_thread_init can only count on - * "sizeof (gpointer)" bytes to store their info. We however need more - * for some of our native implementations. */ -typedef union _GSystemThread GSystemThread; -union _GSystemThread -{ - char data[4]; - double dummy_double; - void *dummy_pointer; - long dummy_long; -}; - -#define GINT16_TO_LE( val ) ( (gint16) ( val ) ) -#define GUINT16_TO_LE( val ) ( (guint16) ( val ) ) -#define GINT16_TO_BE( val ) ( (gint16) GUINT16_SWAP_LE_BE( val ) ) -#define GUINT16_TO_BE( val ) ( GUINT16_SWAP_LE_BE( val ) ) -#define GINT32_TO_LE( val ) ( (gint32) ( val ) ) -#define GUINT32_TO_LE( val ) ( (guint32) ( val ) ) -#define GINT32_TO_BE( val ) ( (gint32) GUINT32_SWAP_LE_BE( val ) ) -#define GUINT32_TO_BE( val ) ( GUINT32_SWAP_LE_BE( val ) ) -#define GINT64_TO_LE( val ) ( (gint64) ( val ) ) -#define GUINT64_TO_LE( val ) ( (guint64) ( val ) ) -#define GINT64_TO_BE( val ) ( (gint64) GUINT64_SWAP_LE_BE( val ) ) -#define GUINT64_TO_BE( val ) ( GUINT64_SWAP_LE_BE( val ) ) -#define GLONG_TO_LE( val ) ( (glong) GINT32_TO_LE( val ) ) -#define GULONG_TO_LE( val ) ( (gulong) GUINT32_TO_LE( val ) ) -#define GLONG_TO_BE( val ) ( (glong) GINT32_TO_BE( val ) ) -#define GULONG_TO_BE( val ) ( (gulong) GUINT32_TO_BE( val ) ) -#define GINT_TO_LE( val ) ( (gint) GINT32_TO_LE( val ) ) -#define GUINT_TO_LE( val ) ( (guint) GUINT32_TO_LE( val ) ) -#define GINT_TO_BE( val ) ( (gint) GINT32_TO_BE( val ) ) -#define GUINT_TO_BE( val ) ( (guint) GUINT32_TO_BE( val ) ) -#define G_BYTE_ORDER G_LITTLE_ENDIAN - -#define GLIB_SYSDEF_POLLIN = 1 -#define GLIB_SYSDEF_POLLOUT = 4 -#define GLIB_SYSDEF_POLLPRI = 2 -#define GLIB_SYSDEF_POLLHUP = 16 -#define GLIB_SYSDEF_POLLERR = 8 -#define GLIB_SYSDEF_POLLNVAL = 32 - -#define G_MODULE_SUFFIX "dll" - -typedef void * GPid; - -G_END_DECLS - -#endif /* GLIBCONFIG_H */ diff --git a/tools/urt/tools/quake3/common/gmodule.h b/tools/urt/tools/quake3/common/gmodule.h deleted file mode 100644 index 77bdc40..0000000 --- a/tools/urt/tools/quake3/common/gmodule.h +++ /dev/null @@ -1,96 +0,0 @@ -/* GMODULE - GLIB wrapper code for dynamic module loading - * Copyright (C) 1998 Tim Janik - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the - * Free Software Foundation, Inc., 59 Temple Place - Suite 330, - * Boston, MA 02111-1307, USA. - */ - -/* - * Modified by the GLib Team and others 1997-2000. See the AUTHORS - * file for a list of people on the GLib Team. See the ChangeLog - * files for a list of changes. These files are distributed with - * GLib at ftp://ftp.gtk.org/pub/gtk/. - */ - -#ifndef __GMODULE_H__ -#define __GMODULE_H__ - -#include - -G_BEGIN_DECLS - -/* exporting and importing functions, this is special cased - * to feature Windows dll stubs. - */ -#define G_MODULE_IMPORT extern -#ifdef G_PLATFORM_WIN32 -# define G_MODULE_EXPORT __declspec( dllexport ) -#else /* !G_PLATFORM_WIN32 */ -# define G_MODULE_EXPORT -#endif /* !G_PLATFORM_WIN32 */ - -typedef enum -{ - G_MODULE_BIND_LAZY = 1 << 0, - G_MODULE_BIND_LOCAL = 1 << 1, - G_MODULE_BIND_MASK = 0x03 -} GModuleFlags; - -typedef struct _GModule GModule; -typedef const gchar* ( *GModuleCheckInit )( GModule *module ); -typedef void ( *GModuleUnload )( GModule *module ); - -/* return TRUE if dynamic module loading is supported */ -gboolean g_module_supported( void ) G_GNUC_CONST; - -/* open a module `file_name' and return handle, which is NULL on error */ -GModule* g_module_open( const gchar *file_name, - GModuleFlags flags ); - -/* close a previously opened module, returns TRUE on success */ -gboolean g_module_close( GModule *module ); - -/* make a module resident so g_module_close on it will be ignored */ -void g_module_make_resident( GModule *module ); - -/* query the last module error as a string */ -G_CONST_RETURN gchar* g_module_error( void ); - -/* retrieve a symbol pointer from `module', returns TRUE on success */ -gboolean g_module_symbol( GModule *module, - const gchar *symbol_name, - gpointer *symbol ); - -/* retrieve the file name from an existing module */ -G_CONST_RETURN gchar* g_module_name( GModule *module ); - -/* Build the actual file name containing a module. `directory' is the - * directory where the module file is supposed to be, or NULL or empty - * in which case it should either be in the current directory or, on - * some operating systems, in some standard place, for instance on the - * PATH. Hence, to be absoultely sure to get the correct module, - * always pass in a directory. The file name consists of the directory, - * if supplied, and `module_name' suitably decorated accoring to - * the operating system's conventions (for instance lib*.so or *.dll). - * - * No checks are made that the file exists, or is of correct type. - */ -gchar* g_module_build_path( const gchar *directory, - const gchar *module_name ); - - -G_END_DECLS - -#endif /* __GMODULE_H__ */ diff --git a/tools/urt/tools/quake3/common/gobject/gboxed.h b/tools/urt/tools/quake3/common/gobject/gboxed.h deleted file mode 100644 index 1c99488..0000000 --- a/tools/urt/tools/quake3/common/gobject/gboxed.h +++ /dev/null @@ -1,83 +0,0 @@ -/* GObject - GLib Type, Object, Parameter and Signal Library - * Copyright (C) 2000-2001 Red Hat, Inc. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General - * Public License along with this library; if not, write to the - * Free Software Foundation, Inc., 59 Temple Place, Suite 330, - * Boston, MA 02111-1307, USA. - */ -#if !defined ( __GLIB_GOBJECT_H_INSIDE__ ) && !defined ( GOBJECT_COMPILATION ) -#error "Only can be included directly." -#endif - -#ifndef __G_BOXED_H__ -#define __G_BOXED_H__ - -#include - -G_BEGIN_DECLS - -/* --- type macros --- */ -#define G_TYPE_IS_BOXED( type ) ( G_TYPE_FUNDAMENTAL( type ) == G_TYPE_BOXED ) -#define G_VALUE_HOLDS_BOXED( value ) ( G_TYPE_CHECK_VALUE_TYPE( ( value ), G_TYPE_BOXED ) ) - - -/* --- typedefs --- */ -typedef gpointer ( *GBoxedCopyFunc )( gpointer boxed ); -typedef void ( *GBoxedFreeFunc )( gpointer boxed ); - - -/* --- prototypes --- */ -gpointer g_boxed_copy( GType boxed_type, - gconstpointer src_boxed ); -void g_boxed_free( GType boxed_type, - gpointer boxed ); -void g_value_set_boxed( GValue *value, - gconstpointer v_boxed ); -void g_value_set_static_boxed( GValue *value, - gconstpointer v_boxed ); -gpointer g_value_get_boxed( const GValue *value ); -gpointer g_value_dup_boxed( const GValue *value ); - - -/* --- convenience --- */ -GType g_boxed_type_register_static( const gchar *name, - GBoxedCopyFunc boxed_copy, - GBoxedFreeFunc boxed_free ); - - -/* --- GLib boxed types --- */ -#define G_TYPE_CLOSURE ( g_closure_get_type() ) -#define G_TYPE_VALUE ( g_value_get_type() ) -#define G_TYPE_VALUE_ARRAY ( g_value_array_get_type() ) -#define G_TYPE_STRV ( g_strv_get_type() ) -#define G_TYPE_GSTRING ( g_gstring_get_type() ) - - -void g_value_take_boxed( GValue *value, - gconstpointer v_boxed ); -#ifndef G_DISABLE_DEPRECATED -void g_value_set_boxed_take_ownership( GValue *value, - gconstpointer v_boxed ); -#endif -GType g_closure_get_type( void ) G_GNUC_CONST; -GType g_value_get_type( void ) G_GNUC_CONST; -GType g_value_array_get_type( void ) G_GNUC_CONST; -GType g_strv_get_type( void ) G_GNUC_CONST; -GType g_gstring_get_type( void ) G_GNUC_CONST; - -typedef gchar** GStrv; - -G_END_DECLS - -#endif /* __G_BOXED_H__ */ diff --git a/tools/urt/tools/quake3/common/gobject/gclosure.h b/tools/urt/tools/quake3/common/gobject/gclosure.h deleted file mode 100644 index 7d29f9e..0000000 --- a/tools/urt/tools/quake3/common/gobject/gclosure.h +++ /dev/null @@ -1,162 +0,0 @@ -/* GObject - GLib Type, Object, Parameter and Signal Library - * Copyright (C) 2000-2001 Red Hat, Inc. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General - * Public License along with this library; if not, write to the - * Free Software Foundation, Inc., 59 Temple Place, Suite 330, - * Boston, MA 02111-1307, USA. - */ -#if !defined ( __GLIB_GOBJECT_H_INSIDE__ ) && !defined ( GOBJECT_COMPILATION ) -#error "Only can be included directly." -#endif - -#ifndef __G_CLOSURE_H__ -#define __G_CLOSURE_H__ - -#include - -G_BEGIN_DECLS - -/* --- defines --- */ -#define G_CLOSURE_NEEDS_MARSHAL( closure ) ( ( (GClosure*) ( closure ) )->marshal == NULL ) -#define G_CLOSURE_N_NOTIFIERS( cl ) ( ( cl )->meta_marshal + ( ( cl )->n_guards << 1L ) + \ - ( cl )->n_fnotifiers + ( cl )->n_inotifiers ) -#define G_CCLOSURE_SWAP_DATA( cclosure ) ( ( (GClosure*) ( closure ) )->derivative_flag ) -#define G_CALLBACK( f ) ( (GCallback) ( f ) ) - - -/* -- typedefs --- */ -typedef struct _GClosure GClosure; -typedef struct _GClosureNotifyData GClosureNotifyData; -typedef void ( *GCallback )( void ); -typedef void ( *GClosureNotify )( gpointer data, - GClosure *closure ); -typedef void ( *GClosureMarshal )( GClosure *closure, - GValue *return_value, - guint n_param_values, - const GValue *param_values, - gpointer invocation_hint, - gpointer marshal_data ); -typedef struct _GCClosure GCClosure; - - -/* --- structures --- */ -struct _GClosureNotifyData -{ - gpointer data; - GClosureNotify notify; -}; -struct _GClosure -{ - /*< private >*/ guint ref_count : 15; - /*< private >*/ guint meta_marshal : 1; - /*< private >*/ guint n_guards : 1; - /*< private >*/ guint n_fnotifiers : 2; /* finalization notifiers */ - /*< private >*/ guint n_inotifiers : 8; /* invalidation notifiers */ - /*< private >*/ guint in_inotify : 1; - /*< private >*/ guint floating : 1; - /*< protected >*/ guint derivative_flag : 1; - /*< public >*/ guint in_marshal : 1; - /*< public >*/ guint is_invalid : 1; - - /*< private >*/ void ( *marshal )( GClosure *closure, - GValue /*out*/ *return_value, - guint n_param_values, - const GValue *param_values, - gpointer invocation_hint, - gpointer marshal_data ); - /*< protected >*/ gpointer data; - - /*< private >*/ GClosureNotifyData *notifiers; - - /* invariants/constrains: - * - ->marshal and ->data are _invalid_ as soon as ->is_invalid==TRUE - * - invocation of all inotifiers occours prior to fnotifiers - * - order of inotifiers is random - * inotifiers may _not_ free/invalidate parameter values (e.g. ->data) - * - order of fnotifiers is random - * - each notifier may only be removed before or during its invocation - * - reference counting may only happen prior to fnotify invocation - * (in that sense, fnotifiers are really finalization handlers) - */ -}; -/* closure for C function calls, callback() is the user function - */ -struct _GCClosure -{ - GClosure closure; - gpointer callback; -}; - - -/* --- prototypes --- */ -GClosure* g_cclosure_new( GCallback callback_func, - gpointer user_data, - GClosureNotify destroy_data ); -GClosure* g_cclosure_new_swap( GCallback callback_func, - gpointer user_data, - GClosureNotify destroy_data ); -GClosure* g_signal_type_cclosure_new( GType itype, - guint struct_offset ); - - -/* --- prototypes --- */ -GClosure* g_closure_ref( GClosure *closure ); -void g_closure_sink( GClosure *closure ); -void g_closure_unref( GClosure *closure ); -/* intimidating */ -GClosure* g_closure_new_simple( guint sizeof_closure, - gpointer data ); -void g_closure_add_finalize_notifier( GClosure *closure, - gpointer notify_data, - GClosureNotify notify_func ); -void g_closure_remove_finalize_notifier( GClosure *closure, - gpointer notify_data, - GClosureNotify notify_func ); -void g_closure_add_invalidate_notifier( GClosure *closure, - gpointer notify_data, - GClosureNotify notify_func ); -void g_closure_remove_invalidate_notifier( GClosure *closure, - gpointer notify_data, - GClosureNotify notify_func ); -void g_closure_add_marshal_guards( GClosure *closure, - gpointer pre_marshal_data, - GClosureNotify pre_marshal_notify, - gpointer post_marshal_data, - GClosureNotify post_marshal_notify ); -void g_closure_set_marshal( GClosure *closure, - GClosureMarshal marshal ); -void g_closure_set_meta_marshal( GClosure *closure, - gpointer marshal_data, - GClosureMarshal meta_marshal ); -void g_closure_invalidate( GClosure *closure ); -void g_closure_invoke( GClosure *closure, - GValue /*out*/ *return_value, - guint n_param_values, - const GValue *param_values, - gpointer invocation_hint ); - -/* FIXME: - OK: data_object::destroy -> closure_invalidate(); - MIS: closure_invalidate() -> disconnect(closure); - MIS: disconnect(closure) -> (unlink) closure_unref(); - OK: closure_finalize() -> g_free (data_string); - - random remarks: - - need marshaller repo with decent aliasing to base types - - provide marshaller collection, virtually covering anything out there - */ - -G_END_DECLS - -#endif /* __G_CLOSURE_H__ */ diff --git a/tools/urt/tools/quake3/common/gobject/genums.h b/tools/urt/tools/quake3/common/gobject/genums.h deleted file mode 100644 index 0596ca5..0000000 --- a/tools/urt/tools/quake3/common/gobject/genums.h +++ /dev/null @@ -1,125 +0,0 @@ -/* GObject - GLib Type, Object, Parameter and Signal Library - * Copyright (C) 1998-1999, 2000-2001 Tim Janik and Red Hat, Inc. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General - * Public License along with this library; if not, write to the - * Free Software Foundation, Inc., 59 Temple Place, Suite 330, - * Boston, MA 02111-1307, USA. - */ -#if !defined ( __GLIB_GOBJECT_H_INSIDE__ ) && !defined ( GOBJECT_COMPILATION ) -#error "Only can be included directly." -#endif - -#ifndef __G_ENUMS_H__ -#define __G_ENUMS_H__ - -#include - -G_BEGIN_DECLS - -/* --- type macros --- */ -#define G_TYPE_IS_ENUM( type ) ( G_TYPE_FUNDAMENTAL( type ) == G_TYPE_ENUM ) -#define G_ENUM_CLASS( class ) ( G_TYPE_CHECK_CLASS_CAST( ( class ), G_TYPE_ENUM, GEnumClass ) ) -#define G_IS_ENUM_CLASS( class ) ( G_TYPE_CHECK_CLASS_TYPE( ( class ), G_TYPE_ENUM ) ) -#define G_ENUM_CLASS_TYPE( class ) ( G_TYPE_FROM_CLASS( class ) ) -#define G_ENUM_CLASS_TYPE_NAME( class ) ( g_type_name( G_ENUM_CLASS_TYPE( class ) ) ) -#define G_TYPE_IS_FLAGS( type ) ( G_TYPE_FUNDAMENTAL( type ) == G_TYPE_FLAGS ) -#define G_FLAGS_CLASS( class ) ( G_TYPE_CHECK_CLASS_CAST( ( class ), G_TYPE_FLAGS, GFlagsClass ) ) -#define G_IS_FLAGS_CLASS( class ) ( G_TYPE_CHECK_CLASS_TYPE( ( class ), G_TYPE_FLAGS ) ) -#define G_FLAGS_CLASS_TYPE( class ) ( G_TYPE_FROM_CLASS( class ) ) -#define G_FLAGS_CLASS_TYPE_NAME( class ) ( g_type_name( G_FLAGS_TYPE( class ) ) ) -#define G_VALUE_HOLDS_ENUM( value ) ( G_TYPE_CHECK_VALUE_TYPE( ( value ), G_TYPE_ENUM ) ) -#define G_VALUE_HOLDS_FLAGS( value ) ( G_TYPE_CHECK_VALUE_TYPE( ( value ), G_TYPE_FLAGS ) ) - - -/* --- enum/flag values & classes --- */ -typedef struct _GEnumClass GEnumClass; -typedef struct _GFlagsClass GFlagsClass; -typedef struct _GEnumValue GEnumValue; -typedef struct _GFlagsValue GFlagsValue; -struct _GEnumClass -{ - GTypeClass g_type_class; - - /*< public >*/ - gint minimum; - gint maximum; - guint n_values; - GEnumValue *values; -}; -struct _GFlagsClass -{ - GTypeClass g_type_class; - - /*< public >*/ - guint mask; - guint n_values; - GFlagsValue *values; -}; -struct _GEnumValue -{ - gint value; - gchar *value_name; - gchar *value_nick; -}; -struct _GFlagsValue -{ - guint value; - gchar *value_name; - gchar *value_nick; -}; - - -/* --- prototypes --- */ -GEnumValue* g_enum_get_value( GEnumClass *enum_class, - gint value ); -GEnumValue* g_enum_get_value_by_name( GEnumClass *enum_class, - const gchar *name ); -GEnumValue* g_enum_get_value_by_nick( GEnumClass *enum_class, - const gchar *nick ); -GFlagsValue* g_flags_get_first_value( GFlagsClass *flags_class, - guint value ); -GFlagsValue* g_flags_get_value_by_name( GFlagsClass *flags_class, - const gchar *name ); -GFlagsValue* g_flags_get_value_by_nick( GFlagsClass *flags_class, - const gchar *nick ); -void g_value_set_enum( GValue *value, - gint v_enum ); -gint g_value_get_enum( const GValue *value ); -void g_value_set_flags( GValue *value, - guint v_flags ); -guint g_value_get_flags( const GValue *value ); - - - -/* --- registration functions --- */ -/* const_static_values is a NULL terminated array of enum/flags - * values that is taken over! - */ -GType g_enum_register_static( const gchar *name, - const GEnumValue *const_static_values ); -GType g_flags_register_static( const gchar *name, - const GFlagsValue *const_static_values ); -/* functions to complete the type information - * for enums/flags implemented by plugins - */ -void g_enum_complete_type_info( GType g_enum_type, - GTypeInfo *info, - const GEnumValue *const_values ); -void g_flags_complete_type_info( GType g_flags_type, - GTypeInfo *info, - const GFlagsValue *const_values ); - -G_END_DECLS - -#endif /* __G_ENUMS_H__ */ diff --git a/tools/urt/tools/quake3/common/gobject/gmarshal.h b/tools/urt/tools/quake3/common/gobject/gmarshal.h deleted file mode 100644 index c2d173b..0000000 --- a/tools/urt/tools/quake3/common/gobject/gmarshal.h +++ /dev/null @@ -1,169 +0,0 @@ -#ifndef __G_MARSHAL_H__ -#define __G_MARSHAL_H__ - -G_BEGIN_DECLS - -/* VOID:VOID (./gmarshal.list:26) */ -extern void g_cclosure_marshal_VOID__VOID( GClosure *closure, - GValue *return_value, - guint n_param_values, - const GValue *param_values, - gpointer invocation_hint, - gpointer marshal_data ); - -/* VOID:BOOLEAN (./gmarshal.list:27) */ -extern void g_cclosure_marshal_VOID__BOOLEAN( GClosure *closure, - GValue *return_value, - guint n_param_values, - const GValue *param_values, - gpointer invocation_hint, - gpointer marshal_data ); - -/* VOID:CHAR (./gmarshal.list:28) */ -extern void g_cclosure_marshal_VOID__CHAR( GClosure *closure, - GValue *return_value, - guint n_param_values, - const GValue *param_values, - gpointer invocation_hint, - gpointer marshal_data ); - -/* VOID:UCHAR (./gmarshal.list:29) */ -extern void g_cclosure_marshal_VOID__UCHAR( GClosure *closure, - GValue *return_value, - guint n_param_values, - const GValue *param_values, - gpointer invocation_hint, - gpointer marshal_data ); - -/* VOID:INT (./gmarshal.list:30) */ -extern void g_cclosure_marshal_VOID__INT( GClosure *closure, - GValue *return_value, - guint n_param_values, - const GValue *param_values, - gpointer invocation_hint, - gpointer marshal_data ); - -/* VOID:UINT (./gmarshal.list:31) */ -extern void g_cclosure_marshal_VOID__UINT( GClosure *closure, - GValue *return_value, - guint n_param_values, - const GValue *param_values, - gpointer invocation_hint, - gpointer marshal_data ); - -/* VOID:LONG (./gmarshal.list:32) */ -extern void g_cclosure_marshal_VOID__LONG( GClosure *closure, - GValue *return_value, - guint n_param_values, - const GValue *param_values, - gpointer invocation_hint, - gpointer marshal_data ); - -/* VOID:ULONG (./gmarshal.list:33) */ -extern void g_cclosure_marshal_VOID__ULONG( GClosure *closure, - GValue *return_value, - guint n_param_values, - const GValue *param_values, - gpointer invocation_hint, - gpointer marshal_data ); - -/* VOID:ENUM (./gmarshal.list:34) */ -extern void g_cclosure_marshal_VOID__ENUM( GClosure *closure, - GValue *return_value, - guint n_param_values, - const GValue *param_values, - gpointer invocation_hint, - gpointer marshal_data ); - -/* VOID:FLAGS (./gmarshal.list:35) */ -extern void g_cclosure_marshal_VOID__FLAGS( GClosure *closure, - GValue *return_value, - guint n_param_values, - const GValue *param_values, - gpointer invocation_hint, - gpointer marshal_data ); - -/* VOID:FLOAT (./gmarshal.list:36) */ -extern void g_cclosure_marshal_VOID__FLOAT( GClosure *closure, - GValue *return_value, - guint n_param_values, - const GValue *param_values, - gpointer invocation_hint, - gpointer marshal_data ); - -/* VOID:DOUBLE (./gmarshal.list:37) */ -extern void g_cclosure_marshal_VOID__DOUBLE( GClosure *closure, - GValue *return_value, - guint n_param_values, - const GValue *param_values, - gpointer invocation_hint, - gpointer marshal_data ); - -/* VOID:STRING (./gmarshal.list:38) */ -extern void g_cclosure_marshal_VOID__STRING( GClosure *closure, - GValue *return_value, - guint n_param_values, - const GValue *param_values, - gpointer invocation_hint, - gpointer marshal_data ); - -/* VOID:PARAM (./gmarshal.list:39) */ -extern void g_cclosure_marshal_VOID__PARAM( GClosure *closure, - GValue *return_value, - guint n_param_values, - const GValue *param_values, - gpointer invocation_hint, - gpointer marshal_data ); - -/* VOID:BOXED (./gmarshal.list:40) */ -extern void g_cclosure_marshal_VOID__BOXED( GClosure *closure, - GValue *return_value, - guint n_param_values, - const GValue *param_values, - gpointer invocation_hint, - gpointer marshal_data ); - -/* VOID:POINTER (./gmarshal.list:41) */ -extern void g_cclosure_marshal_VOID__POINTER( GClosure *closure, - GValue *return_value, - guint n_param_values, - const GValue *param_values, - gpointer invocation_hint, - gpointer marshal_data ); - -/* VOID:OBJECT (./gmarshal.list:42) */ -extern void g_cclosure_marshal_VOID__OBJECT( GClosure *closure, - GValue *return_value, - guint n_param_values, - const GValue *param_values, - gpointer invocation_hint, - gpointer marshal_data ); - -/* VOID:UINT,POINTER (./gmarshal.list:45) */ -extern void g_cclosure_marshal_VOID__UINT_POINTER( GClosure *closure, - GValue *return_value, - guint n_param_values, - const GValue *param_values, - gpointer invocation_hint, - gpointer marshal_data ); - -/* BOOL:FLAGS (./gmarshal.list:46) */ -extern void g_cclosure_marshal_BOOLEAN__FLAGS( GClosure *closure, - GValue *return_value, - guint n_param_values, - const GValue *param_values, - gpointer invocation_hint, - gpointer marshal_data ); -#define g_cclosure_marshal_BOOL__FLAGS g_cclosure_marshal_BOOLEAN__FLAGS - -/* STRING:OBJECT,POINTER (./gmarshal.list:47) */ -extern void g_cclosure_marshal_STRING__OBJECT_POINTER( GClosure *closure, - GValue *return_value, - guint n_param_values, - const GValue *param_values, - gpointer invocation_hint, - gpointer marshal_data ); - -G_END_DECLS - -#endif /* __G_MARSHAL_H__ */ diff --git a/tools/urt/tools/quake3/common/gobject/gobject.h b/tools/urt/tools/quake3/common/gobject/gobject.h deleted file mode 100644 index 510201d..0000000 --- a/tools/urt/tools/quake3/common/gobject/gobject.h +++ /dev/null @@ -1,252 +0,0 @@ -/* GObject - GLib Type, Object, Parameter and Signal Library - * Copyright (C) 1998-1999, 2000-2001 Tim Janik and Red Hat, Inc. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General - * Public License along with this library; if not, write to the - * Free Software Foundation, Inc., 59 Temple Place, Suite 330, - * Boston, MA 02111-1307, USA. - */ -#if !defined ( __GLIB_GOBJECT_H_INSIDE__ ) && !defined ( GOBJECT_COMPILATION ) -#error "Only can be included directly." -#endif - -#ifndef __G_OBJECT_H__ -#define __G_OBJECT_H__ - -#include -#include -#include -#include -#include - -G_BEGIN_DECLS - -/* --- type macros --- */ -#define G_TYPE_IS_OBJECT( type ) ( G_TYPE_FUNDAMENTAL( type ) == G_TYPE_OBJECT ) -#define G_OBJECT( object ) ( G_TYPE_CHECK_INSTANCE_CAST( ( object ), G_TYPE_OBJECT, GObject ) ) -#define G_OBJECT_CLASS( class ) ( G_TYPE_CHECK_CLASS_CAST( ( class ), G_TYPE_OBJECT, GObjectClass ) ) -#define G_IS_OBJECT( object ) ( G_TYPE_CHECK_INSTANCE_TYPE( ( object ), G_TYPE_OBJECT ) ) -#define G_IS_OBJECT_CLASS( class ) ( G_TYPE_CHECK_CLASS_TYPE( ( class ), G_TYPE_OBJECT ) ) -#define G_OBJECT_GET_CLASS( object ) ( G_TYPE_INSTANCE_GET_CLASS( ( object ), G_TYPE_OBJECT, GObjectClass ) ) -#define G_OBJECT_TYPE( object ) ( G_TYPE_FROM_INSTANCE( object ) ) -#define G_OBJECT_TYPE_NAME( object ) ( g_type_name( G_OBJECT_TYPE( object ) ) ) -#define G_OBJECT_CLASS_TYPE( class ) ( G_TYPE_FROM_CLASS( class ) ) -#define G_OBJECT_CLASS_NAME( class ) ( g_type_name( G_OBJECT_CLASS_TYPE( class ) ) ) -#define G_VALUE_HOLDS_OBJECT( value ) ( G_TYPE_CHECK_VALUE_TYPE( ( value ), G_TYPE_OBJECT ) ) - - -/* --- typedefs & structures --- */ -typedef struct _GObject GObject; -typedef struct _GObjectClass GObjectClass; -typedef struct _GObjectConstructParam GObjectConstructParam; -typedef void ( *GObjectGetPropertyFunc )( GObject *object, - guint property_id, - GValue *value, - GParamSpec *pspec ); -typedef void ( *GObjectSetPropertyFunc )( GObject *object, - guint property_id, - const GValue *value, - GParamSpec *pspec ); -typedef void ( *GObjectFinalizeFunc )( GObject *object ); -typedef void ( *GWeakNotify )( gpointer data, - GObject *where_the_object_was ); -struct _GObject -{ - GTypeInstance g_type_instance; - - /*< private >*/ - guint ref_count; - GData *qdata; -}; -struct _GObjectClass -{ - GTypeClass g_type_class; - - /*< private >*/ - GSList *construct_properties; - - /*< public >*/ - /* overridable methods */ - GObject* ( *constructor )( GType type, - guint n_construct_properties, - GObjectConstructParam * construct_properties ); - void ( *set_property )( GObject *object, - guint property_id, - const GValue *value, - GParamSpec *pspec ); - void ( *get_property )( GObject *object, - guint property_id, - GValue *value, - GParamSpec *pspec ); - void ( *dispose )( GObject *object ); - void ( *finalize )( GObject *object ); - - /* seldomly overidden */ - void ( *dispatch_properties_changed )( GObject *object, - guint n_pspecs, - GParamSpec **pspecs ); - - /* signals */ - void ( *notify )( GObject *object, - GParamSpec *pspec ); - /*< private >*/ - /* padding */ - gpointer pdummy[8]; -}; -struct _GObjectConstructParam -{ - GParamSpec *pspec; - GValue *value; -}; - - -/* --- prototypes --- */ -void g_object_class_install_property( GObjectClass *oclass, - guint property_id, - GParamSpec *pspec ); -GParamSpec* g_object_class_find_property( GObjectClass *oclass, - const gchar *property_name ); -GParamSpec**g_object_class_list_properties( GObjectClass *oclass, - guint *n_properties ); -void g_object_class_override_property( GObjectClass *oclass, - guint property_id, - const gchar *name ); - -void g_object_interface_install_property( gpointer g_iface, - GParamSpec *pspec ); -GParamSpec* g_object_interface_find_property( gpointer g_iface, - const gchar *property_name ); -GParamSpec**g_object_interface_list_properties( gpointer g_iface, - guint *n_properties_p ); - -gpointer g_object_new( GType object_type, - const gchar *first_property_name, - ... ); -gpointer g_object_newv( GType object_type, - guint n_parameters, - GParameter *parameters ); -GObject* g_object_new_valist( GType object_type, - const gchar *first_property_name, - va_list var_args ); -void g_object_set( gpointer object, - const gchar *first_property_name, - ... ); -void g_object_get( gpointer object, - const gchar *first_property_name, - ... ); -gpointer g_object_connect( gpointer object, - const gchar *signal_spec, - ... ); -void g_object_disconnect( gpointer object, - const gchar *signal_spec, - ... ); -void g_object_set_valist( GObject *object, - const gchar *first_property_name, - va_list var_args ); -void g_object_get_valist( GObject *object, - const gchar *first_property_name, - va_list var_args ); -void g_object_set_property( GObject *object, - const gchar *property_name, - const GValue *value ); -void g_object_get_property( GObject *object, - const gchar *property_name, - GValue *value ); -void g_object_freeze_notify( GObject *object ); -void g_object_notify( GObject *object, - const gchar *property_name ); -void g_object_thaw_notify( GObject *object ); -gpointer g_object_ref( gpointer object ); -void g_object_unref( gpointer object ); -void g_object_weak_ref( GObject *object, - GWeakNotify notify, - gpointer data ); -void g_object_weak_unref( GObject *object, - GWeakNotify notify, - gpointer data ); -void g_object_add_weak_pointer( GObject *object, - gpointer *weak_pointer_location ); -void g_object_remove_weak_pointer( GObject *object, - gpointer *weak_pointer_location ); -gpointer g_object_get_qdata( GObject *object, - GQuark quark ); -void g_object_set_qdata( GObject *object, - GQuark quark, - gpointer data ); -void g_object_set_qdata_full( GObject *object, - GQuark quark, - gpointer data, - GDestroyNotify destroy ); -gpointer g_object_steal_qdata( GObject *object, - GQuark quark ); -gpointer g_object_get_data( GObject *object, - const gchar *key ); -void g_object_set_data( GObject *object, - const gchar *key, - gpointer data ); -void g_object_set_data_full( GObject *object, - const gchar *key, - gpointer data, - GDestroyNotify destroy ); -gpointer g_object_steal_data( GObject *object, - const gchar *key ); -void g_object_watch_closure( GObject *object, - GClosure *closure ); -GClosure* g_cclosure_new_object( GCallback callback_func, - GObject *object ); -GClosure* g_cclosure_new_object_swap( GCallback callback_func, - GObject *object ); -GClosure* g_closure_new_object( guint sizeof_closure, - GObject *object ); -void g_value_set_object( GValue *value, - gpointer v_object ); -gpointer g_value_get_object( const GValue *value ); -GObject* g_value_dup_object( const GValue *value ); -gulong g_signal_connect_object( gpointer instance, - const gchar *detailed_signal, - GCallback c_handler, - gpointer gobject, - GConnectFlags connect_flags ); - - -/*< protected >*/ -void g_object_run_dispose( GObject *object ); - - -void g_value_take_object( GValue *value, - gpointer v_object ); -#ifndef G_DISABLE_DEPRECATED -void g_value_set_object_take_ownership( GValue *value, - gpointer v_object ); -#endif - -/* --- implementation macros --- */ -#define G_OBJECT_WARN_INVALID_PSPEC( object, pname, property_id, pspec ) \ - G_STMT_START { \ - GObject *_object = (GObject*) ( object ); \ - GParamSpec *_pspec = (GParamSpec*) ( pspec ); \ - guint _property_id = ( property_id ); \ - g_warning( "%s: invalid %s id %u for \"%s\" of type `%s' in `%s'", \ - G_STRLOC, \ - ( pname ), \ - _property_id, \ - _pspec->name, \ - g_type_name( G_PARAM_SPEC_TYPE( _pspec ) ), \ - G_OBJECT_TYPE_NAME( _object ) ); \ - } G_STMT_END -#define G_OBJECT_WARN_INVALID_PROPERTY_ID( object, property_id, pspec ) \ - G_OBJECT_WARN_INVALID_PSPEC( ( object ), "property", ( property_id ), ( pspec ) ) - -G_END_DECLS - -#endif /* __G_OBJECT_H__ */ diff --git a/tools/urt/tools/quake3/common/gobject/gobjectnotifyqueue.c b/tools/urt/tools/quake3/common/gobject/gobjectnotifyqueue.c deleted file mode 100644 index 421ce3c..0000000 --- a/tools/urt/tools/quake3/common/gobject/gobjectnotifyqueue.c +++ /dev/null @@ -1,166 +0,0 @@ -/* GObject - GLib Type, Object, Parameter and Signal Library - * Copyright (C) 1998-1999, 2000-2001 Tim Janik and Red Hat, Inc. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General - * Public License along with this library; if not, write to the - * Free Software Foundation, Inc., 59 Temple Place, Suite 330, - * Boston, MA 02111-1307, USA. - */ -#ifndef __G_NOTIFY_H__ -#define __G_NOTIFY_H__ - -#include /* memset */ -#include - -G_BEGIN_DECLS - - -/* --- typedefs --- */ -typedef struct _GObjectNotifyContext GObjectNotifyContext; -typedef struct _GObjectNotifyQueue GObjectNotifyQueue; -typedef void ( *GObjectNotifyQueueDispatcher )( GObject *object, - guint n_pspecs, - GParamSpec **pspecs ); - - -/* --- structures --- */ -struct _GObjectNotifyContext -{ - GQuark quark_notify_queue; - GObjectNotifyQueueDispatcher dispatcher; - GTrashStack *_nqueue_trash; /* unused */ -}; -struct _GObjectNotifyQueue -{ - GObjectNotifyContext *context; - GSList *pspecs; - guint16 n_pspecs; - guint16 freeze_count; - /* currently, this structure abuses the GList allocation chain and thus - * must be <= sizeof (GList) - */ -}; - - -/* --- functions --- */ -static void -g_object_notify_queue_free( gpointer data ){ - GObjectNotifyQueue *nqueue = data; - - g_slist_free( nqueue->pspecs ); - g_list_free_1( (void*) nqueue ); -} - -static inline GObjectNotifyQueue* -g_object_notify_queue_freeze( GObject *object, - GObjectNotifyContext *context ){ - GObjectNotifyQueue *nqueue; - - nqueue = g_datalist_id_get_data( &object->qdata, context->quark_notify_queue ); - if ( !nqueue ) { - nqueue = (void*) g_list_alloc(); - memset( nqueue, 0, sizeof( *nqueue ) ); - nqueue->context = context; - g_datalist_id_set_data_full( &object->qdata, context->quark_notify_queue, - nqueue, g_object_notify_queue_free ); - } - - g_return_val_if_fail( nqueue->freeze_count < 65535, nqueue ); - nqueue->freeze_count++; - - return nqueue; -} - -static inline void -g_object_notify_queue_thaw( GObject *object, - GObjectNotifyQueue *nqueue ){ - GObjectNotifyContext *context = nqueue->context; - GParamSpec *pspecs_mem[16], **pspecs, **free_me = NULL; - GSList *slist; - guint n_pspecs = 0; - - g_return_if_fail( nqueue->freeze_count > 0 ); - - nqueue->freeze_count--; - if ( nqueue->freeze_count ) { - return; - } - g_return_if_fail( object->ref_count > 0 ); - - pspecs = nqueue->n_pspecs > 16 ? free_me = g_new( GParamSpec *, nqueue->n_pspecs ) : pspecs_mem; - /* set first entry to NULL since it's checked unconditionally */ - pspecs[0] = NULL; - for ( slist = nqueue->pspecs; slist; slist = slist->next ) - { - GParamSpec *pspec = slist->data; - gint i = 0; - - /* dedup, make pspecs in the list unique */ -redo_dedup_check: - if ( pspecs[i] == pspec ) { - continue; - } - if ( ++i < n_pspecs ) { - goto redo_dedup_check; - } - - pspecs[n_pspecs++] = pspec; - } - g_datalist_id_set_data( &object->qdata, context->quark_notify_queue, NULL ); - - if ( n_pspecs ) { - context->dispatcher( object, n_pspecs, pspecs ); - } - g_free( free_me ); -} - -static inline void -g_object_notify_queue_clear( GObject *object, - GObjectNotifyQueue *nqueue ){ - g_return_if_fail( nqueue->freeze_count > 0 ); - - g_slist_free( nqueue->pspecs ); - nqueue->pspecs = NULL; - nqueue->n_pspecs = 0; -} - -static inline void -g_object_notify_queue_add( GObject *object, - GObjectNotifyQueue *nqueue, - GParamSpec *pspec ){ - if ( pspec->flags & G_PARAM_READABLE ) { - GParamSpec *redirect; - - g_return_if_fail( nqueue->n_pspecs < 65535 ); - - redirect = g_param_spec_get_redirect_target( pspec ); - if ( redirect ) { - pspec = redirect; - } - - /* we do the deduping in _thaw */ - nqueue->pspecs = g_slist_prepend( nqueue->pspecs, pspec ); - nqueue->n_pspecs++; - } -} - -static inline GObjectNotifyQueue* -g_object_notify_queue_from_object( GObject *object, - GObjectNotifyContext *context ){ - return g_datalist_id_get_data( &object->qdata, context->quark_notify_queue ); -} - - -G_END_DECLS - -#endif /* __G_OBJECT_H__ */ diff --git a/tools/urt/tools/quake3/common/gobject/gparam.h b/tools/urt/tools/quake3/common/gobject/gparam.h deleted file mode 100644 index a6c6c3f..0000000 --- a/tools/urt/tools/quake3/common/gobject/gparam.h +++ /dev/null @@ -1,228 +0,0 @@ -/* GObject - GLib Type, Object, Parameter and Signal Library - * Copyright (C) 1997-1999, 2000-2001 Tim Janik and Red Hat, Inc. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General - * Public License along with this library; if not, write to the - * Free Software Foundation, Inc., 59 Temple Place, Suite 330, - * Boston, MA 02111-1307, USA. - * - * gparam.h: GParamSpec base class implementation - */ -#if !defined ( __GLIB_GOBJECT_H_INSIDE__ ) && !defined ( GOBJECT_COMPILATION ) -#error "Only can be included directly." -#endif - -#ifndef __G_PARAM_H__ -#define __G_PARAM_H__ - -#include - -G_BEGIN_DECLS - -/* --- standard type macros --- */ -#define G_TYPE_IS_PARAM( type ) ( G_TYPE_FUNDAMENTAL( type ) == G_TYPE_PARAM ) -#define G_PARAM_SPEC( pspec ) ( G_TYPE_CHECK_INSTANCE_CAST( ( pspec ), G_TYPE_PARAM, GParamSpec ) ) -#define G_IS_PARAM_SPEC( pspec ) ( G_TYPE_CHECK_INSTANCE_TYPE( ( pspec ), G_TYPE_PARAM ) ) -#define G_PARAM_SPEC_CLASS( pclass ) ( G_TYPE_CHECK_CLASS_CAST( ( pclass ), G_TYPE_PARAM, GParamSpecClass ) ) -#define G_IS_PARAM_SPEC_CLASS( pclass ) ( G_TYPE_CHECK_CLASS_TYPE( ( pclass ), G_TYPE_PARAM ) ) -#define G_PARAM_SPEC_GET_CLASS( pspec ) ( G_TYPE_INSTANCE_GET_CLASS( ( pspec ), G_TYPE_PARAM, GParamSpecClass ) ) - - -/* --- convenience macros --- */ -#define G_PARAM_SPEC_TYPE( pspec ) ( G_TYPE_FROM_INSTANCE( pspec ) ) -#define G_PARAM_SPEC_TYPE_NAME( pspec ) ( g_type_name( G_PARAM_SPEC_TYPE( pspec ) ) ) -#define G_PARAM_SPEC_VALUE_TYPE( pspec ) ( G_PARAM_SPEC( pspec )->value_type ) -#define G_VALUE_HOLDS_PARAM( value ) ( G_TYPE_CHECK_VALUE_TYPE( ( value ), G_TYPE_PARAM ) ) - - -/* --- flags --- */ -typedef enum -{ - G_PARAM_READABLE = 1 << 0, - G_PARAM_WRITABLE = 1 << 1, - G_PARAM_CONSTRUCT = 1 << 2, - G_PARAM_CONSTRUCT_ONLY = 1 << 3, - G_PARAM_LAX_VALIDATION = 1 << 4, - G_PARAM_PRIVATE = 1 << 5 -} GParamFlags; -#define G_PARAM_READWRITE ( G_PARAM_READABLE | G_PARAM_WRITABLE ) -#define G_PARAM_MASK ( 0x000000ff ) -/* bits in the range 0xffffff00 are reserved for 3rd party usage */ -#define G_PARAM_USER_SHIFT ( 8 ) - - -/* --- typedefs & structures --- */ -typedef struct _GParamSpec GParamSpec; -typedef struct _GParamSpecClass GParamSpecClass; -typedef struct _GParameter GParameter; -typedef struct _GParamSpecPool GParamSpecPool; -struct _GParamSpec -{ - GTypeInstance g_type_instance; - - gchar *name; - GParamFlags flags; - GType value_type; - GType owner_type; /* class or interface using this property */ - - /*< private >*/ - gchar *_nick; - gchar *_blurb; - GData *qdata; - guint ref_count; - guint param_id; /* sort-criteria */ -}; -struct _GParamSpecClass -{ - GTypeClass g_type_class; - - GType value_type; - - void ( *finalize )( GParamSpec *pspec ); - - /* GParam methods */ - void ( *value_set_default )( GParamSpec *pspec, - GValue *value ); - gboolean ( *value_validate )( GParamSpec *pspec, - GValue *value ); - gint ( *values_cmp )( GParamSpec *pspec, - const GValue *value1, - const GValue *value2 ); - /*< private >*/ - gpointer dummy[4]; -}; -struct _GParameter /* auxillary structure for _setv() variants */ -{ - const gchar *name; - GValue value; -}; - - -/* --- prototypes --- */ -GParamSpec* g_param_spec_ref( GParamSpec *pspec ); -void g_param_spec_unref( GParamSpec *pspec ); -void g_param_spec_sink( GParamSpec *pspec ); -gpointer g_param_spec_get_qdata( GParamSpec *pspec, - GQuark quark ); -void g_param_spec_set_qdata( GParamSpec *pspec, - GQuark quark, - gpointer data ); -void g_param_spec_set_qdata_full( GParamSpec *pspec, - GQuark quark, - gpointer data, - GDestroyNotify destroy ); -gpointer g_param_spec_steal_qdata( GParamSpec *pspec, - GQuark quark ); -GParamSpec* g_param_spec_get_redirect_target( GParamSpec *pspec ); - -void g_param_value_set_default( GParamSpec *pspec, - GValue *value ); -gboolean g_param_value_defaults( GParamSpec *pspec, - GValue *value ); -gboolean g_param_value_validate( GParamSpec *pspec, - GValue *value ); -gboolean g_param_value_convert( GParamSpec *pspec, - const GValue *src_value, - GValue *dest_value, - gboolean strict_validation ); -gint g_param_values_cmp( GParamSpec *pspec, - const GValue *value1, - const GValue *value2 ); -G_CONST_RETURN gchar* g_param_spec_get_name( GParamSpec *pspec ); -G_CONST_RETURN gchar* g_param_spec_get_nick( GParamSpec *pspec ); -G_CONST_RETURN gchar* g_param_spec_get_blurb( GParamSpec *pspec ); -void g_value_set_param( GValue *value, - GParamSpec *param ); -GParamSpec* g_value_get_param( const GValue *value ); -GParamSpec* g_value_dup_param( const GValue *value ); - - -void g_value_take_param( GValue *value, - GParamSpec *param ); -#ifndef G_DISABLE_DEPRECATED -void g_value_set_param_take_ownership( GValue *value, - GParamSpec *param ); -#endif - -/* --- convenience functions --- */ -typedef struct _GParamSpecTypeInfo GParamSpecTypeInfo; -struct _GParamSpecTypeInfo -{ - /* type system portion */ - guint16 instance_size; /* obligatory */ - guint16 n_preallocs; /* optional */ - void ( *instance_init )( GParamSpec *pspec ); /* optional */ - - /* class portion */ - GType value_type; /* obligatory */ - void ( *finalize )( GParamSpec *pspec ); /* optional */ - void ( *value_set_default )( GParamSpec *pspec, /* recommended */ - GValue *value ); - gboolean ( *value_validate )( GParamSpec *pspec, /* optional */ - GValue *value ); - gint ( *values_cmp )( GParamSpec *pspec, /* recommended */ - const GValue *value1, - const GValue *value2 ); -}; -GType g_param_type_register_static( const gchar *name, - const GParamSpecTypeInfo *pspec_info ); - -/* For registering builting types */ -GType _g_param_type_register_static_constant( const gchar *name, - const GParamSpecTypeInfo *pspec_info, - GType opt_type ); - - -/* --- protected --- */ -gpointer g_param_spec_internal( GType param_type, - const gchar *name, - const gchar *nick, - const gchar *blurb, - GParamFlags flags ); -GParamSpecPool* g_param_spec_pool_new( gboolean type_prefixing ); -void g_param_spec_pool_insert( GParamSpecPool *pool, - GParamSpec *pspec, - GType owner_type ); -void g_param_spec_pool_remove( GParamSpecPool *pool, - GParamSpec *pspec ); -GParamSpec* g_param_spec_pool_lookup( GParamSpecPool *pool, - const gchar *param_name, - GType owner_type, - gboolean walk_ancestors ); -GList* g_param_spec_pool_list_owned( GParamSpecPool *pool, - GType owner_type ); -GParamSpec** g_param_spec_pool_list( GParamSpecPool *pool, - GType owner_type, - guint *n_pspecs_p ); - - - -/* contracts: - * - * gboolean value_validate (GParamSpec *pspec, - * GValue *value): - * modify value contents in the least destructive way, so - * that it complies with pspec's requirements (i.e. - * according to minimum/maximum ranges etc...). return - * whether modification was necessary. - * - * gint values_cmp (GParamSpec *pspec, - * const GValue *value1, - * const GValue *value2): - * return value1 - value2, i.e. (-1) if value1 < value2, - * (+1) if value1 > value2, and (0) otherwise (equality) - */ - -G_END_DECLS - -#endif /* __G_PARAM_H__ */ diff --git a/tools/urt/tools/quake3/common/gobject/gparamspecs.h b/tools/urt/tools/quake3/common/gobject/gparamspecs.h deleted file mode 100644 index 125bb88..0000000 --- a/tools/urt/tools/quake3/common/gobject/gparamspecs.h +++ /dev/null @@ -1,426 +0,0 @@ -/* GObject - GLib Type, Object, Parameter and Signal Library - * Copyright (C) 1997-1999, 2000-2001 Tim Janik and Red Hat, Inc. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General - * Public License along with this library; if not, write to the - * Free Software Foundation, Inc., 59 Temple Place, Suite 330, - * Boston, MA 02111-1307, USA. - * - * gparamspecs.h: GLib default param specs - */ -#if !defined ( __GLIB_GOBJECT_H_INSIDE__ ) && !defined ( GOBJECT_COMPILATION ) -#error "Only can be included directly." -#endif - -#ifndef __G_PARAMSPECS_H__ -#define __G_PARAMSPECS_H__ - -#include -#include -#include -#include - -G_BEGIN_DECLS - -/* --- type macros --- */ -#define G_TYPE_PARAM_CHAR ( g_param_spec_types[0] ) -#define G_IS_PARAM_SPEC_CHAR( pspec ) ( G_TYPE_CHECK_INSTANCE_TYPE( ( pspec ), G_TYPE_PARAM_CHAR ) ) -#define G_PARAM_SPEC_CHAR( pspec ) ( G_TYPE_CHECK_INSTANCE_CAST( ( pspec ), G_TYPE_PARAM_CHAR, GParamSpecChar ) ) -#define G_TYPE_PARAM_UCHAR ( g_param_spec_types[1] ) -#define G_IS_PARAM_SPEC_UCHAR( pspec ) ( G_TYPE_CHECK_INSTANCE_TYPE( ( pspec ), G_TYPE_PARAM_UCHAR ) ) -#define G_PARAM_SPEC_UCHAR( pspec ) ( G_TYPE_CHECK_INSTANCE_CAST( ( pspec ), G_TYPE_PARAM_UCHAR, GParamSpecUChar ) ) -#define G_TYPE_PARAM_BOOLEAN ( g_param_spec_types[2] ) -#define G_IS_PARAM_SPEC_BOOLEAN( pspec ) ( G_TYPE_CHECK_INSTANCE_TYPE( ( pspec ), G_TYPE_PARAM_BOOLEAN ) ) -#define G_PARAM_SPEC_BOOLEAN( pspec ) ( G_TYPE_CHECK_INSTANCE_CAST( ( pspec ), G_TYPE_PARAM_BOOLEAN, GParamSpecBoolean ) ) -#define G_TYPE_PARAM_INT ( g_param_spec_types[3] ) -#define G_IS_PARAM_SPEC_INT( pspec ) ( G_TYPE_CHECK_INSTANCE_TYPE( ( pspec ), G_TYPE_PARAM_INT ) ) -#define G_PARAM_SPEC_INT( pspec ) ( G_TYPE_CHECK_INSTANCE_CAST( ( pspec ), G_TYPE_PARAM_INT, GParamSpecInt ) ) -#define G_TYPE_PARAM_UINT ( g_param_spec_types[4] ) -#define G_IS_PARAM_SPEC_UINT( pspec ) ( G_TYPE_CHECK_INSTANCE_TYPE( ( pspec ), G_TYPE_PARAM_UINT ) ) -#define G_PARAM_SPEC_UINT( pspec ) ( G_TYPE_CHECK_INSTANCE_CAST( ( pspec ), G_TYPE_PARAM_UINT, GParamSpecUInt ) ) -#define G_TYPE_PARAM_LONG ( g_param_spec_types[5] ) -#define G_IS_PARAM_SPEC_LONG( pspec ) ( G_TYPE_CHECK_INSTANCE_TYPE( ( pspec ), G_TYPE_PARAM_LONG ) ) -#define G_PARAM_SPEC_LONG( pspec ) ( G_TYPE_CHECK_INSTANCE_CAST( ( pspec ), G_TYPE_PARAM_LONG, GParamSpecLong ) ) -#define G_TYPE_PARAM_ULONG ( g_param_spec_types[6] ) -#define G_IS_PARAM_SPEC_ULONG( pspec ) ( G_TYPE_CHECK_INSTANCE_TYPE( ( pspec ), G_TYPE_PARAM_ULONG ) ) -#define G_PARAM_SPEC_ULONG( pspec ) ( G_TYPE_CHECK_INSTANCE_CAST( ( pspec ), G_TYPE_PARAM_ULONG, GParamSpecULong ) ) -#define G_TYPE_PARAM_INT64 ( g_param_spec_types[7] ) -#define G_IS_PARAM_SPEC_INT64( pspec ) ( G_TYPE_CHECK_INSTANCE_TYPE( ( pspec ), G_TYPE_PARAM_INT64 ) ) -#define G_PARAM_SPEC_INT64( pspec ) ( G_TYPE_CHECK_INSTANCE_CAST( ( pspec ), G_TYPE_PARAM_INT64, GParamSpecInt64 ) ) -#define G_TYPE_PARAM_UINT64 ( g_param_spec_types[8] ) -#define G_IS_PARAM_SPEC_UINT64( pspec ) ( G_TYPE_CHECK_INSTANCE_TYPE( ( pspec ), G_TYPE_PARAM_UINT64 ) ) -#define G_PARAM_SPEC_UINT64( pspec ) ( G_TYPE_CHECK_INSTANCE_CAST( ( pspec ), G_TYPE_PARAM_UINT64, GParamSpecUInt64 ) ) -#define G_TYPE_PARAM_UNICHAR ( g_param_spec_types[9] ) -#define G_PARAM_SPEC_UNICHAR( pspec ) ( G_TYPE_CHECK_INSTANCE_CAST( ( pspec ), G_TYPE_PARAM_UNICHAR, GParamSpecUnichar ) ) -#define G_IS_PARAM_SPEC_UNICHAR( pspec ) ( G_TYPE_CHECK_INSTANCE_TYPE( ( pspec ), G_TYPE_PARAM_UNICHAR ) ) -#define G_TYPE_PARAM_ENUM ( g_param_spec_types[10] ) -#define G_IS_PARAM_SPEC_ENUM( pspec ) ( G_TYPE_CHECK_INSTANCE_TYPE( ( pspec ), G_TYPE_PARAM_ENUM ) ) -#define G_PARAM_SPEC_ENUM( pspec ) ( G_TYPE_CHECK_INSTANCE_CAST( ( pspec ), G_TYPE_PARAM_ENUM, GParamSpecEnum ) ) -#define G_TYPE_PARAM_FLAGS ( g_param_spec_types[11] ) -#define G_IS_PARAM_SPEC_FLAGS( pspec ) ( G_TYPE_CHECK_INSTANCE_TYPE( ( pspec ), G_TYPE_PARAM_FLAGS ) ) -#define G_PARAM_SPEC_FLAGS( pspec ) ( G_TYPE_CHECK_INSTANCE_CAST( ( pspec ), G_TYPE_PARAM_FLAGS, GParamSpecFlags ) ) -#define G_TYPE_PARAM_FLOAT ( g_param_spec_types[12] ) -#define G_IS_PARAM_SPEC_FLOAT( pspec ) ( G_TYPE_CHECK_INSTANCE_TYPE( ( pspec ), G_TYPE_PARAM_FLOAT ) ) -#define G_PARAM_SPEC_FLOAT( pspec ) ( G_TYPE_CHECK_INSTANCE_CAST( ( pspec ), G_TYPE_PARAM_FLOAT, GParamSpecFloat ) ) -#define G_TYPE_PARAM_DOUBLE ( g_param_spec_types[13] ) -#define G_IS_PARAM_SPEC_DOUBLE( pspec ) ( G_TYPE_CHECK_INSTANCE_TYPE( ( pspec ), G_TYPE_PARAM_DOUBLE ) ) -#define G_PARAM_SPEC_DOUBLE( pspec ) ( G_TYPE_CHECK_INSTANCE_CAST( ( pspec ), G_TYPE_PARAM_DOUBLE, GParamSpecDouble ) ) -#define G_TYPE_PARAM_STRING ( g_param_spec_types[14] ) -#define G_IS_PARAM_SPEC_STRING( pspec ) ( G_TYPE_CHECK_INSTANCE_TYPE( ( pspec ), G_TYPE_PARAM_STRING ) ) -#define G_PARAM_SPEC_STRING( pspec ) ( G_TYPE_CHECK_INSTANCE_CAST( ( pspec ), G_TYPE_PARAM_STRING, GParamSpecString ) ) -#define G_TYPE_PARAM_PARAM ( g_param_spec_types[15] ) -#define G_IS_PARAM_SPEC_PARAM( pspec ) ( G_TYPE_CHECK_INSTANCE_TYPE( ( pspec ), G_TYPE_PARAM_PARAM ) ) -#define G_PARAM_SPEC_PARAM( pspec ) ( G_TYPE_CHECK_INSTANCE_CAST( ( pspec ), G_TYPE_PARAM_PARAM, GParamSpecParam ) ) -#define G_TYPE_PARAM_BOXED ( g_param_spec_types[16] ) -#define G_IS_PARAM_SPEC_BOXED( pspec ) ( G_TYPE_CHECK_INSTANCE_TYPE( ( pspec ), G_TYPE_PARAM_BOXED ) ) -#define G_PARAM_SPEC_BOXED( pspec ) ( G_TYPE_CHECK_INSTANCE_CAST( ( pspec ), G_TYPE_PARAM_BOXED, GParamSpecBoxed ) ) -#define G_TYPE_PARAM_POINTER ( g_param_spec_types[17] ) -#define G_IS_PARAM_SPEC_POINTER( pspec ) ( G_TYPE_CHECK_INSTANCE_TYPE( ( pspec ), G_TYPE_PARAM_POINTER ) ) -#define G_PARAM_SPEC_POINTER( pspec ) ( G_TYPE_CHECK_INSTANCE_CAST( ( pspec ), G_TYPE_PARAM_POINTER, GParamSpecPointer ) ) -#define G_TYPE_PARAM_VALUE_ARRAY ( g_param_spec_types[18] ) -#define G_IS_PARAM_SPEC_VALUE_ARRAY( pspec ) ( G_TYPE_CHECK_INSTANCE_TYPE( ( pspec ), G_TYPE_PARAM_VALUE_ARRAY ) ) -#define G_PARAM_SPEC_VALUE_ARRAY( pspec ) ( G_TYPE_CHECK_INSTANCE_CAST( ( pspec ), G_TYPE_PARAM_VALUE_ARRAY, GParamSpecValueArray ) ) -#define G_TYPE_PARAM_OBJECT ( g_param_spec_types[19] ) -#define G_IS_PARAM_SPEC_OBJECT( pspec ) ( G_TYPE_CHECK_INSTANCE_TYPE( ( pspec ), G_TYPE_PARAM_OBJECT ) ) -#define G_PARAM_SPEC_OBJECT( pspec ) ( G_TYPE_CHECK_INSTANCE_CAST( ( pspec ), G_TYPE_PARAM_OBJECT, GParamSpecObject ) ) -#define G_TYPE_PARAM_OVERRIDE ( g_param_spec_types[20] ) -#define G_IS_PARAM_SPEC_OVERRIDE( pspec ) ( G_TYPE_CHECK_INSTANCE_TYPE( ( pspec ), G_TYPE_PARAM_OVERRIDE ) ) -#define G_PARAM_SPEC_OVERRIDE( pspec ) ( G_TYPE_CHECK_INSTANCE_CAST( ( pspec ), G_TYPE_PARAM_OVERRIDE, GParamSpecOverride ) ) - - -/* --- typedefs & structures --- */ -typedef struct _GParamSpecChar GParamSpecChar; -typedef struct _GParamSpecUChar GParamSpecUChar; -typedef struct _GParamSpecBoolean GParamSpecBoolean; -typedef struct _GParamSpecInt GParamSpecInt; -typedef struct _GParamSpecUInt GParamSpecUInt; -typedef struct _GParamSpecLong GParamSpecLong; -typedef struct _GParamSpecULong GParamSpecULong; -typedef struct _GParamSpecInt64 GParamSpecInt64; -typedef struct _GParamSpecUInt64 GParamSpecUInt64; -typedef struct _GParamSpecUnichar GParamSpecUnichar; -typedef struct _GParamSpecEnum GParamSpecEnum; -typedef struct _GParamSpecFlags GParamSpecFlags; -typedef struct _GParamSpecFloat GParamSpecFloat; -typedef struct _GParamSpecDouble GParamSpecDouble; -typedef struct _GParamSpecString GParamSpecString; -typedef struct _GParamSpecParam GParamSpecParam; -typedef struct _GParamSpecBoxed GParamSpecBoxed; -typedef struct _GParamSpecPointer GParamSpecPointer; -typedef struct _GParamSpecValueArray GParamSpecValueArray; -typedef struct _GParamSpecObject GParamSpecObject; -typedef struct _GParamSpecOverride GParamSpecOverride; - -struct _GParamSpecChar -{ - GParamSpec parent_instance; - - gint8 minimum; - gint8 maximum; - gint8 default_value; -}; -struct _GParamSpecUChar -{ - GParamSpec parent_instance; - - guint8 minimum; - guint8 maximum; - guint8 default_value; -}; -struct _GParamSpecBoolean -{ - GParamSpec parent_instance; - - gboolean default_value; -}; -struct _GParamSpecInt -{ - GParamSpec parent_instance; - - gint minimum; - gint maximum; - gint default_value; -}; -struct _GParamSpecUInt -{ - GParamSpec parent_instance; - - guint minimum; - guint maximum; - guint default_value; -}; -struct _GParamSpecLong -{ - GParamSpec parent_instance; - - glong minimum; - glong maximum; - glong default_value; -}; -struct _GParamSpecULong -{ - GParamSpec parent_instance; - - gulong minimum; - gulong maximum; - gulong default_value; -}; -struct _GParamSpecInt64 -{ - GParamSpec parent_instance; - - gint64 minimum; - gint64 maximum; - gint64 default_value; -}; -struct _GParamSpecUInt64 -{ - GParamSpec parent_instance; - - guint64 minimum; - guint64 maximum; - guint64 default_value; -}; -struct _GParamSpecUnichar -{ - GParamSpec parent_instance; - - gunichar default_value; -}; -struct _GParamSpecEnum -{ - GParamSpec parent_instance; - - GEnumClass *enum_class; - gint default_value; -}; -struct _GParamSpecFlags -{ - GParamSpec parent_instance; - - GFlagsClass *flags_class; - guint default_value; -}; -struct _GParamSpecFloat -{ - GParamSpec parent_instance; - - gfloat minimum; - gfloat maximum; - gfloat default_value; - gfloat epsilon; -}; -struct _GParamSpecDouble -{ - GParamSpec parent_instance; - - gdouble minimum; - gdouble maximum; - gdouble default_value; - gdouble epsilon; -}; -struct _GParamSpecString -{ - GParamSpec parent_instance; - - gchar *default_value; - gchar *cset_first; - gchar *cset_nth; - gchar substitutor; - guint null_fold_if_empty : 1; - guint ensure_non_null : 1; -}; -struct _GParamSpecParam -{ - GParamSpec parent_instance; -}; -struct _GParamSpecBoxed -{ - GParamSpec parent_instance; -}; -struct _GParamSpecPointer -{ - GParamSpec parent_instance; -}; -struct _GParamSpecValueArray -{ - GParamSpec parent_instance; - GParamSpec *element_spec; - guint fixed_n_elements; -}; -struct _GParamSpecObject -{ - GParamSpec parent_instance; -}; -struct _GParamSpecOverride -{ - /*< private >*/ - GParamSpec parent_instance; - GParamSpec *overridden; -}; - -/* --- GParamSpec prototypes --- */ -GParamSpec* g_param_spec_char( const gchar *name, - const gchar *nick, - const gchar *blurb, - gint8 minimum, - gint8 maximum, - gint8 default_value, - GParamFlags flags ); -GParamSpec* g_param_spec_uchar( const gchar *name, - const gchar *nick, - const gchar *blurb, - guint8 minimum, - guint8 maximum, - guint8 default_value, - GParamFlags flags ); -GParamSpec* g_param_spec_boolean( const gchar *name, - const gchar *nick, - const gchar *blurb, - gboolean default_value, - GParamFlags flags ); -GParamSpec* g_param_spec_int( const gchar *name, - const gchar *nick, - const gchar *blurb, - gint minimum, - gint maximum, - gint default_value, - GParamFlags flags ); -GParamSpec* g_param_spec_uint( const gchar *name, - const gchar *nick, - const gchar *blurb, - guint minimum, - guint maximum, - guint default_value, - GParamFlags flags ); -GParamSpec* g_param_spec_long( const gchar *name, - const gchar *nick, - const gchar *blurb, - glong minimum, - glong maximum, - glong default_value, - GParamFlags flags ); -GParamSpec* g_param_spec_ulong( const gchar *name, - const gchar *nick, - const gchar *blurb, - gulong minimum, - gulong maximum, - gulong default_value, - GParamFlags flags ); -GParamSpec* g_param_spec_int64( const gchar *name, - const gchar *nick, - const gchar *blurb, - gint64 minimum, - gint64 maximum, - gint64 default_value, - GParamFlags flags ); -GParamSpec* g_param_spec_uint64( const gchar *name, - const gchar *nick, - const gchar *blurb, - guint64 minimum, - guint64 maximum, - guint64 default_value, - GParamFlags flags ); -GParamSpec* g_param_spec_unichar( const gchar *name, - const gchar *nick, - const gchar *blurb, - gunichar default_value, - GParamFlags flags ); -GParamSpec* g_param_spec_enum( const gchar *name, - const gchar *nick, - const gchar *blurb, - GType enum_type, - gint default_value, - GParamFlags flags ); -GParamSpec* g_param_spec_flags( const gchar *name, - const gchar *nick, - const gchar *blurb, - GType flags_type, - guint default_value, - GParamFlags flags ); -GParamSpec* g_param_spec_float( const gchar *name, - const gchar *nick, - const gchar *blurb, - gfloat minimum, - gfloat maximum, - gfloat default_value, - GParamFlags flags ); -GParamSpec* g_param_spec_double( const gchar *name, - const gchar *nick, - const gchar *blurb, - gdouble minimum, - gdouble maximum, - gdouble default_value, - GParamFlags flags ); -GParamSpec* g_param_spec_string( const gchar *name, - const gchar *nick, - const gchar *blurb, - const gchar *default_value, - GParamFlags flags ); -GParamSpec* g_param_spec_param( const gchar *name, - const gchar *nick, - const gchar *blurb, - GType param_type, - GParamFlags flags ); -GParamSpec* g_param_spec_boxed( const gchar *name, - const gchar *nick, - const gchar *blurb, - GType boxed_type, - GParamFlags flags ); -GParamSpec* g_param_spec_pointer( const gchar *name, - const gchar *nick, - const gchar *blurb, - GParamFlags flags ); -GParamSpec* g_param_spec_value_array( const gchar *name, - const gchar *nick, - const gchar *blurb, - GParamSpec *element_spec, - GParamFlags flags ); -GParamSpec* g_param_spec_object( const gchar *name, - const gchar *nick, - const gchar *blurb, - GType object_type, - GParamFlags flags ); - -GParamSpec* g_param_spec_override( const gchar *name, - GParamSpec *overridden ); - -/* --- internal --- */ -/* We prefix variable declarations so they can - * properly get exported in windows dlls. - */ -#ifndef GOBJECT_VAR -# ifdef G_PLATFORM_WIN32 -# ifdef GOBJECT_STATIC_COMPILATION -# define GOBJECT_VAR extern -# else /* !GOBJECT_STATIC_COMPILATION */ -# ifdef GOBJECT_COMPILATION -# ifdef DLL_EXPORT -# define GOBJECT_VAR __declspec( dllexport ) -# else /* !DLL_EXPORT */ -# define GOBJECT_VAR extern -# endif /* !DLL_EXPORT */ -# else /* !GOBJECT_COMPILATION */ -# define GOBJECT_VAR extern __declspec( dllimport ) -# endif /* !GOBJECT_COMPILATION */ -# endif /* !GOBJECT_STATIC_COMPILATION */ -# else /* !G_PLATFORM_WIN32 */ -# define GOBJECT_VAR extern -# endif /* !G_PLATFORM_WIN32 */ -#endif /* GOBJECT_VAR */ - -GOBJECT_VAR GType *g_param_spec_types; - -G_END_DECLS - -#endif /* __G_PARAMSPECS_H__ */ diff --git a/tools/urt/tools/quake3/common/gobject/gsignal.h b/tools/urt/tools/quake3/common/gobject/gsignal.h deleted file mode 100644 index f8f6b9c..0000000 --- a/tools/urt/tools/quake3/common/gobject/gsignal.h +++ /dev/null @@ -1,270 +0,0 @@ -/* GObject - GLib Type, Object, Parameter and Signal Library - * Copyright (C) 2000-2001 Red Hat, Inc. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General - * Public License along with this library; if not, write to the - * Free Software Foundation, Inc., 59 Temple Place, Suite 330, - * Boston, MA 02111-1307, USA. - */ -#if !defined ( __GLIB_GOBJECT_H_INSIDE__ ) && !defined ( GOBJECT_COMPILATION ) -#error "Only can be included directly." -#endif - -#ifndef __G_SIGNAL_H__ -#define __G_SIGNAL_H__ - -#include -#include -#include -#include - -G_BEGIN_DECLS - -/* --- typedefs --- */ -typedef struct _GSignalQuery GSignalQuery; -typedef struct _GSignalInvocationHint GSignalInvocationHint; -typedef GClosureMarshal GSignalCMarshaller; -typedef gboolean ( *GSignalEmissionHook )( GSignalInvocationHint *ihint, - guint n_param_values, - const GValue *param_values, - gpointer data ); -typedef gboolean ( *GSignalAccumulator )( GSignalInvocationHint *ihint, - GValue *return_accu, - const GValue *handler_return, - gpointer data ); - - -/* --- run, match and connect types --- */ -typedef enum -{ - G_SIGNAL_RUN_FIRST = 1 << 0, - G_SIGNAL_RUN_LAST = 1 << 1, - G_SIGNAL_RUN_CLEANUP = 1 << 2, - G_SIGNAL_NO_RECURSE = 1 << 3, - G_SIGNAL_DETAILED = 1 << 4, - G_SIGNAL_ACTION = 1 << 5, - G_SIGNAL_NO_HOOKS = 1 << 6 -} GSignalFlags; -#define G_SIGNAL_FLAGS_MASK 0x7f -typedef enum -{ - G_CONNECT_AFTER = 1 << 0, - G_CONNECT_SWAPPED = 1 << 1 -} GConnectFlags; -typedef enum -{ - G_SIGNAL_MATCH_ID = 1 << 0, - G_SIGNAL_MATCH_DETAIL = 1 << 1, - G_SIGNAL_MATCH_CLOSURE = 1 << 2, - G_SIGNAL_MATCH_FUNC = 1 << 3, - G_SIGNAL_MATCH_DATA = 1 << 4, - G_SIGNAL_MATCH_UNBLOCKED = 1 << 5 -} GSignalMatchType; -#define G_SIGNAL_MATCH_MASK 0x3f -#define G_SIGNAL_TYPE_STATIC_SCOPE ( G_TYPE_FLAG_RESERVED_ID_BIT ) - - -/* --- signal information --- */ -struct _GSignalInvocationHint -{ - guint signal_id; - GQuark detail; - GSignalFlags run_type; -}; -struct _GSignalQuery -{ - guint signal_id; - const gchar *signal_name; - GType itype; - GSignalFlags signal_flags; - GType return_type; /* mangled with G_SIGNAL_TYPE_STATIC_SCOPE flag */ - guint n_params; - const GType *param_types; /* mangled with G_SIGNAL_TYPE_STATIC_SCOPE flag */ -}; - - -/* --- signals --- */ -guint g_signal_newv( const gchar *signal_name, - GType itype, - GSignalFlags signal_flags, - GClosure *class_closure, - GSignalAccumulator accumulator, - gpointer accu_data, - GSignalCMarshaller c_marshaller, - GType return_type, - guint n_params, - GType *param_types ); -guint g_signal_new_valist( const gchar *signal_name, - GType itype, - GSignalFlags signal_flags, - GClosure *class_closure, - GSignalAccumulator accumulator, - gpointer accu_data, - GSignalCMarshaller c_marshaller, - GType return_type, - guint n_params, - va_list args ); -guint g_signal_new( const gchar *signal_name, - GType itype, - GSignalFlags signal_flags, - guint class_offset, - GSignalAccumulator accumulator, - gpointer accu_data, - GSignalCMarshaller c_marshaller, - GType return_type, - guint n_params, - ... ); -void g_signal_emitv( const GValue *instance_and_params, - guint signal_id, - GQuark detail, - GValue *return_value ); -void g_signal_emit_valist( gpointer instance, - guint signal_id, - GQuark detail, - va_list var_args ); -void g_signal_emit( gpointer instance, - guint signal_id, - GQuark detail, - ... ); -void g_signal_emit_by_name( gpointer instance, - const gchar *detailed_signal, - ... ); -guint g_signal_lookup( const gchar *name, - GType itype ); -G_CONST_RETURN gchar* g_signal_name( guint signal_id ); -void g_signal_query( guint signal_id, - GSignalQuery *query ); -guint* g_signal_list_ids( GType itype, - guint *n_ids ); -gboolean g_signal_parse_name( const gchar *detailed_signal, - GType itype, - guint *signal_id_p, - GQuark *detail_p, - gboolean force_detail_quark ); -GSignalInvocationHint* g_signal_get_invocation_hint( gpointer instance ); - - -/* --- signal emissions --- */ -void g_signal_stop_emission( gpointer instance, - guint signal_id, - GQuark detail ); -void g_signal_stop_emission_by_name( gpointer instance, - const gchar *detailed_signal ); -gulong g_signal_add_emission_hook( guint signal_id, - GQuark detail, - GSignalEmissionHook hook_func, - gpointer hook_data, - GDestroyNotify data_destroy ); -void g_signal_remove_emission_hook( guint signal_id, - gulong hook_id ); - - -/* --- signal handlers --- */ -gboolean g_signal_has_handler_pending( gpointer instance, - guint signal_id, - GQuark detail, - gboolean may_be_blocked ); -gulong g_signal_connect_closure_by_id( gpointer instance, - guint signal_id, - GQuark detail, - GClosure *closure, - gboolean after ); -gulong g_signal_connect_closure( gpointer instance, - const gchar *detailed_signal, - GClosure *closure, - gboolean after ); -gulong g_signal_connect_data( gpointer instance, - const gchar *detailed_signal, - GCallback c_handler, - gpointer data, - GClosureNotify destroy_data, - GConnectFlags connect_flags ); -void g_signal_handler_block( gpointer instance, - gulong handler_id ); -void g_signal_handler_unblock( gpointer instance, - gulong handler_id ); -void g_signal_handler_disconnect( gpointer instance, - gulong handler_id ); -gboolean g_signal_handler_is_connected( gpointer instance, - gulong handler_id ); -gulong g_signal_handler_find( gpointer instance, - GSignalMatchType mask, - guint signal_id, - GQuark detail, - GClosure *closure, - gpointer func, - gpointer data ); -guint g_signal_handlers_block_matched( gpointer instance, - GSignalMatchType mask, - guint signal_id, - GQuark detail, - GClosure *closure, - gpointer func, - gpointer data ); -guint g_signal_handlers_unblock_matched( gpointer instance, - GSignalMatchType mask, - guint signal_id, - GQuark detail, - GClosure *closure, - gpointer func, - gpointer data ); -guint g_signal_handlers_disconnect_matched( gpointer instance, - GSignalMatchType mask, - guint signal_id, - GQuark detail, - GClosure *closure, - gpointer func, - gpointer data ); - - -/* --- chaining for language bindings --- */ -void g_signal_override_class_closure( guint signal_id, - GType instance_type, - GClosure *class_closure ); -void g_signal_chain_from_overridden( const GValue *instance_and_params, - GValue *return_value ); - - -/* --- convenience --- */ -#define g_signal_connect( instance, detailed_signal, c_handler, data ) \ - g_signal_connect_data( ( instance ), ( detailed_signal ), ( c_handler ), ( data ), NULL, (GConnectFlags) 0 ) -#define g_signal_connect_after( instance, detailed_signal, c_handler, data ) \ - g_signal_connect_data( ( instance ), ( detailed_signal ), ( c_handler ), ( data ), NULL, G_CONNECT_AFTER ) -#define g_signal_connect_swapped( instance, detailed_signal, c_handler, data ) \ - g_signal_connect_data( ( instance ), ( detailed_signal ), ( c_handler ), ( data ), NULL, G_CONNECT_SWAPPED ) -#define g_signal_handlers_disconnect_by_func( instance, func, data ) \ - g_signal_handlers_disconnect_matched( ( instance ), \ - (GSignalMatchType) ( G_SIGNAL_MATCH_FUNC | G_SIGNAL_MATCH_DATA ), \ - 0, 0, NULL, ( func ), ( data ) ) -#define g_signal_handlers_block_by_func( instance, func, data ) \ - g_signal_handlers_block_matched( ( instance ), \ - (GSignalMatchType) ( G_SIGNAL_MATCH_FUNC | G_SIGNAL_MATCH_DATA ), \ - 0, 0, NULL, ( func ), ( data ) ) -#define g_signal_handlers_unblock_by_func( instance, func, data ) \ - g_signal_handlers_unblock_matched( ( instance ), \ - (GSignalMatchType) ( G_SIGNAL_MATCH_FUNC | G_SIGNAL_MATCH_DATA ), \ - 0, 0, NULL, ( func ), ( data ) ) - - -gboolean g_signal_accumulator_true_handled( GSignalInvocationHint *ihint, - GValue *return_accu, - const GValue *handler_return, - gpointer dummy ); - -/*< private >*/ -void g_signal_handlers_destroy( gpointer instance ); -void _g_signals_destroy( GType itype ); - -G_END_DECLS - -#endif /* __G_SIGNAL_H__ */ diff --git a/tools/urt/tools/quake3/common/gobject/gsourceclosure.h b/tools/urt/tools/quake3/common/gobject/gsourceclosure.h deleted file mode 100644 index dd95184..0000000 --- a/tools/urt/tools/quake3/common/gobject/gsourceclosure.h +++ /dev/null @@ -1,41 +0,0 @@ -/* GObject - GLib Type, Object, Parameter and Signal Library - * Copyright (C) 2001 Red Hat, Inc. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General - * Public License along with this library; if not, write to the - * Free Software Foundation, Inc., 59 Temple Place, Suite 330, - * Boston, MA 02111-1307, USA. - */ -#if !defined ( __GLIB_GOBJECT_H_INSIDE__ ) && !defined ( GOBJECT_COMPILATION ) -#error "Only can be included directly." -#endif - -#ifndef __G_SOURCECLOSURE_H__ -#define __G_SOURCECLOSURE_H__ - -#include - -G_BEGIN_DECLS - -void g_source_set_closure( GSource *source, - GClosure *closure ); - -GType g_io_channel_get_type( void ); -GType g_io_condition_get_type( void ); - -#define G_TYPE_IO_CHANNEL ( g_io_channel_get_type() ) -#define G_TYPE_IO_CONDITION ( g_io_condition_get_type() ) - -G_END_DECLS - -#endif /* __G_SOURCECLOSURE_H__ */ diff --git a/tools/urt/tools/quake3/common/gobject/gtype.h b/tools/urt/tools/quake3/common/gobject/gtype.h deleted file mode 100644 index 5015811..0000000 --- a/tools/urt/tools/quake3/common/gobject/gtype.h +++ /dev/null @@ -1,479 +0,0 @@ -/* GObject - GLib Type, Object, Parameter and Signal Library - * Copyright (C) 1998-1999, 2000-2001 Tim Janik and Red Hat, Inc. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General - * Public License along with this library; if not, write to the - * Free Software Foundation, Inc., 59 Temple Place, Suite 330, - * Boston, MA 02111-1307, USA. - */ -#if !defined ( __GLIB_GOBJECT_H_INSIDE__ ) && !defined ( GOBJECT_COMPILATION ) -#error "Only can be included directly." -#endif - -#ifndef __G_TYPE_H__ -#define __G_TYPE_H__ - -#include - -G_BEGIN_DECLS - -/* Basic Type Macros - */ -#define G_TYPE_FUNDAMENTAL( type ) ( g_type_fundamental( type ) ) -#define G_TYPE_FUNDAMENTAL_MAX ( 255 << G_TYPE_FUNDAMENTAL_SHIFT ) - -/* Constant fundamental types, - * introduced by g_type_init(). - */ -#define G_TYPE_INVALID G_TYPE_MAKE_FUNDAMENTAL( 0 ) -#define G_TYPE_NONE G_TYPE_MAKE_FUNDAMENTAL( 1 ) -#define G_TYPE_INTERFACE G_TYPE_MAKE_FUNDAMENTAL( 2 ) -#define G_TYPE_CHAR G_TYPE_MAKE_FUNDAMENTAL( 3 ) -#define G_TYPE_UCHAR G_TYPE_MAKE_FUNDAMENTAL( 4 ) -#define G_TYPE_BOOLEAN G_TYPE_MAKE_FUNDAMENTAL( 5 ) -#define G_TYPE_INT G_TYPE_MAKE_FUNDAMENTAL( 6 ) -#define G_TYPE_UINT G_TYPE_MAKE_FUNDAMENTAL( 7 ) -#define G_TYPE_LONG G_TYPE_MAKE_FUNDAMENTAL( 8 ) -#define G_TYPE_ULONG G_TYPE_MAKE_FUNDAMENTAL( 9 ) -#define G_TYPE_INT64 G_TYPE_MAKE_FUNDAMENTAL( 10 ) -#define G_TYPE_UINT64 G_TYPE_MAKE_FUNDAMENTAL( 11 ) -#define G_TYPE_ENUM G_TYPE_MAKE_FUNDAMENTAL( 12 ) -#define G_TYPE_FLAGS G_TYPE_MAKE_FUNDAMENTAL( 13 ) -#define G_TYPE_FLOAT G_TYPE_MAKE_FUNDAMENTAL( 14 ) -#define G_TYPE_DOUBLE G_TYPE_MAKE_FUNDAMENTAL( 15 ) -#define G_TYPE_STRING G_TYPE_MAKE_FUNDAMENTAL( 16 ) -#define G_TYPE_POINTER G_TYPE_MAKE_FUNDAMENTAL( 17 ) -#define G_TYPE_BOXED G_TYPE_MAKE_FUNDAMENTAL( 18 ) -#define G_TYPE_PARAM G_TYPE_MAKE_FUNDAMENTAL( 19 ) -#define G_TYPE_OBJECT G_TYPE_MAKE_FUNDAMENTAL( 20 ) - - -/* Reserved fundamental type numbers to create new fundamental - * type IDs with G_TYPE_MAKE_FUNDAMENTAL(). - * Send email to gtk-devel-list@redhat.com for reservations. - */ -#define G_TYPE_FUNDAMENTAL_SHIFT ( 2 ) -#define G_TYPE_MAKE_FUNDAMENTAL( x ) ( (GType) ( ( x ) << G_TYPE_FUNDAMENTAL_SHIFT ) ) -#define G_TYPE_RESERVED_GLIB_FIRST ( 21 ) -#define G_TYPE_RESERVED_GLIB_LAST ( 31 ) -#define G_TYPE_RESERVED_BSE_FIRST ( 32 ) -#define G_TYPE_RESERVED_BSE_LAST ( 48 ) -#define G_TYPE_RESERVED_USER_FIRST ( 49 ) - - -/* Type Checking Macros - */ -#define G_TYPE_IS_FUNDAMENTAL( type ) ( ( type ) <= G_TYPE_FUNDAMENTAL_MAX ) -#define G_TYPE_IS_DERIVED( type ) ( ( type ) > G_TYPE_FUNDAMENTAL_MAX ) -#define G_TYPE_IS_INTERFACE( type ) ( G_TYPE_FUNDAMENTAL( type ) == G_TYPE_INTERFACE ) -#define G_TYPE_IS_CLASSED( type ) ( g_type_test_flags( ( type ), G_TYPE_FLAG_CLASSED ) ) -#define G_TYPE_IS_INSTANTIATABLE( type ) ( g_type_test_flags( ( type ), G_TYPE_FLAG_INSTANTIATABLE ) ) -#define G_TYPE_IS_DERIVABLE( type ) ( g_type_test_flags( ( type ), G_TYPE_FLAG_DERIVABLE ) ) -#define G_TYPE_IS_DEEP_DERIVABLE( type ) ( g_type_test_flags( ( type ), G_TYPE_FLAG_DEEP_DERIVABLE ) ) -#define G_TYPE_IS_ABSTRACT( type ) ( g_type_test_flags( ( type ), G_TYPE_FLAG_ABSTRACT ) ) -#define G_TYPE_IS_VALUE_ABSTRACT( type ) ( g_type_test_flags( ( type ), G_TYPE_FLAG_VALUE_ABSTRACT ) ) -#define G_TYPE_IS_VALUE_TYPE( type ) ( g_type_check_is_value_type( type ) ) -#define G_TYPE_HAS_VALUE_TABLE( type ) ( g_type_value_table_peek( type ) != NULL ) - - -/* Typedefs - */ -#if GLIB_SIZEOF_LONG == GLIB_SIZEOF_SIZE_T -typedef gulong GType; -#else /* hm, shouldn't happen? */ -typedef gsize GType; -#endif -typedef struct _GValue GValue; -typedef union _GTypeCValue GTypeCValue; -typedef struct _GTypePlugin GTypePlugin; -typedef struct _GTypeClass GTypeClass; -typedef struct _GTypeInterface GTypeInterface; -typedef struct _GTypeInstance GTypeInstance; -typedef struct _GTypeInfo GTypeInfo; -typedef struct _GTypeFundamentalInfo GTypeFundamentalInfo; -typedef struct _GInterfaceInfo GInterfaceInfo; -typedef struct _GTypeValueTable GTypeValueTable; -typedef struct _GTypeQuery GTypeQuery; - - -/* Basic Type Structures - */ -struct _GTypeClass -{ - /*< private >*/ - GType g_type; -}; -struct _GTypeInstance -{ - /*< private >*/ - GTypeClass *g_class; -}; -struct _GTypeInterface -{ - /*< private >*/ - GType g_type; /* iface type */ - GType g_instance_type; -}; -struct _GTypeQuery -{ - GType type; - const gchar *type_name; - guint class_size; - guint instance_size; -}; - - -/* Casts, checks and accessors for structured types - * usage of these macros is reserved to type implementations only - */ -/*< protected >*/ -#define G_TYPE_CHECK_INSTANCE( instance ) ( _G_TYPE_CHI( (GTypeInstance*) ( instance ) ) ) -#define G_TYPE_CHECK_INSTANCE_CAST( instance, g_type, c_type ) ( _G_TYPE_CIC( ( instance ), ( g_type ), c_type ) ) -#define G_TYPE_CHECK_INSTANCE_TYPE( instance, g_type ) ( _G_TYPE_CIT( ( instance ), ( g_type ) ) ) -#define G_TYPE_INSTANCE_GET_CLASS( instance, g_type, c_type ) ( _G_TYPE_IGC( ( instance ), ( g_type ), c_type ) ) -#define G_TYPE_INSTANCE_GET_INTERFACE( instance, g_type, c_type ) ( _G_TYPE_IGI( ( instance ), ( g_type ), c_type ) ) -#define G_TYPE_CHECK_CLASS_CAST( g_class, g_type, c_type ) ( _G_TYPE_CCC( ( g_class ), ( g_type ), c_type ) ) -#define G_TYPE_CHECK_CLASS_TYPE( g_class, g_type ) ( _G_TYPE_CCT( ( g_class ), ( g_type ) ) ) -#define G_TYPE_CHECK_VALUE( value ) ( _G_TYPE_CHV( ( value ) ) ) -#define G_TYPE_CHECK_VALUE_TYPE( value, g_type ) ( _G_TYPE_CVH( ( value ), ( g_type ) ) ) -#define G_TYPE_FROM_INSTANCE( instance ) ( G_TYPE_FROM_CLASS( ( (GTypeInstance*) ( instance ) )->g_class ) ) -#define G_TYPE_FROM_CLASS( g_class ) ( ( (GTypeClass*) ( g_class ) )->g_type ) -#define G_TYPE_FROM_INTERFACE( g_iface ) ( ( (GTypeInterface*) ( g_iface ) )->g_type ) - -#define G_TYPE_INSTANCE_GET_PRIVATE( instance, g_type, c_type ) ( (c_type*) g_type_instance_get_private( (GTypeInstance*) ( instance ), ( g_type ) ) ) - - -/* debug flags for g_type_init_with_debug_flags() */ -typedef enum /*< skip >*/ -{ - G_TYPE_DEBUG_NONE = 0, - G_TYPE_DEBUG_OBJECTS = 1 << 0, - G_TYPE_DEBUG_SIGNALS = 1 << 1, - G_TYPE_DEBUG_MASK = 0x03 -} GTypeDebugFlags; - - -/* --- prototypes --- */ -void g_type_init( void ); -void g_type_init_with_debug_flags( GTypeDebugFlags debug_flags ); -G_CONST_RETURN gchar* g_type_name( GType type ); -GQuark g_type_qname( GType type ); -GType g_type_from_name( const gchar *name ); -GType g_type_parent( GType type ); -guint g_type_depth( GType type ); -GType g_type_next_base( GType leaf_type, - GType root_type ); -gboolean g_type_is_a( GType type, - GType is_a_type ); -gpointer g_type_class_ref( GType type ); -gpointer g_type_class_peek( GType type ); -gpointer g_type_class_peek_static( GType type ); -void g_type_class_unref( gpointer g_class ); -gpointer g_type_class_peek_parent( gpointer g_class ); -gpointer g_type_interface_peek( gpointer instance_class, - GType iface_type ); -gpointer g_type_interface_peek_parent( gpointer g_iface ); - -gpointer g_type_default_interface_ref( GType g_type ); -gpointer g_type_default_interface_peek( GType g_type ); -void g_type_default_interface_unref( gpointer g_iface ); - -/* g_free() the returned arrays */ -GType* g_type_children( GType type, - guint *n_children ); -GType* g_type_interfaces( GType type, - guint *n_interfaces ); - -/* per-type _static_ data */ -void g_type_set_qdata( GType type, - GQuark quark, - gpointer data ); -gpointer g_type_get_qdata( GType type, - GQuark quark ); -void g_type_query( GType type, - GTypeQuery *query ); - - -/* --- type registration --- */ -typedef void ( *GBaseInitFunc )( gpointer g_class ); -typedef void ( *GBaseFinalizeFunc )( gpointer g_class ); -typedef void ( *GClassInitFunc )( gpointer g_class, - gpointer class_data ); -typedef void ( *GClassFinalizeFunc )( gpointer g_class, - gpointer class_data ); -typedef void ( *GInstanceInitFunc )( GTypeInstance *instance, - gpointer g_class ); -typedef void ( *GInterfaceInitFunc )( gpointer g_iface, - gpointer iface_data ); -typedef void ( *GInterfaceFinalizeFunc )( gpointer g_iface, - gpointer iface_data ); -typedef gboolean ( *GTypeClassCacheFunc )( gpointer cache_data, - GTypeClass *g_class ); -typedef void ( *GTypeInterfaceCheckFunc )( gpointer func_data, - gpointer g_iface ); -typedef enum /*< skip >*/ -{ - G_TYPE_FLAG_CLASSED = ( 1 << 0 ), - G_TYPE_FLAG_INSTANTIATABLE = ( 1 << 1 ), - G_TYPE_FLAG_DERIVABLE = ( 1 << 2 ), - G_TYPE_FLAG_DEEP_DERIVABLE = ( 1 << 3 ) -} GTypeFundamentalFlags; -typedef enum /*< skip >*/ -{ - G_TYPE_FLAG_ABSTRACT = ( 1 << 4 ), - G_TYPE_FLAG_VALUE_ABSTRACT = ( 1 << 5 ) -} GTypeFlags; -struct _GTypeInfo -{ - /* interface types, classed types, instantiated types */ - guint16 class_size; - - GBaseInitFunc base_init; - GBaseFinalizeFunc base_finalize; - - /* interface types, classed types, instantiated types */ - GClassInitFunc class_init; - GClassFinalizeFunc class_finalize; - gconstpointer class_data; - - /* instantiated types */ - guint16 instance_size; - guint16 n_preallocs; - GInstanceInitFunc instance_init; - - /* value handling */ - const GTypeValueTable *value_table; -}; -struct _GTypeFundamentalInfo -{ - GTypeFundamentalFlags type_flags; -}; -struct _GInterfaceInfo -{ - GInterfaceInitFunc interface_init; - GInterfaceFinalizeFunc interface_finalize; - gpointer interface_data; -}; -struct _GTypeValueTable -{ - void ( *value_init )( GValue *value ); - void ( *value_free )( GValue *value ); - void ( *value_copy )( const GValue *src_value, - GValue *dest_value ); - /* varargs functionality (optional) */ - gpointer ( *value_peek_pointer )( const GValue *value ); - gchar *collect_format; - gchar* ( *collect_value )( GValue * value, - guint n_collect_values, - GTypeCValue * collect_values, - guint collect_flags ); - gchar *lcopy_format; - gchar* ( *lcopy_value )( const GValue * value, - guint n_collect_values, - GTypeCValue * collect_values, - guint collect_flags ); -}; -GType g_type_register_static( GType parent_type, - const gchar *type_name, - const GTypeInfo *info, - GTypeFlags flags ); -GType g_type_register_dynamic( GType parent_type, - const gchar *type_name, - GTypePlugin *plugin, - GTypeFlags flags ); -GType g_type_register_fundamental( GType type_id, - const gchar *type_name, - const GTypeInfo *info, - const GTypeFundamentalInfo *finfo, - GTypeFlags flags ); -void g_type_add_interface_static( GType instance_type, - GType interface_type, - const GInterfaceInfo *info ); -void g_type_add_interface_dynamic( GType instance_type, - GType interface_type, - GTypePlugin *plugin ); -void g_type_interface_add_prerequisite( GType interface_type, - GType prerequisite_type ); -GType*g_type_interface_prerequisites( GType interface_type, - guint *n_prerequisites ); -void g_type_class_add_private( gpointer g_class, - gsize private_size ); -gpointer g_type_instance_get_private( GTypeInstance *instance, - GType private_type ); - - -/* --- GType boilerplate --- */ -/* convenience macros for type implementations, which for a type GtkGadget will: - * - prototype: static void gtk_gadget_class_init (GtkGadgetClass *klass); - * - prototype: static void gtk_gadget_init (GtkGadget *self); - * - define: static gpointer gtk_gadget_parent_class = NULL; - * gtk_gadget_parent_class is initialized prior to calling gtk_gadget_class_init() - * - implement: GType gtk_gadget_get_type (void) { ... } - * - support custom code in gtk_gadget_get_type() after the type is registered. - * - * macro arguments: TypeName, type_name, TYPE_PARENT, CODE - * example: G_DEFINE_TYPE_WITH_CODE (GtkGadget, gtk_gadget, GTK_TYPE_WIDGET, - * g_print ("GtkGadget-id: %lu\n", g_define_type_id)); - */ -#define G_DEFINE_TYPE( TN, t_n, T_P ) G_DEFINE_TYPE_EXTENDED( TN, t_n, T_P, 0, {} ) -#define G_DEFINE_TYPE_WITH_CODE( TN, t_n, T_P, _C_ ) G_DEFINE_TYPE_EXTENDED( TN, t_n, T_P, 0, _C_ ) -#define G_DEFINE_ABSTRACT_TYPE( TN, t_n, T_P ) G_DEFINE_TYPE_EXTENDED( TN, t_n, T_P, G_TYPE_FLAG_ABSTRACT, {} ) -#define G_DEFINE_ABSTRACT_TYPE_WITH_CODE( TN, t_n, T_P, _C_ ) G_DEFINE_TYPE_EXTENDED( TN, t_n, T_P, G_TYPE_FLAG_ABSTRACT, _C_ ) - -/* convenience macro to ease interface addition in the CODE - * section of G_DEFINE_TYPE_WITH_CODE() (this macro relies on - * the g_define_type_id present within G_DEFINE_TYPE_WITH_CODE()). - * usage example: - * G_DEFINE_TYPE_WITH_CODE (GtkTreeStore, gtk_tree_store, G_TYPE_OBJECT, - * G_IMPLEMENT_INTERFACE (GTK_TYPE_TREE_MODEL, - * gtk_tree_store_tree_model_init)); - */ -#define G_IMPLEMENT_INTERFACE( TYPE_IFACE, iface_init ) { \ - static const GInterfaceInfo g_implement_interface_info = { \ - (GInterfaceInitFunc) iface_init \ - }; \ - g_type_add_interface_static( g_define_type_id, TYPE_IFACE, &g_implement_interface_info ); \ -} - -#define G_DEFINE_TYPE_EXTENDED( TypeName, type_name, TYPE_PARENT, flags, CODE ) \ -\ - static void type_name ## _init( TypeName *self ); \ - static void type_name ## _class_init( TypeName ## Class *klass ); \ - static gpointer type_name ## _parent_class = NULL; \ - static void type_name ## _class_intern_init( gpointer klass ) \ - { \ - type_name ## _parent_class = g_type_class_peek_parent( klass ); \ - type_name ## _class_init( ( TypeName ## Class* ) klass ); \ - } \ -\ - GType \ - type_name ## _get_type( void ) \ - { \ - static GType g_define_type_id = 0; \ - if ( G_UNLIKELY( g_define_type_id == 0 ) ) \ - { \ - static const GTypeInfo g_define_type_info = { \ - sizeof( TypeName ## Class ), \ - (GBaseInitFunc) NULL, \ - (GBaseFinalizeFunc) NULL, \ - (GClassInitFunc) type_name ## _class_intern_init, \ - (GClassFinalizeFunc) NULL, \ - NULL, /* class_data */ \ - sizeof( TypeName ), \ - 0, /* n_preallocs */ \ - (GInstanceInitFunc) type_name ## _init, \ - NULL /* value_table */ \ - }; \ - g_define_type_id = g_type_register_static( TYPE_PARENT, # TypeName, &g_define_type_info, (GTypeFlags) flags ); \ - { CODE ; } \ - } \ - return g_define_type_id; \ - } - - -/* --- protected (for fundamental type implementations) --- */ -GTypePlugin* g_type_get_plugin( GType type ); -GTypePlugin* g_type_interface_get_plugin( GType instance_type, - GType interface_type ); -GType g_type_fundamental_next( void ); -GType g_type_fundamental( GType type_id ); -GTypeInstance* g_type_create_instance( GType type ); -void g_type_free_instance( GTypeInstance *instance ); - -void g_type_add_class_cache_func( gpointer cache_data, - GTypeClassCacheFunc cache_func ); -void g_type_remove_class_cache_func( gpointer cache_data, - GTypeClassCacheFunc cache_func ); -void g_type_class_unref_uncached( gpointer g_class ); - -void g_type_add_interface_check( gpointer check_data, - GTypeInterfaceCheckFunc check_func ); -void g_type_remove_interface_check( gpointer check_data, - GTypeInterfaceCheckFunc chec_func ); - -GTypeValueTable* g_type_value_table_peek( GType type ); - - -/*< private >*/ -gboolean g_type_check_instance( GTypeInstance *instance ); -GTypeInstance* g_type_check_instance_cast( GTypeInstance *instance, - GType iface_type ); -gboolean g_type_check_instance_is_a( GTypeInstance *instance, - GType iface_type ); -GTypeClass* g_type_check_class_cast( GTypeClass *g_class, - GType is_a_type ); -gboolean g_type_check_class_is_a( GTypeClass *g_class, - GType is_a_type ); -gboolean g_type_check_is_value_type( GType type ); -gboolean g_type_check_value( GValue *value ); -gboolean g_type_check_value_holds( GValue *value, - GType type ); -gboolean g_type_test_flags( GType type, - guint flags ); - - -/* --- debugging functions --- */ -G_CONST_RETURN gchar* g_type_name_from_instance( GTypeInstance *instance ); -G_CONST_RETURN gchar* g_type_name_from_class( GTypeClass *g_class ); - - -/* --- implementation bits --- */ -#ifndef G_DISABLE_CAST_CHECKS -# define _G_TYPE_CIC( ip, gt, ct ) \ - ( (ct*) g_type_check_instance_cast( (GTypeInstance*) ip, gt ) ) -# define _G_TYPE_CCC( cp, gt, ct ) \ - ( (ct*) g_type_check_class_cast( (GTypeClass*) cp, gt ) ) -#else /* G_DISABLE_CAST_CHECKS */ -# define _G_TYPE_CIC( ip, gt, ct ) ( (ct*) ip ) -# define _G_TYPE_CCC( cp, gt, ct ) ( (ct*) cp ) -#endif /* G_DISABLE_CAST_CHECKS */ -#define _G_TYPE_CHI( ip ) ( g_type_check_instance( (GTypeInstance*) ip ) ) -#define _G_TYPE_CHV( vl ) ( g_type_check_value( (GValue*) vl ) ) -#define _G_TYPE_IGC( ip, gt, ct ) ( (ct*) ( ( (GTypeInstance*) ip )->g_class ) ) -#define _G_TYPE_IGI( ip, gt, ct ) ( (ct*) g_type_interface_peek( ( (GTypeInstance*) ip )->g_class, gt ) ) -#ifdef __GNUC__ -# define _G_TYPE_CIT( ip, gt ) ( G_GNUC_EXTENSION( { \ - GTypeInstance *__inst = (GTypeInstance*) ip; GType __t = gt; gboolean __r; \ - if ( __inst && __inst->g_class && __inst->g_class->g_type == __t ) { \ - __r = TRUE; } \ - else{ \ - __r = g_type_check_instance_is_a( __inst, __t ); } \ - __r; \ - } ) ) -# define _G_TYPE_CCT( cp, gt ) ( G_GNUC_EXTENSION( { \ - GTypeClass *__class = (GTypeClass*) cp; GType __t = gt; gboolean __r; \ - if ( __class && __class->g_type == __t ) { \ - __r = TRUE; } \ - else{ \ - __r = g_type_check_class_is_a( __class, __t ); } \ - __r; \ - } ) ) -# define _G_TYPE_CVH( vl, gt ) ( G_GNUC_EXTENSION( { \ - GValue *__val = (GValue*) vl; GType __t = gt; gboolean __r; \ - if ( __val && __val->g_type == __t ) { \ - __r = TRUE; } \ - else{ \ - __r = g_type_check_value_holds( __val, __t ); } \ - __r; \ - } ) ) -#else /* !__GNUC__ */ -# define _G_TYPE_CIT( ip, gt ) ( g_type_check_instance_is_a( (GTypeInstance*) ip, gt ) ) -# define _G_TYPE_CCT( cp, gt ) ( g_type_check_class_is_a( (GTypeClass*) cp, gt ) ) -# define _G_TYPE_CVH( vl, gt ) ( g_type_check_value_holds( (GValue*) vl, gt ) ) -#endif /* !__GNUC__ */ -#define G_TYPE_FLAG_RESERVED_ID_BIT ( (GType) ( 1 << 0 ) ) -extern GTypeDebugFlags _g_type_debug_flags; - -G_END_DECLS - -#endif /* __G_TYPE_H__ */ diff --git a/tools/urt/tools/quake3/common/gobject/gtypemodule.h b/tools/urt/tools/quake3/common/gobject/gtypemodule.h deleted file mode 100644 index cd4a458..0000000 --- a/tools/urt/tools/quake3/common/gobject/gtypemodule.h +++ /dev/null @@ -1,85 +0,0 @@ -/* GObject - GLib Type, Object, Parameter and Signal Library - * Copyright (C) 2000 Red Hat, Inc. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the - * Free Software Foundation, Inc., 59 Temple Place - Suite 330, - * Boston, MA 02111-1307, USA. - */ -#if !defined ( __GLIB_GOBJECT_H_INSIDE__ ) && !defined ( GOBJECT_COMPILATION ) -#error "Only can be included directly." -#endif - -#ifndef __G_TYPE_MODULE_H__ -#define __G_TYPE_MODULE_H__ - -#include - -G_BEGIN_DECLS - -typedef struct _GTypeModule GTypeModule; -typedef struct _GTypeModuleClass GTypeModuleClass; - -#define G_TYPE_TYPE_MODULE ( g_type_module_get_type() ) -#define G_TYPE_MODULE( module ) ( G_TYPE_CHECK_INSTANCE_CAST( ( module ), G_TYPE_TYPE_MODULE, GTypeModule ) ) -#define G_TYPE_MODULE_CLASS( class ) ( G_TYPE_CHECK_CLASS_CAST( ( class ), G_TYPE_TYPE_MODULE, GTypeModuleClass ) ) -#define G_IS_TYPE_MODULE( module ) ( G_TYPE_CHECK_INSTANCE_TYPE( ( module ), G_TYPE_TYPE_MODULE ) ) -#define G_IS_TYPE_MODULE_CLASS( class ) ( G_TYPE_CHECK_CLASS_TYPE( ( class ), G_TYPE_TYPE_MODULE ) ) -#define G_TYPE_MODULE_GET_CLASS( module ) ( G_TYPE_INSTANCE_GET_CLASS( ( module ), G_TYPE_TYPE_MODULE, GTypeModuleClass ) ) - -struct _GTypeModule -{ - GObject parent_instance; - - guint use_count; - GSList *type_infos; - GSList *interface_infos; - - /*< public >*/ - gchar *name; -}; - -struct _GTypeModuleClass -{ - GObjectClass parent_class; - - /*< public >*/ - gboolean ( * load )( GTypeModule *module ); - void ( * unload )( GTypeModule *module ); - - /*< private >*/ - /* Padding for future expansion */ - void ( *reserved1 )( void ); - void ( *reserved2 )( void ); - void ( *reserved3 )( void ); - void ( *reserved4 )( void ); -}; - -GType g_type_module_get_type( void ); -gboolean g_type_module_use( GTypeModule *module ); -void g_type_module_unuse( GTypeModule *module ); -void g_type_module_set_name( GTypeModule *module, - const gchar *name ); -GType g_type_module_register_type( GTypeModule *module, - GType parent_type, - const gchar *type_name, - const GTypeInfo *type_info, - GTypeFlags flags ); -void g_type_module_add_interface( GTypeModule *module, - GType instance_type, - GType interface_type, - const GInterfaceInfo *interface_info ); - -G_END_DECLS - -#endif /* __G_TYPE_MODULE_H__ */ diff --git a/tools/urt/tools/quake3/common/gobject/gtypeplugin.h b/tools/urt/tools/quake3/common/gobject/gtypeplugin.h deleted file mode 100644 index 9372523..0000000 --- a/tools/urt/tools/quake3/common/gobject/gtypeplugin.h +++ /dev/null @@ -1,79 +0,0 @@ -/* GObject - GLib Type, Object, Parameter and Signal Library - * Copyright (C) 2000 Red Hat, Inc. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General - * Public License along with this library; if not, write to the - * Free Software Foundation, Inc., 59 Temple Place, Suite 330, - * Boston, MA 02111-1307, USA. - */ -#if !defined ( __GLIB_GOBJECT_H_INSIDE__ ) && !defined ( GOBJECT_COMPILATION ) -#error "Only can be included directly." -#endif - -#ifndef __G_TYPE_PLUGIN_H__ -#define __G_TYPE_PLUGIN_H__ - -#include - -G_BEGIN_DECLS - -/* --- type macros --- */ -#define G_TYPE_TYPE_PLUGIN ( g_type_plugin_get_type() ) -#define G_TYPE_PLUGIN( inst ) ( G_TYPE_CHECK_INSTANCE_CAST( ( inst ), G_TYPE_TYPE_PLUGIN, GTypePlugin ) ) -#define G_TYPE_PLUGIN_CLASS( vtable ) ( G_TYPE_CHECK_CLASS_CAST( ( vtable ), G_TYPE_TYPE_PLUGIN, GTypePluginClass ) ) -#define G_IS_TYPE_PLUGIN( inst ) ( G_TYPE_CHECK_INSTANCE_TYPE( ( inst ), G_TYPE_TYPE_PLUGIN ) ) -#define G_IS_TYPE_PLUGIN_CLASS( vtable ) ( G_TYPE_CHECK_CLASS_TYPE( ( vtable ), G_TYPE_TYPE_PLUGIN ) ) -#define G_TYPE_PLUGIN_GET_CLASS( inst ) ( G_TYPE_INSTANCE_GET_INTERFACE( ( inst ), G_TYPE_TYPE_PLUGIN, GTypePluginClass ) ) - - -/* --- typedefs & structures --- */ -typedef struct _GTypePluginClass GTypePluginClass; -typedef void ( *GTypePluginUse )( GTypePlugin *plugin ); -typedef void ( *GTypePluginUnuse )( GTypePlugin *plugin ); -typedef void ( *GTypePluginCompleteTypeInfo )( GTypePlugin *plugin, - GType g_type, - GTypeInfo *info, - GTypeValueTable *value_table ); -typedef void ( *GTypePluginCompleteInterfaceInfo )( GTypePlugin *plugin, - GType instance_type, - GType interface_type, - GInterfaceInfo *info ); -struct _GTypePluginClass -{ - /*< private >*/ - GTypeInterface base_iface; - - /*< public >*/ - GTypePluginUse use_plugin; - GTypePluginUnuse unuse_plugin; - GTypePluginCompleteTypeInfo complete_type_info; - GTypePluginCompleteInterfaceInfo complete_interface_info; -}; - - -/* --- prototypes --- */ -GType g_type_plugin_get_type( void ) G_GNUC_CONST; -void g_type_plugin_use( GTypePlugin *plugin ); -void g_type_plugin_unuse( GTypePlugin *plugin ); -void g_type_plugin_complete_type_info( GTypePlugin *plugin, - GType g_type, - GTypeInfo *info, - GTypeValueTable *value_table ); -void g_type_plugin_complete_interface_info( GTypePlugin *plugin, - GType instance_type, - GType interface_type, - GInterfaceInfo *info ); - -G_END_DECLS - -#endif /* __G_TYPE_PLUGIN_H__ */ diff --git a/tools/urt/tools/quake3/common/gobject/gvalue.h b/tools/urt/tools/quake3/common/gobject/gvalue.h deleted file mode 100644 index 8286522..0000000 --- a/tools/urt/tools/quake3/common/gobject/gvalue.h +++ /dev/null @@ -1,94 +0,0 @@ -/* GObject - GLib Type, Object, Parameter and Signal Library - * Copyright (C) 1997-1999, 2000-2001 Tim Janik and Red Hat, Inc. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General - * Public License along with this library; if not, write to the - * Free Software Foundation, Inc., 59 Temple Place, Suite 330, - * Boston, MA 02111-1307, USA. - * - * gvalue.h: generic GValue functions - */ -#if !defined ( __GLIB_GOBJECT_H_INSIDE__ ) && !defined ( GOBJECT_COMPILATION ) -#error "Only can be included directly." -#endif - -#ifndef __G_VALUE_H__ -#define __G_VALUE_H__ - -#include - -G_BEGIN_DECLS - -/* --- type macros --- */ -#define G_TYPE_IS_VALUE( type ) ( g_type_check_is_value_type( type ) ) -#define G_IS_VALUE( value ) ( G_TYPE_CHECK_VALUE( value ) ) -#define G_VALUE_TYPE( value ) ( ( (GValue*) ( value ) )->g_type ) -#define G_VALUE_TYPE_NAME( value ) ( g_type_name( G_VALUE_TYPE( value ) ) ) -#define G_VALUE_HOLDS( value,type ) ( G_TYPE_CHECK_VALUE_TYPE( ( value ), ( type ) ) ) - - -/* --- typedefs & structures --- */ -typedef void ( *GValueTransform )( const GValue *src_value, - GValue *dest_value ); -struct _GValue -{ - /*< private >*/ - GType g_type; - - /* public for GTypeValueTable methods */ - union { - gint v_int; - guint v_uint; - glong v_long; - gulong v_ulong; - gint64 v_int64; - guint64 v_uint64; - gfloat v_float; - gdouble v_double; - gpointer v_pointer; - } data[2]; -}; - - -/* --- prototypes --- */ -GValue* g_value_init( GValue *value, - GType g_type ); -void g_value_copy( const GValue *src_value, - GValue *dest_value ); -GValue* g_value_reset( GValue *value ); -void g_value_unset( GValue *value ); -void g_value_set_instance( GValue *value, - gpointer instance ); - - -/* --- private --- */ -gboolean g_value_fits_pointer( const GValue *value ); -gpointer g_value_peek_pointer( const GValue *value ); - - -/* --- implementation details --- */ -gboolean g_value_type_compatible( GType src_type, - GType dest_type ); -gboolean g_value_type_transformable( GType src_type, - GType dest_type ); -gboolean g_value_transform( const GValue *src_value, - GValue *dest_value ); -void g_value_register_transform_func( GType src_type, - GType dest_type, - GValueTransform transform_func ); -#define G_VALUE_NOCOPY_CONTENTS ( 1 << 27 ) - - -G_END_DECLS - -#endif /* __G_VALUE_H__ */ diff --git a/tools/urt/tools/quake3/common/gobject/gvaluearray.h b/tools/urt/tools/quake3/common/gobject/gvaluearray.h deleted file mode 100644 index 50beb18..0000000 --- a/tools/urt/tools/quake3/common/gobject/gvaluearray.h +++ /dev/null @@ -1,75 +0,0 @@ -/* GObject - GLib Type, Object, Parameter and Signal Library - * Copyright (C) 2001 Red Hat, Inc. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General - * Public License along with this library; if not, write to the - * Free Software Foundation, Inc., 59 Temple Place, Suite 330, - * Boston, MA 02111-1307, USA. - * - * gvaluearray.h: GLib array type holding GValues - */ -#if !defined ( __GLIB_GOBJECT_H_INSIDE__ ) && !defined ( GOBJECT_COMPILATION ) -#error "Only can be included directly." -#endif - -#ifndef __G_VALUE_ARRAY_H__ -#define __G_VALUE_ARRAY_H__ - -#include - - -#ifdef __cplusplus -extern "C" { -#endif /* __cplusplus */ - - -/* --- typedefs & structs --- */ -typedef struct _GValueArray GValueArray; -struct _GValueArray -{ - guint n_values; - GValue *values; - - /*< private >*/ - guint n_prealloced; -}; - - -/* --- prototypes --- */ -GValue* g_value_array_get_nth( GValueArray *value_array, - guint index_ ); -GValueArray* g_value_array_new( guint n_prealloced ); -void g_value_array_free( GValueArray *value_array ); -GValueArray* g_value_array_copy( const GValueArray *value_array ); -GValueArray* g_value_array_prepend( GValueArray *value_array, - const GValue *value ); -GValueArray* g_value_array_append( GValueArray *value_array, - const GValue *value ); -GValueArray* g_value_array_insert( GValueArray *value_array, - guint index_, - const GValue *value ); -GValueArray* g_value_array_remove( GValueArray *value_array, - guint index_ ); -GValueArray* g_value_array_sort( GValueArray *value_array, - GCompareFunc compare_func ); -GValueArray* g_value_array_sort_with_data( GValueArray *value_array, - GCompareDataFunc compare_func, - gpointer user_data ); - - - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#endif /* __G_VALUE_ARRAY_H__ */ diff --git a/tools/urt/tools/quake3/common/gobject/gvaluecollector.h b/tools/urt/tools/quake3/common/gobject/gvaluecollector.h deleted file mode 100644 index 2e83dc5..0000000 --- a/tools/urt/tools/quake3/common/gobject/gvaluecollector.h +++ /dev/null @@ -1,160 +0,0 @@ -/* GObject - GLib Type, Object, Parameter and Signal Library - * Copyright (C) 1998-1999, 2000-2001 Tim Janik and Red Hat, Inc. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General - * Public License along with this library; if not, write to the - * Free Software Foundation, Inc., 59 Temple Place, Suite 330, - * Boston, MA 02111-1307, USA. - * - * gvaluecollector.h: GValue varargs stubs - */ -#ifndef __G_VALUE_COLLECTOR_H__ -#define __G_VALUE_COLLECTOR_H__ - -#include - -G_BEGIN_DECLS - -/* we may want to add aggregate types here some day, if requested - * by users. the basic C types are covered already, everything - * smaller than an int is promoted to an integer and floats are - * always promoted to doubles for varargs call constructions. - */ -enum /*< skip >*/ -{ - G_VALUE_COLLECT_INT = 'i', - G_VALUE_COLLECT_LONG = 'l', - G_VALUE_COLLECT_INT64 = 'q', - G_VALUE_COLLECT_DOUBLE = 'd', - G_VALUE_COLLECT_POINTER = 'p' -}; - - -/* vararg union holding actuall values collected - */ -union _GTypeCValue -{ - gint v_int; - glong v_long; - gint64 v_int64; - gdouble v_double; - gpointer v_pointer; -}; - - -/* G_VALUE_COLLECT() collects a variable argument value - * from a va_list. we have to implement the varargs collection as a - * macro, because on some systems va_list variables cannot be passed - * by reference. - * value is supposed to be initialized according to the value - * type to be collected. - * var_args is the va_list variable and may be evaluated multiple times. - * __error is a gchar** variable that will be modified to hold a g_new() - * allocated error messages if something fails. - */ -#define G_VALUE_COLLECT( value, var_args, flags, __error ) \ - G_STMT_START { \ - GValue *_value = ( value ); \ - guint _flags = ( flags ); \ - GType _value_type = G_VALUE_TYPE( _value ); \ - GTypeValueTable *_vtable = g_type_value_table_peek( _value_type ); \ - gchar *_collect_format = _vtable->collect_format; \ - GTypeCValue _cvalues[G_VALUE_COLLECT_FORMAT_MAX_LENGTH] = { { 0, }, }; \ - guint _n_values = 0; \ - \ - if ( _vtable->value_free ) { \ - _vtable->value_free( _value ); } \ - _value->g_type = _value_type; /* value_meminit() from gvalue.c */ \ - memset( _value->data, 0, sizeof( _value->data ) ); \ - while ( *_collect_format ) \ - { \ - GTypeCValue *_cvalue = _cvalues + _n_values++; \ - \ - switch ( *_collect_format++ ) \ - { \ - case G_VALUE_COLLECT_INT: \ - _cvalue->v_int = va_arg( ( var_args ), gint ); \ - break; \ - case G_VALUE_COLLECT_LONG: \ - _cvalue->v_long = va_arg( ( var_args ), glong ); \ - break; \ - case G_VALUE_COLLECT_INT64: \ - _cvalue->v_int64 = va_arg( ( var_args ), gint64 ); \ - break; \ - case G_VALUE_COLLECT_DOUBLE: \ - _cvalue->v_double = va_arg( ( var_args ), gdouble ); \ - break; \ - case G_VALUE_COLLECT_POINTER: \ - _cvalue->v_pointer = va_arg( ( var_args ), gpointer ); \ - break; \ - default: \ - g_assert_not_reached(); \ - } \ - } \ - *( __error ) = _vtable->collect_value( _value, \ - _n_values, \ - _cvalues, \ - _flags ); \ - } G_STMT_END - - -/* G_VALUE_LCOPY() collects a value's variable argument - * locations from a va_list. usage is analogous to G_VALUE_COLLECT(). - */ -#define G_VALUE_LCOPY( value, var_args, flags, __error ) \ - G_STMT_START { \ - const GValue *_value = ( value ); \ - guint _flags = ( flags ); \ - GType _value_type = G_VALUE_TYPE( _value ); \ - GTypeValueTable *_vtable = g_type_value_table_peek( _value_type ); \ - gchar *_lcopy_format = _vtable->lcopy_format; \ - GTypeCValue _cvalues[G_VALUE_COLLECT_FORMAT_MAX_LENGTH] = { { 0, }, }; \ - guint _n_values = 0; \ - \ - while ( *_lcopy_format ) \ - { \ - GTypeCValue *_cvalue = _cvalues + _n_values++; \ - \ - switch ( *_lcopy_format++ ) \ - { \ - case G_VALUE_COLLECT_INT: \ - _cvalue->v_int = va_arg( ( var_args ), gint ); \ - break; \ - case G_VALUE_COLLECT_LONG: \ - _cvalue->v_long = va_arg( ( var_args ), glong ); \ - break; \ - case G_VALUE_COLLECT_INT64: \ - _cvalue->v_int64 = va_arg( ( var_args ), gint64 ); \ - break; \ - case G_VALUE_COLLECT_DOUBLE: \ - _cvalue->v_double = va_arg( ( var_args ), gdouble ); \ - break; \ - case G_VALUE_COLLECT_POINTER: \ - _cvalue->v_pointer = va_arg( ( var_args ), gpointer ); \ - break; \ - default: \ - g_assert_not_reached(); \ - } \ - } \ - *( __error ) = _vtable->lcopy_value( _value, \ - _n_values, \ - _cvalues, \ - _flags ); \ - } G_STMT_END - - -#define G_VALUE_COLLECT_FORMAT_MAX_LENGTH ( 8 ) - -G_END_DECLS - -#endif /* __G_VALUE_COLLECTOR_H__ */ diff --git a/tools/urt/tools/quake3/common/gobject/gvaluetypes.h b/tools/urt/tools/quake3/common/gobject/gvaluetypes.h deleted file mode 100644 index 68fe183..0000000 --- a/tools/urt/tools/quake3/common/gobject/gvaluetypes.h +++ /dev/null @@ -1,114 +0,0 @@ -/* GObject - GLib Type, Object, Parameter and Signal Library - * Copyright (C) 1997-1999, 2000-2001 Tim Janik and Red Hat, Inc. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General - * Public License along with this library; if not, write to the - * Free Software Foundation, Inc., 59 Temple Place, Suite 330, - * Boston, MA 02111-1307, USA. - * - * gvaluetypes.h: GLib default values - */ -#if !defined ( __GLIB_GOBJECT_H_INSIDE__ ) && !defined ( GOBJECT_COMPILATION ) -#error "Only can be included directly." -#endif - -#ifndef __G_VALUETYPES_H__ -#define __G_VALUETYPES_H__ - -#include - -G_BEGIN_DECLS - -/* --- type macros --- */ -#define G_VALUE_HOLDS_CHAR( value ) ( G_TYPE_CHECK_VALUE_TYPE( ( value ), G_TYPE_CHAR ) ) -#define G_VALUE_HOLDS_UCHAR( value ) ( G_TYPE_CHECK_VALUE_TYPE( ( value ), G_TYPE_UCHAR ) ) -#define G_VALUE_HOLDS_BOOLEAN( value ) ( G_TYPE_CHECK_VALUE_TYPE( ( value ), G_TYPE_BOOLEAN ) ) -#define G_VALUE_HOLDS_INT( value ) ( G_TYPE_CHECK_VALUE_TYPE( ( value ), G_TYPE_INT ) ) -#define G_VALUE_HOLDS_UINT( value ) ( G_TYPE_CHECK_VALUE_TYPE( ( value ), G_TYPE_UINT ) ) -#define G_VALUE_HOLDS_LONG( value ) ( G_TYPE_CHECK_VALUE_TYPE( ( value ), G_TYPE_LONG ) ) -#define G_VALUE_HOLDS_ULONG( value ) ( G_TYPE_CHECK_VALUE_TYPE( ( value ), G_TYPE_ULONG ) ) -#define G_VALUE_HOLDS_INT64( value ) ( G_TYPE_CHECK_VALUE_TYPE( ( value ), G_TYPE_INT64 ) ) -#define G_VALUE_HOLDS_UINT64( value ) ( G_TYPE_CHECK_VALUE_TYPE( ( value ), G_TYPE_UINT64 ) ) -#define G_VALUE_HOLDS_FLOAT( value ) ( G_TYPE_CHECK_VALUE_TYPE( ( value ), G_TYPE_FLOAT ) ) -#define G_VALUE_HOLDS_DOUBLE( value ) ( G_TYPE_CHECK_VALUE_TYPE( ( value ), G_TYPE_DOUBLE ) ) -#define G_VALUE_HOLDS_STRING( value ) ( G_TYPE_CHECK_VALUE_TYPE( ( value ), G_TYPE_STRING ) ) -#define G_VALUE_HOLDS_POINTER( value ) ( G_TYPE_CHECK_VALUE_TYPE( ( value ), G_TYPE_POINTER ) ) - - -/* --- prototypes --- */ -void g_value_set_char( GValue *value, - gchar v_char ); -gchar g_value_get_char( const GValue *value ); -void g_value_set_uchar( GValue *value, - guchar v_uchar ); -guchar g_value_get_uchar( const GValue *value ); -void g_value_set_boolean( GValue *value, - gboolean v_boolean ); -gboolean g_value_get_boolean( const GValue *value ); -void g_value_set_int( GValue *value, - gint v_int ); -gint g_value_get_int( const GValue *value ); -void g_value_set_uint( GValue *value, - guint v_uint ); -guint g_value_get_uint( const GValue *value ); -void g_value_set_long( GValue *value, - glong v_long ); -glong g_value_get_long( const GValue *value ); -void g_value_set_ulong( GValue *value, - gulong v_ulong ); -gulong g_value_get_ulong( const GValue *value ); -void g_value_set_int64( GValue *value, - gint64 v_int64 ); -gint64 g_value_get_int64( const GValue *value ); -void g_value_set_uint64( GValue *value, - guint64 v_uint64 ); -guint64 g_value_get_uint64( const GValue *value ); -void g_value_set_float( GValue *value, - gfloat v_float ); -gfloat g_value_get_float( const GValue *value ); -void g_value_set_double( GValue *value, - gdouble v_double ); -gdouble g_value_get_double( const GValue *value ); -void g_value_set_string( GValue *value, - const gchar *v_string ); -void g_value_set_static_string( GValue *value, - const gchar *v_string ); -G_CONST_RETURN gchar* g_value_get_string( const GValue *value ); -gchar* g_value_dup_string( const GValue *value ); -void g_value_set_pointer( GValue *value, - gpointer v_pointer ); -gpointer g_value_get_pointer( const GValue *value ); - - -/* Convenience for registering new pointer types */ -GType g_pointer_type_register_static( const gchar *name ); - -/* debugging aid, describe value contents as string */ -gchar* g_strdup_value_contents( const GValue *value ); - - -void g_value_take_string( GValue *value, - gchar *v_string ); -#ifndef G_DISABLE_DEPRECATED -void g_value_set_string_take_ownership( GValue *value, - gchar *v_string ); -#endif - - -/* humpf, need a C representable type name for G_TYPE_STRING */ -typedef gchar* gchararray; - - -G_END_DECLS - -#endif /* __G_VALUETYPES_H__ */ diff --git a/tools/urt/tools/quake3/common/imagelib.c b/tools/urt/tools/quake3/common/imagelib.c deleted file mode 100644 index 06e7433..0000000 --- a/tools/urt/tools/quake3/common/imagelib.c +++ /dev/null @@ -1,1220 +0,0 @@ -/* - Copyright (C) 1999-2007 id Software, Inc. and contributors. - For a list of contributors, see the accompanying CONTRIBUTORS file. - - This file is part of GtkRadiant. - - GtkRadiant is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - GtkRadiant is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with GtkRadiant; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - */ - -// imagelib.c - -#include "cmdlib.h" -#include "imagelib.h" -#include "vfs.h" - -int fgetLittleShort( FILE *f ){ - byte b1, b2; - - b1 = fgetc( f ); - b2 = fgetc( f ); - - return (short)( b1 + b2 * 256 ); -} - -int fgetLittleLong( FILE *f ){ - byte b1, b2, b3, b4; - - b1 = fgetc( f ); - b2 = fgetc( f ); - b3 = fgetc( f ); - b4 = fgetc( f ); - - return b1 + ( b2 << 8 ) + ( b3 << 16 ) + ( b4 << 24 ); -} - -int bufLittleShort( byte *buf, int len, int *pos ){ - byte b1, b2; - - if ( ( len - *pos ) < 2 ) { - Error( "Unexpected buffer end" ); - } - - b1 = buf[*pos]; *pos += 1; - b2 = buf[*pos]; *pos += 1; - - return (short)( b1 + b2 * 256 ); -} - -int bufLittleLong( byte *buf, int len, int *pos ){ - byte b1, b2, b3, b4; - - if ( ( len - *pos ) < 4 ) { - Error( "Unexpected buffer end" ); - } - - b1 = buf[*pos]; *pos += 1; - b2 = buf[*pos]; *pos += 1; - b3 = buf[*pos]; *pos += 1; - b4 = buf[*pos]; *pos += 1; - - return b1 + ( b2 << 8 ) + ( b3 << 16 ) + ( b4 << 24 ); -} - - -/* - ============================================================================ - - LBM STUFF - - ============================================================================ - */ - - -typedef unsigned char UBYTE; -//conflicts with windows typedef short WORD; -typedef unsigned short UWORD; -typedef long LONG; - -typedef enum -{ - ms_none, - ms_mask, - ms_transcolor, - ms_lasso -} mask_t; - -typedef enum -{ - cm_none, - cm_rle1 -} compress_t; - -typedef struct -{ - UWORD w,h; - short x,y; - UBYTE nPlanes; - UBYTE masking; - UBYTE compression; - UBYTE pad1; - UWORD transparentColor; - UBYTE xAspect,yAspect; - short pageWidth,pageHeight; -} bmhd_t; - -extern bmhd_t bmhd; // will be in native byte order - - - -#define FORMID ( 'F' + ( 'O' << 8 ) + ( (int)'R' << 16 ) + ( (int)'M' << 24 ) ) -#define ILBMID ( 'I' + ( 'L' << 8 ) + ( (int)'B' << 16 ) + ( (int)'M' << 24 ) ) -#define PBMID ( 'P' + ( 'B' << 8 ) + ( (int)'M' << 16 ) + ( (int)' ' << 24 ) ) -#define BMHDID ( 'B' + ( 'M' << 8 ) + ( (int)'H' << 16 ) + ( (int)'D' << 24 ) ) -#define BODYID ( 'B' + ( 'O' << 8 ) + ( (int)'D' << 16 ) + ( (int)'Y' << 24 ) ) -#define CMAPID ( 'C' + ( 'M' << 8 ) + ( (int)'A' << 16 ) + ( (int)'P' << 24 ) ) - - -bmhd_t bmhd; - -int Align( int l ){ - if ( l & 1 ) { - return l + 1; - } - return l; -} - - - -/* - ================ - LBMRLEdecompress - - Source must be evenly aligned! - ================ - */ -byte *LBMRLEDecompress( byte *source,byte *unpacked, int bpwidth ){ - int count; - byte b,rept; - - count = 0; - - do - { - rept = *source++; - - if ( rept > 0x80 ) { - rept = ( rept ^ 0xff ) + 2; - b = *source++; - memset( unpacked,b,rept ); - unpacked += rept; - } - else if ( rept < 0x80 ) { - rept++; - memcpy( unpacked,source,rept ); - unpacked += rept; - source += rept; - } - else{ - rept = 0; // rept of 0x80 is NOP - - } - count += rept; - - } while ( count < bpwidth ); - - if ( count > bpwidth ) { - Error( "Decompression exceeded width!\n" ); - } - - - return source; -} - - -/* - ================= - LoadLBM - ================= - */ -void LoadLBM( const char *filename, byte **picture, byte **palette ){ - byte *LBMbuffer, *picbuffer, *cmapbuffer; - int y; - byte *LBM_P, *LBMEND_P; - byte *pic_p; - byte *body_p; - - int formtype,formlength; - int chunktype,chunklength; - -// qiet compiler warnings - picbuffer = NULL; - cmapbuffer = NULL; - -// -// load the LBM -// - LoadFile( filename, (void **)&LBMbuffer ); - -// -// parse the LBM header -// - LBM_P = LBMbuffer; - if ( *(int *)LBMbuffer != LittleLong( FORMID ) ) { - Error( "No FORM ID at start of file!\n" ); - } - - LBM_P += 4; - formlength = BigLong( *(int *)LBM_P ); - LBM_P += 4; - LBMEND_P = LBM_P + Align( formlength ); - - formtype = LittleLong( *(int *)LBM_P ); - - if ( formtype != ILBMID && formtype != PBMID ) { - Error( "Unrecognized form type: %c%c%c%c\n", formtype & 0xff - ,( formtype >> 8 ) & 0xff,( formtype >> 16 ) & 0xff,( formtype >> 24 ) & 0xff ); - } - - LBM_P += 4; - -// -// parse chunks -// - - while ( LBM_P < LBMEND_P ) - { - chunktype = LBM_P[0] + ( LBM_P[1] << 8 ) + ( LBM_P[2] << 16 ) + ( LBM_P[3] << 24 ); - LBM_P += 4; - chunklength = LBM_P[3] + ( LBM_P[2] << 8 ) + ( LBM_P[1] << 16 ) + ( LBM_P[0] << 24 ); - LBM_P += 4; - - switch ( chunktype ) - { - case BMHDID: - memcpy( &bmhd,LBM_P,sizeof( bmhd ) ); - bmhd.w = BigShort( bmhd.w ); - bmhd.h = BigShort( bmhd.h ); - bmhd.x = BigShort( bmhd.x ); - bmhd.y = BigShort( bmhd.y ); - bmhd.pageWidth = BigShort( bmhd.pageWidth ); - bmhd.pageHeight = BigShort( bmhd.pageHeight ); - break; - - case CMAPID: - cmapbuffer = safe_malloc( 768 ); - memset( cmapbuffer, 0, 768 ); - memcpy( cmapbuffer, LBM_P, chunklength ); - break; - - case BODYID: - body_p = LBM_P; - - pic_p = picbuffer = safe_malloc( bmhd.w * bmhd.h ); - if ( formtype == PBMID ) { - // - // unpack PBM - // - for ( y = 0 ; y < bmhd.h ; y++, pic_p += bmhd.w ) - { - if ( bmhd.compression == cm_rle1 ) { - body_p = LBMRLEDecompress( (byte *)body_p - , pic_p, bmhd.w ); - } - else if ( bmhd.compression == cm_none ) { - memcpy( pic_p,body_p,bmhd.w ); - body_p += Align( bmhd.w ); - } - } - - } - else - { - // - // unpack ILBM - // - Error( "%s is an interlaced LBM, not packed", filename ); - } - break; - } - - LBM_P += Align( chunklength ); - } - - free( LBMbuffer ); - - *picture = picbuffer; - - if ( palette ) { - *palette = cmapbuffer; - } -} - - -/* - ============================================================================ - - WRITE LBM - - ============================================================================ - */ - -/* - ============== - WriteLBMfile - ============== - */ -void WriteLBMfile( const char *filename, byte *data, - int width, int height, byte *palette ){ - byte *lbm, *lbmptr; - int *formlength, *bmhdlength, *cmaplength, *bodylength; - int length; - bmhd_t basebmhd; - - lbm = lbmptr = safe_malloc( width * height + 1000 ); - -// -// start FORM -// - *lbmptr++ = 'F'; - *lbmptr++ = 'O'; - *lbmptr++ = 'R'; - *lbmptr++ = 'M'; - - formlength = (int*)lbmptr; - lbmptr += 4; // leave space for length - - *lbmptr++ = 'P'; - *lbmptr++ = 'B'; - *lbmptr++ = 'M'; - *lbmptr++ = ' '; - -// -// write BMHD -// - *lbmptr++ = 'B'; - *lbmptr++ = 'M'; - *lbmptr++ = 'H'; - *lbmptr++ = 'D'; - - bmhdlength = (int *)lbmptr; - lbmptr += 4; // leave space for length - - memset( &basebmhd,0,sizeof( basebmhd ) ); - basebmhd.w = BigShort( (short)width ); - basebmhd.h = BigShort( (short)height ); - basebmhd.nPlanes = BigShort( 8 ); - basebmhd.xAspect = BigShort( 5 ); - basebmhd.yAspect = BigShort( 6 ); - basebmhd.pageWidth = BigShort( (short)width ); - basebmhd.pageHeight = BigShort( (short)height ); - - memcpy( lbmptr,&basebmhd,sizeof( basebmhd ) ); - lbmptr += sizeof( basebmhd ); - - length = lbmptr - (byte *)bmhdlength - 4; - *bmhdlength = BigLong( length ); - if ( length & 1 ) { - *lbmptr++ = 0; // pad chunk to even offset - - } -// -// write CMAP -// - *lbmptr++ = 'C'; - *lbmptr++ = 'M'; - *lbmptr++ = 'A'; - *lbmptr++ = 'P'; - - cmaplength = (int *)lbmptr; - lbmptr += 4; // leave space for length - - memcpy( lbmptr,palette,768 ); - lbmptr += 768; - - length = lbmptr - (byte *)cmaplength - 4; - *cmaplength = BigLong( length ); - if ( length & 1 ) { - *lbmptr++ = 0; // pad chunk to even offset - - } -// -// write BODY -// - *lbmptr++ = 'B'; - *lbmptr++ = 'O'; - *lbmptr++ = 'D'; - *lbmptr++ = 'Y'; - - bodylength = (int *)lbmptr; - lbmptr += 4; // leave space for length - - memcpy( lbmptr,data,width * height ); - lbmptr += width * height; - - length = lbmptr - (byte *)bodylength - 4; - *bodylength = BigLong( length ); - if ( length & 1 ) { - *lbmptr++ = 0; // pad chunk to even offset - - } -// -// done -// - length = lbmptr - (byte *)formlength - 4; - *formlength = BigLong( length ); - if ( length & 1 ) { - *lbmptr++ = 0; // pad chunk to even offset - - } -// -// write output file -// - SaveFile( filename, lbm, lbmptr - lbm ); - free( lbm ); -} - - -/* - ============================================================================ - - LOAD PCX - - ============================================================================ - */ - -typedef struct -{ - char manufacturer; - char version; - char encoding; - char bits_per_pixel; - unsigned short xmin,ymin,xmax,ymax; - unsigned short hres,vres; - unsigned char palette[48]; - char reserved; - char color_planes; - unsigned short bytes_per_line; - unsigned short palette_type; - char filler[58]; - unsigned char data; // unbounded -} pcx_t; - - -/* - ============== - LoadPCX - ============== - */ - -/* RR2DO2 */ -#define DECODEPCX( b, d, r ) d = *b++; if ( ( d & 0xC0 ) == 0xC0 ) {r = d & 0x3F; d = *b++; }else{r = 1; } - -void LoadPCX( const char *filename, byte **pic, byte **palette, int *width, int *height ){ - byte *raw; - pcx_t *pcx; - int x, y, lsize; - int len; - int dataByte, runLength; - byte *out, *pix; - - - /* load the file */ - len = vfsLoadFile( filename, (void **)&raw, 0 ); - if ( len == -1 ) { - Error( "LoadPCX: Couldn't read %s", filename ); - } - - - /* parse the PCX file */ - pcx = (pcx_t *)raw; - raw = &pcx->data; - - pcx->xmin = LittleShort( pcx->xmin ); - pcx->ymin = LittleShort( pcx->ymin ); - pcx->xmax = LittleShort( pcx->xmax ); - pcx->ymax = LittleShort( pcx->ymax ); - pcx->hres = LittleShort( pcx->hres ); - pcx->vres = LittleShort( pcx->vres ); - pcx->bytes_per_line = LittleShort( pcx->bytes_per_line ); - pcx->palette_type = LittleShort( pcx->palette_type ); - - if ( pcx->manufacturer != 0x0a - || pcx->version != 5 - || pcx->encoding != 1 - || pcx->bits_per_pixel != 8 - || pcx->xmax >= 640 - || pcx->ymax >= 480 ) { - Error( "Bad pcx file %s", filename ); - } - - if ( palette ) { - *palette = safe_malloc( 768 ); - memcpy( *palette, (byte *)pcx + len - 768, 768 ); - } - - if ( width ) { - *width = pcx->xmax + 1; - } - if ( height ) { - *height = pcx->ymax + 1; - } - - if ( !pic ) { - return; - } - - out = safe_malloc( ( pcx->ymax + 1 ) * ( pcx->xmax + 1 ) ); - if ( !out ) { - Error( "LoadPCX: couldn't allocate" ); - } - - *pic = out; - pix = out; - - /* RR2DO2: pcx fix */ - lsize = pcx->color_planes * pcx->bytes_per_line; - - /* go scanline by scanline */ - for ( y = 0; y <= pcx->ymax; y++, pix += pcx->xmax + 1 ) - { - /* do a scanline */ - for ( x = 0; x <= pcx->xmax; ) - { - /* RR2DO2 */ - DECODEPCX( raw, dataByte, runLength ); - while ( runLength-- > 0 ) - pix[ x++ ] = dataByte; - } - - /* RR2DO2: discard any other data */ - while ( x < lsize ) - { - DECODEPCX( raw, dataByte, runLength ); - x++; - } - while ( runLength-- > 0 ) - x++; - } - - /* validity check */ - if ( raw - (byte *) pcx > len ) { - Error( "PCX file %s was malformed", filename ); - } - free( pcx ); -} - - - -/* - ============== - WritePCXfile - ============== - */ -void WritePCXfile( const char *filename, byte *data, - int width, int height, byte *palette ){ - int i, j, length; - pcx_t *pcx; - byte *pack; - - pcx = safe_malloc( width * height * 2 + 1000 ); - memset( pcx, 0, sizeof( *pcx ) ); - - pcx->manufacturer = 0x0a; // PCX id - pcx->version = 5; // 256 color - pcx->encoding = 1; // uncompressed - pcx->bits_per_pixel = 8; // 256 color - pcx->xmin = 0; - pcx->ymin = 0; - pcx->xmax = LittleShort( (short)( width - 1 ) ); - pcx->ymax = LittleShort( (short)( height - 1 ) ); - pcx->hres = LittleShort( (short)width ); - pcx->vres = LittleShort( (short)height ); - pcx->color_planes = 1; // chunky image - pcx->bytes_per_line = LittleShort( (short)width ); - pcx->palette_type = LittleShort( 1 ); // not a grey scale - - // pack the image - pack = &pcx->data; - - for ( i = 0 ; i < height ; i++ ) - { - for ( j = 0 ; j < width ; j++ ) - { - if ( ( *data & 0xc0 ) != 0xc0 ) { - *pack++ = *data++; - } - else - { - *pack++ = 0xc1; - *pack++ = *data++; - } - } - } - - // write the palette - *pack++ = 0x0c; // palette ID byte - for ( i = 0 ; i < 768 ; i++ ) - *pack++ = *palette++; - -// write output file - length = pack - (byte *)pcx; - SaveFile( filename, pcx, length ); - - free( pcx ); -} - -/* - ============================================================================ - - LOAD BMP - - ============================================================================ - */ - - -/* - - // we can't just use these structures, because - // compiler structure alignment will not be portable - // on this unaligned stuff - - typedef struct tagBITMAPFILEHEADER { // bmfh - WORD bfType; // BM - DWORD bfSize; - WORD bfReserved1; - WORD bfReserved2; - DWORD bfOffBits; - } BITMAPFILEHEADER; - - typedef struct tagBITMAPINFOHEADER{ // bmih - DWORD biSize; - LONG biWidth; - LONG biHeight; - WORD biPlanes; - WORD biBitCount - DWORD biCompression; - DWORD biSizeImage; - LONG biXPelsPerMeter; - LONG biYPelsPerMeter; - DWORD biClrUsed; - DWORD biClrImportant; - } BITMAPINFOHEADER; - - typedef struct tagBITMAPINFO { // bmi - BITMAPINFOHEADER bmiHeader; - RGBQUAD bmiColors[1]; - } BITMAPINFO; - - typedef struct tagBITMAPCOREHEADER { // bmch - DWORD bcSize; - WORD bcWidth; - WORD bcHeight; - WORD bcPlanes; - WORD bcBitCount; - } BITMAPCOREHEADER; - - typedef struct _BITMAPCOREINFO { // bmci - BITMAPCOREHEADER bmciHeader; - RGBTRIPLE bmciColors[1]; - } BITMAPCOREINFO; - - */ - -/* - ============== - LoadBMP - ============== - */ -void LoadBMP( const char *filename, byte **pic, byte **palette, int *width, int *height ){ - byte *out; - int i; - int bfSize; - int bfOffBits; - int structSize; - int bcWidth; - int bcHeight; - int bcPlanes; - int bcBitCount; - byte bcPalette[1024]; - qboolean flipped; - byte *in; - int len, pos = 0; - - len = vfsLoadFile( filename, (void **)&in, 0 ); - if ( len == -1 ) { - Error( "Couldn't read %s", filename ); - } - - i = bufLittleShort( in, len, &pos ); - if ( i != 'B' + ( 'M' << 8 ) ) { - Error( "%s is not a bmp file", filename ); - } - - bfSize = bufLittleLong( in, len, &pos ); - bufLittleShort( in, len, &pos ); - bufLittleShort( in, len, &pos ); - bfOffBits = bufLittleLong( in, len, &pos ); - - // the size will tell us if it is a - // bitmapinfo or a bitmapcore - structSize = bufLittleLong( in, len, &pos ); - if ( structSize == 40 ) { - // bitmapinfo - bcWidth = bufLittleLong( in, len, &pos ); - bcHeight = bufLittleLong( in, len, &pos ); - bcPlanes = bufLittleShort( in, len, &pos ); - bcBitCount = bufLittleShort( in, len, &pos ); - - pos += 24; - - if ( palette ) { - memcpy( bcPalette, in + pos, 1024 ); - pos += 1024; - *palette = safe_malloc( 768 ); - - for ( i = 0 ; i < 256 ; i++ ) - { - ( *palette )[i * 3 + 0] = bcPalette[i * 4 + 2]; - ( *palette )[i * 3 + 1] = bcPalette[i * 4 + 1]; - ( *palette )[i * 3 + 2] = bcPalette[i * 4 + 0]; - } - } - } - else if ( structSize == 12 ) { - // bitmapcore - bcWidth = bufLittleShort( in, len, &pos ); - bcHeight = bufLittleShort( in, len, &pos ); - bcPlanes = bufLittleShort( in, len, &pos ); - bcBitCount = bufLittleShort( in, len, &pos ); - - if ( palette ) { - memcpy( bcPalette, in + pos, 768 ); - pos += 768; - *palette = safe_malloc( 768 ); - - for ( i = 0 ; i < 256 ; i++ ) { - ( *palette )[i * 3 + 0] = bcPalette[i * 3 + 2]; - ( *palette )[i * 3 + 1] = bcPalette[i * 3 + 1]; - ( *palette )[i * 3 + 2] = bcPalette[i * 3 + 0]; - } - } - } - else { - Error( "%s had strange struct size", filename ); - } - - if ( bcPlanes != 1 ) { - Error( "%s was not a single plane image", filename ); - } - - if ( bcBitCount != 8 ) { - Error( "%s was not an 8 bit image", filename ); - } - - if ( bcHeight < 0 ) { - bcHeight = -bcHeight; - flipped = qtrue; - } - else { - flipped = qfalse; - } - - if ( width ) { - *width = bcWidth; - } - if ( height ) { - *height = bcHeight; - } - - if ( !pic ) { - free( in ); - return; - } - - out = safe_malloc( bcWidth * bcHeight ); - *pic = out; - pos = bfOffBits; - - if ( flipped ) { - for ( i = 0 ; i < bcHeight ; i++ ) { - memcpy( out + bcWidth * ( bcHeight - 1 - i ), in + pos, bcWidth ); - pos += bcWidth; - } - } - else { - memcpy( out, in + pos, bcWidth * bcHeight ); - pos += bcWidth * bcHeight; - } - - free( in ); -} - - -/* - ============================================================================ - - LOAD IMAGE - - ============================================================================ - */ - -/* - ============== - Load256Image - - Will load either an lbm or pcx, depending on extension. - Any of the return pointers can be NULL if you don't want them. - ============== - */ -void Load256Image( const char *name, byte **pixels, byte **palette, int *width, int *height ){ - char ext[128]; - - ExtractFileExtension( name, ext ); - if ( !Q_stricmp( ext, "lbm" ) ) { - LoadLBM( name, pixels, palette ); - if ( width ) { - *width = bmhd.w; - } - if ( height ) { - *height = bmhd.h; - } - } - else if ( !Q_stricmp( ext, "pcx" ) ) { - LoadPCX( name, pixels, palette, width, height ); - } - else if ( !Q_stricmp( ext, "bmp" ) ) { - LoadBMP( name, pixels, palette, width, height ); - } - else{ - Error( "%s doesn't have a known image extension", name ); - } -} - - -/* - ============== - Save256Image - - Will save either an lbm or pcx, depending on extension. - ============== - */ -void Save256Image( const char *name, byte *pixels, byte *palette, - int width, int height ){ - char ext[128]; - - ExtractFileExtension( name, ext ); - if ( !Q_stricmp( ext, "lbm" ) ) { - WriteLBMfile( name, pixels, width, height, palette ); - } - else if ( !Q_stricmp( ext, "pcx" ) ) { - WritePCXfile( name, pixels, width, height, palette ); - } - else{ - Error( "%s doesn't have a known image extension", name ); - } -} - - - - -/* - ============================================================================ - - TARGA IMAGE - - ============================================================================ - */ - -typedef struct _TargaHeader { - unsigned char id_length, colormap_type, image_type; - unsigned short colormap_index, colormap_length; - unsigned char colormap_size; - unsigned short x_origin, y_origin, width, height; - unsigned char pixel_size, attributes; -} TargaHeader; - -/* - ============= - LoadTGABuffer - ============= - */ -void LoadTGABuffer( byte *buffer, byte **pic, int *width, int *height ){ - int columns, rows, numPixels; - byte *pixbuf; - int row, column; - byte *buf_p; - TargaHeader targa_header; - byte *targa_rgba; - - *pic = NULL; - - buf_p = buffer; - - targa_header.id_length = *buf_p++; - targa_header.colormap_type = *buf_p++; - targa_header.image_type = *buf_p++; - - targa_header.colormap_index = LittleShort( *(short *)buf_p ); - buf_p += 2; - targa_header.colormap_length = LittleShort( *(short *)buf_p ); - buf_p += 2; - targa_header.colormap_size = *buf_p++; - targa_header.x_origin = LittleShort( *(short *)buf_p ); - buf_p += 2; - targa_header.y_origin = LittleShort( *(short *)buf_p ); - buf_p += 2; - targa_header.width = LittleShort( *(short *)buf_p ); - buf_p += 2; - targa_header.height = LittleShort( *(short *)buf_p ); - buf_p += 2; - targa_header.pixel_size = *buf_p++; - targa_header.attributes = *buf_p++; - - if ( targa_header.image_type != 2 - && targa_header.image_type != 10 - && targa_header.image_type != 3 ) { - Error( "LoadTGA: Only type 2 (RGB), 3 (gray), and 10 (RGB) TGA images supported\n" ); - } - - if ( targa_header.colormap_type != 0 ) { - Error( "LoadTGA: colormaps not supported\n" ); - } - - if ( ( targa_header.pixel_size != 32 && targa_header.pixel_size != 24 ) && targa_header.image_type != 3 ) { - Error( "LoadTGA: Only 32 or 24 bit images supported (no colormaps)\n" ); - } - - columns = targa_header.width; - rows = targa_header.height; - numPixels = columns * rows; - - if ( width ) { - *width = columns; - } - if ( height ) { - *height = rows; - } - - targa_rgba = safe_malloc( numPixels * 4 ); - *pic = targa_rgba; - - if ( targa_header.id_length != 0 ) { - buf_p += targa_header.id_length; // skip TARGA image comment - - } - if ( targa_header.image_type == 2 || targa_header.image_type == 3 ) { - // Uncompressed RGB or gray scale image - for ( row = rows - 1; row >= 0; row-- ) - { - pixbuf = targa_rgba + row * columns * 4; - for ( column = 0; column < columns; column++ ) - { - unsigned char red,green,blue,alphabyte; - switch ( targa_header.pixel_size ) - { - - case 8: - blue = *buf_p++; - green = blue; - red = blue; - *pixbuf++ = red; - *pixbuf++ = green; - *pixbuf++ = blue; - *pixbuf++ = 255; - break; - - case 24: - blue = *buf_p++; - green = *buf_p++; - red = *buf_p++; - *pixbuf++ = red; - *pixbuf++ = green; - *pixbuf++ = blue; - *pixbuf++ = 255; - break; - case 32: - blue = *buf_p++; - green = *buf_p++; - red = *buf_p++; - alphabyte = *buf_p++; - *pixbuf++ = red; - *pixbuf++ = green; - *pixbuf++ = blue; - *pixbuf++ = alphabyte; - break; - default: - //Error("LoadTGA: illegal pixel_size '%d' in file '%s'\n", targa_header.pixel_size, name ); - break; - } - } - } - } - else if ( targa_header.image_type == 10 ) { // Runlength encoded RGB images - unsigned char red,green,blue,alphabyte,packetHeader,packetSize,j; - - red = 0; - green = 0; - blue = 0; - alphabyte = 0xff; - - for ( row = rows - 1; row >= 0; row-- ) { - pixbuf = targa_rgba + row * columns * 4; - for ( column = 0; column < columns; ) { - packetHeader = *buf_p++; - packetSize = 1 + ( packetHeader & 0x7f ); - if ( packetHeader & 0x80 ) { // run-length packet - switch ( targa_header.pixel_size ) { - case 24: - blue = *buf_p++; - green = *buf_p++; - red = *buf_p++; - alphabyte = 255; - break; - case 32: - blue = *buf_p++; - green = *buf_p++; - red = *buf_p++; - alphabyte = *buf_p++; - break; - default: - //Error("LoadTGA: illegal pixel_size '%d' in file '%s'\n", targa_header.pixel_size, name ); - break; - } - - for ( j = 0; j < packetSize; j++ ) { - *pixbuf++ = red; - *pixbuf++ = green; - *pixbuf++ = blue; - *pixbuf++ = alphabyte; - column++; - if ( column == columns ) { // run spans across rows - column = 0; - if ( row > 0 ) { - row--; - } - else{ - goto breakOut; - } - pixbuf = targa_rgba + row * columns * 4; - } - } - } - else { // non run-length packet - for ( j = 0; j < packetSize; j++ ) { - switch ( targa_header.pixel_size ) { - case 24: - blue = *buf_p++; - green = *buf_p++; - red = *buf_p++; - *pixbuf++ = red; - *pixbuf++ = green; - *pixbuf++ = blue; - *pixbuf++ = 255; - break; - case 32: - blue = *buf_p++; - green = *buf_p++; - red = *buf_p++; - alphabyte = *buf_p++; - *pixbuf++ = red; - *pixbuf++ = green; - *pixbuf++ = blue; - *pixbuf++ = alphabyte; - break; - default: - //Sysprintf("LoadTGA: illegal pixel_size '%d' in file '%s'\n", targa_header.pixel_size, name ); - break; - } - column++; - if ( column == columns ) { // pixel packet run spans across rows - column = 0; - if ( row > 0 ) { - row--; - } - else{ - goto breakOut; - } - pixbuf = targa_rgba + row * columns * 4; - } - } - } - } -breakOut:; - } - } - - // vertically flipped - if ( ( targa_header.attributes & ( 1 << 5 ) ) ) { - int flip; - for ( row = 0; row < .5f * rows; row++ ) - { - for ( column = 0; column < columns; column++ ) - { - flip = *( (int*)targa_rgba + row * columns + column ); - *( (int*)targa_rgba + row * columns + column ) = *( (int*)targa_rgba + ( ( rows - 1 ) - row ) * columns + column ); - *( (int*)targa_rgba + ( ( rows - 1 ) - row ) * columns + column ) = flip; - } - } - } - - //free(buffer); -} - - - -/* - ============= - LoadTGA - ============= - */ -void LoadTGA( const char *name, byte **pixels, int *width, int *height ){ - byte *buffer; - int nLen; - // - // load the file - // - nLen = vfsLoadFile( ( char * ) name, (void **)&buffer, 0 ); - if ( nLen == -1 ) { - Error( "Couldn't read %s", name ); - } - - LoadTGABuffer( buffer, pixels, width, height ); - -} - - -/* - ================ - WriteTGA - ================ - */ -void WriteTGA( const char *filename, byte *data, int width, int height ) { - byte *buffer; - int i; - int c; - FILE *f; - - buffer = safe_malloc( width * height * 4 + 18 ); - memset( buffer, 0, 18 ); - buffer[2] = 2; // uncompressed type - buffer[12] = width & 255; - buffer[13] = width >> 8; - buffer[14] = height & 255; - buffer[15] = height >> 8; - buffer[16] = 32; // pixel size - - // swap rgb to bgr - c = 18 + width * height * 4; - for ( i = 18 ; i < c ; i += 4 ) - { - buffer[i] = data[i - 18 + 2]; // blue - buffer[i + 1] = data[i - 18 + 1]; // green - buffer[i + 2] = data[i - 18 + 0]; // red - buffer[i + 3] = data[i - 18 + 3]; // alpha - } - - f = fopen( filename, "wb" ); - fwrite( buffer, 1, c, f ); - fclose( f ); - - free( buffer ); -} - -/* - ============================================================================ - - LOAD32BITIMAGE - - ============================================================================ - */ - -/* - ============== - Load32BitImage - - Any of the return pointers can be NULL if you don't want them. - ============== - */ -void Load32BitImage( const char *name, unsigned **pixels, int *width, int *height ){ - char ext[128]; - byte *palette; - byte *pixels8; - byte *pixels32; - int size; - int i; - int v; - - ExtractFileExtension( name, ext ); - if ( !Q_stricmp( ext, "tga" ) ) { - LoadTGA( name, (byte **)pixels, width, height ); - } - else { - Load256Image( name, &pixels8, &palette, width, height ); - if ( !pixels ) { - return; - } - size = *width * *height; - pixels32 = safe_malloc( size * 4 ); - *pixels = (unsigned *)pixels32; - for ( i = 0 ; i < size ; i++ ) { - v = pixels8[i]; - pixels32[i * 4 + 0] = palette[ v * 3 + 0 ]; - pixels32[i * 4 + 1] = palette[ v * 3 + 1 ]; - pixels32[i * 4 + 2] = palette[ v * 3 + 2 ]; - pixels32[i * 4 + 3] = 0xff; - } - } -} diff --git a/tools/urt/tools/quake3/common/imagelib.h b/tools/urt/tools/quake3/common/imagelib.h deleted file mode 100644 index 95ba675..0000000 --- a/tools/urt/tools/quake3/common/imagelib.h +++ /dev/null @@ -1,43 +0,0 @@ -/* - Copyright (C) 1999-2007 id Software, Inc. and contributors. - For a list of contributors, see the accompanying CONTRIBUTORS file. - - This file is part of GtkRadiant. - - GtkRadiant is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - GtkRadiant is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with GtkRadiant; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - */ - -// piclib.h - - -void LoadLBM( const char *filename, byte **picture, byte **palette ); -void WriteLBMfile( const char *filename, byte *data, int width, int height - , byte *palette ); -void LoadPCX( const char *filename, byte **picture, byte **palette, int *width, int *height ); -void WritePCXfile( const char *filename, byte *data, int width, int height - , byte *palette ); - -// loads / saves either lbm or pcx, depending on extension -void Load256Image( const char *name, byte **pixels, byte **palette, - int *width, int *height ); -void Save256Image( const char *name, byte *pixels, byte *palette, - int width, int height ); - - -void LoadTGA( const char *filename, byte **pixels, int *width, int *height ); -void LoadTGABuffer( byte *buffer, byte **pic, int *width, int *height ); -void WriteTGA( const char *filename, byte *data, int width, int height ); - -void Load32BitImage( const char *name, unsigned **pixels, int *width, int *height ); diff --git a/tools/urt/tools/quake3/common/inout.c b/tools/urt/tools/quake3/common/inout.c deleted file mode 100644 index 74a111b..0000000 --- a/tools/urt/tools/quake3/common/inout.c +++ /dev/null @@ -1,364 +0,0 @@ -/* - Copyright (C) 1999-2007 id Software, Inc. and contributors. - For a list of contributors, see the accompanying CONTRIBUTORS file. - - This file is part of GtkRadiant. - - GtkRadiant is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - GtkRadiant is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with GtkRadiant; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - */ - -//----------------------------------------------------------------------------- -// -// -// DESCRIPTION: -// deal with in/out tasks, for either stdin/stdout or network/XML stream -// - -#include "cmdlib.h" -#include "mathlib.h" -#include "polylib.h" -#include "inout.h" -#include -#include - -#ifdef WIN32 -#include -#include -#endif - -// network broadcasting -#include "l_net/l_net.h" -#include "libxml/tree.h" - -// utf8 conversion -#include -#include - -#ifdef WIN32 -HWND hwndOut = NULL; -qboolean lookedForServer = qfalse; -UINT wm_BroadcastCommand = -1; -#endif - -socket_t *brdcst_socket; -netmessage_t msg; - -qboolean verbose = qfalse; - -// our main document -// is streamed through the network to Radiant -// possibly written to disk at the end of the run -//++timo FIXME: need to be global, required when creating nodes? -xmlDocPtr doc; -xmlNodePtr tree; - -// some useful stuff -xmlNodePtr xml_NodeForVec( vec3_t v ){ - xmlNodePtr ret; - char buf[1024]; - - sprintf( buf, "%f %f %f", v[0], v[1], v[2] ); - ret = xmlNewNode( NULL, "point" ); - xmlNodeSetContent( ret, buf ); - return ret; -} - -// send a node down the stream, add it to the document -void xml_SendNode( xmlNodePtr node ){ - xmlBufferPtr xml_buf; - char xmlbuf[MAX_NETMESSAGE]; // we have to copy content from the xmlBufferPtr into an aux buffer .. that sucks .. - // this index loops through the node buffer - int pos = 0; - int size; - - xmlAddChild( doc->children, node ); - - if ( brdcst_socket ) { - xml_buf = xmlBufferCreate(); - xmlNodeDump( xml_buf, doc, node, 0, 0 ); - - // the XML node might be too big to fit in a single network message - // l_net library defines an upper limit of MAX_NETMESSAGE - // there are some size check errors, so we use MAX_NETMESSAGE-10 to be safe - // if the size of the buffer exceeds MAX_NETMESSAGE-10 we'll send in several network messages - while ( pos < xml_buf->use ) - { - // what size are we gonna send now? - ( xml_buf->use - pos < MAX_NETMESSAGE - 10 ) ? ( size = xml_buf->use - pos ) : ( size = MAX_NETMESSAGE - 10 ); - //++timo just a debug thing - if ( size == MAX_NETMESSAGE - 10 ) { - Sys_FPrintf( SYS_NOXML, "Got to split the buffer\n" ); - } - memcpy( xmlbuf, xml_buf->content + pos, size ); - xmlbuf[size] = '\0'; - NMSG_Clear( &msg ); - NMSG_WriteString( &msg, xmlbuf ); - Net_Send( brdcst_socket, &msg ); - // now that the thing is sent prepare to loop again - pos += size; - } - -#if 0 - // NOTE: the NMSG_WriteString is limited to MAX_NETMESSAGE - // we will need to split into chunks - // (we could also go lower level, in the end it's using send and receiv which are not size limited) - //++timo FIXME: MAX_NETMESSAGE is not exactly the max size we can stick in the message - // there's some tweaking to do in l_net for that .. so let's give us a margin for now - - //++timo we need to handle the case of a buffer too big to fit in a single message - // try without checks for now - if ( xml_buf->use > MAX_NETMESSAGE - 10 ) { - // if we send that we are probably gonna break the stream at the other end.. - // and Error will call right there - //Error( "MAX_NETMESSAGE exceeded for XML feedback stream in FPrintf (%d)\n", xml_buf->use); - Sys_FPrintf( SYS_NOXML, "MAX_NETMESSAGE exceeded for XML feedback stream in FPrintf (%d)\n", xml_buf->use ); - xml_buf->content[xml_buf->use] = '\0'; //++timo this corrupts the buffer but we don't care it's for printing - Sys_FPrintf( SYS_NOXML, xml_buf->content ); - - } - - size = xml_buf->use; - memcpy( xmlbuf, xml_buf->content, size ); - xmlbuf[size] = '\0'; - NMSG_Clear( &msg ); - NMSG_WriteString( &msg, xmlbuf ); - Net_Send( brdcst_socket, &msg ); -#endif - - xmlBufferFree( xml_buf ); - } -} - -void xml_Select( char *msg, int entitynum, int brushnum, qboolean bError ){ - xmlNodePtr node, select; - char buf[1024]; - char level[2]; - - // now build a proper "select" XML node - sprintf( buf, "Entity %i, Brush %i: %s", entitynum, brushnum, msg ); - node = xmlNewNode( NULL, "select" ); - xmlNodeSetContent( node, buf ); - level[0] = (int)'0' + ( bError ? SYS_ERR : SYS_WRN ) ; - level[1] = 0; - xmlSetProp( node, "level", (char *)&level ); - // a 'select' information - sprintf( buf, "%i %i", entitynum, brushnum ); - select = xmlNewNode( NULL, "brush" ); - xmlNodeSetContent( select, buf ); - xmlAddChild( node, select ); - xml_SendNode( node ); - - sprintf( buf, "Entity %i, Brush %i: %s", entitynum, brushnum, msg ); - if ( bError ) { - Error( buf ); - } - else{ - Sys_FPrintf( SYS_NOXML, "%s\n", buf ); - } - -} - -void xml_Point( char *msg, vec3_t pt ){ - xmlNodePtr node, point; - char buf[1024]; - char level[2]; - - node = xmlNewNode( NULL, "pointmsg" ); - xmlNodeSetContent( node, msg ); - level[0] = (int)'0' + SYS_ERR; - level[1] = 0; - xmlSetProp( node, "level", (char *)&level ); - // a 'point' node - sprintf( buf, "%g %g %g", pt[0], pt[1], pt[2] ); - point = xmlNewNode( NULL, "point" ); - xmlNodeSetContent( point, buf ); - xmlAddChild( node, point ); - xml_SendNode( node ); - - sprintf( buf, "%s (%g %g %g)", msg, pt[0], pt[1], pt[2] ); - Error( buf ); -} - -#define WINDING_BUFSIZE 2048 -void xml_Winding( char *msg, vec3_t p[], int numpoints, qboolean die ){ - xmlNodePtr node, winding; - char buf[WINDING_BUFSIZE]; - char smlbuf[128]; - char level[2]; - int i; - - node = xmlNewNode( NULL, "windingmsg" ); - xmlNodeSetContent( node, msg ); - level[0] = (int)'0' + SYS_ERR; - level[1] = 0; - xmlSetProp( node, "level", (char *)&level ); - // a 'winding' node - sprintf( buf, "%i ", numpoints ); - for ( i = 0; i < numpoints; i++ ) - { - sprintf( smlbuf, "(%g %g %g)", p[i][0], p[i][1], p[i][2] ); - // don't overflow - if ( strlen( buf ) + strlen( smlbuf ) > WINDING_BUFSIZE ) { - break; - } - strcat( buf, smlbuf ); - } - - winding = xmlNewNode( NULL, "winding" ); - xmlNodeSetContent( winding, buf ); - xmlAddChild( node, winding ); - xml_SendNode( node ); - - if ( die ) { - Error( msg ); - } - else - { - Sys_Printf( msg ); - Sys_Printf( "\n" ); - } -} - -// in include -#include "stream_version.h" - -void Broadcast_Setup( const char *dest ){ - address_t address; - char sMsg[1024]; - - Net_Setup(); - Net_StringToAddress( (char *)dest, &address ); - brdcst_socket = Net_Connect( &address, 0 ); - if ( brdcst_socket ) { - // send in a header - sprintf( sMsg, "" ); - NMSG_Clear( &msg ); - NMSG_WriteString( &msg, sMsg ); - Net_Send( brdcst_socket, &msg ); - } -} - -void Broadcast_Shutdown(){ - if ( brdcst_socket ) { - Sys_Printf( "Disconnecting\n" ); - Net_Disconnect( brdcst_socket ); - brdcst_socket = NULL; - } -} - -// all output ends up through here -void FPrintf( int flag, char *buf ){ - xmlNodePtr node; - static qboolean bGotXML = qfalse; - char level[2]; - - printf( buf ); - - // the following part is XML stuff only.. but maybe we don't want that message to go down the XML pipe? - if ( flag == SYS_NOXML ) { - return; - } - - // ouput an XML file of the run - // use the DOM interface to build a tree - /* - - message string - .. various nodes to describe corresponding geometry .. - - */ - if ( !bGotXML ) { - // initialize - doc = xmlNewDoc( "1.0" ); - doc->children = xmlNewDocRawNode( doc, NULL, "q3map_feedback", NULL ); - bGotXML = qtrue; - } - node = xmlNewNode( NULL, "message" ); - { - gchar* utf8 = g_locale_to_utf8( buf, -1, NULL, NULL, NULL ); - xmlNodeSetContent( node, utf8 ); - g_free( utf8 ); - } - level[0] = (int)'0' + flag; - level[1] = 0; - xmlSetProp( node, "level", (char *)&level ); - - xml_SendNode( node ); -} - -#ifdef DBG_XML -void DumpXML(){ - xmlSaveFile( "XMLDump.xml", doc ); -} -#endif - -void Sys_FPrintf( int flag, const char *format, ... ){ - char out_buffer[4096]; - va_list argptr; - - if ( ( flag == SYS_VRB ) && ( verbose == qfalse ) ) { - return; - } - - va_start( argptr, format ); - vsprintf( out_buffer, format, argptr ); - va_end( argptr ); - - FPrintf( flag, out_buffer ); -} - -void Sys_Printf( const char *format, ... ){ - char out_buffer[4096]; - va_list argptr; - - va_start( argptr, format ); - vsprintf( out_buffer, format, argptr ); - va_end( argptr ); - - FPrintf( SYS_STD, out_buffer ); -} - -/* - ================= - Error - - For abnormal program terminations - ================= - */ -void Error( const char *error, ... ){ - char out_buffer[4096]; - char tmp[4096]; - va_list argptr; - - va_start( argptr,error ); - vsprintf( tmp, error, argptr ); - va_end( argptr ); - - sprintf( out_buffer, "************ ERROR ************\n%s\n", tmp ); - - FPrintf( SYS_ERR, out_buffer ); - -#ifdef DBG_XML - DumpXML(); -#endif - - //++timo HACK ALERT .. if we shut down too fast the xml stream won't reach the listener. - // a clean solution is to send a sync request node in the stream and wait for an answer before exiting - Sys_Sleep( 1000 ); - - Broadcast_Shutdown(); - - exit( 1 ); -} diff --git a/tools/urt/tools/quake3/common/inout.h b/tools/urt/tools/quake3/common/inout.h deleted file mode 100644 index 0070592..0000000 --- a/tools/urt/tools/quake3/common/inout.h +++ /dev/null @@ -1,61 +0,0 @@ -/* - Copyright (C) 1999-2007 id Software, Inc. and contributors. - For a list of contributors, see the accompanying CONTRIBUTORS file. - - This file is part of GtkRadiant. - - GtkRadiant is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - GtkRadiant is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with GtkRadiant; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - */ - -#ifndef __INOUT__ -#define __INOUT__ - -// inout is the only stuff relying on xml, include the headers there -#include "libxml/tree.h" - -// some useful xml routines -xmlNodePtr xml_NodeForVec( vec3_t v ); -void xml_SendNode( xmlNodePtr node ); -// print a message in q3map output and send the corresponding select information down the xml stream -// bError: do we end with an error on this one or do we go ahead? -void xml_Select( char *msg, int entitynum, int brushnum, qboolean bError ); -// end q3map with an error message and send a point information in the xml stream -// note: we might want to add a boolean to use this as a warning or an error thing.. -void xml_Winding( char *msg, vec3_t p[], int numpoints, qboolean die ); -void xml_Point( char *msg, vec3_t pt ); - -extern qboolean bNetworkBroadcast; -void Broadcast_Setup( const char *dest ); -void Broadcast_Shutdown(); - -#define SYS_VRB 0 // verbose support (on/off) -#define SYS_STD 1 // standard print level -#define SYS_WRN 2 // warnings -#define SYS_ERR 3 // error -#define SYS_NOXML 4 // don't send that down the XML stream - -extern qboolean verbose; -void Sys_Printf( const char *text, ... ); -void Sys_FPrintf( int flag, const char *text, ... ); - -#ifdef _DEBUG -#define DBG_XML 1 -#endif - -#ifdef DBG_XML -void DumpXML(); -#endif - -#endif diff --git a/tools/urt/tools/quake3/common/l3dslib.c b/tools/urt/tools/quake3/common/l3dslib.c deleted file mode 100644 index 5e340b9..0000000 --- a/tools/urt/tools/quake3/common/l3dslib.c +++ /dev/null @@ -1,312 +0,0 @@ -/* - Copyright (C) 1999-2007 id Software, Inc. and contributors. - For a list of contributors, see the accompanying CONTRIBUTORS file. - - This file is part of GtkRadiant. - - GtkRadiant is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - GtkRadiant is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with GtkRadiant; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - */ - -// -// l3dslib.c: library for loading triangles from an Alias triangle file -// - -#include -#include "cmdlib.h" -#include "mathlib.h" -#include "trilib.h" -#include "l3dslib.h" - -#define MAIN3DS 0x4D4D -#define EDIT3DS 0x3D3D // this is the start of the editor config -#define EDIT_OBJECT 0x4000 -#define OBJ_TRIMESH 0x4100 -#define TRI_VERTEXL 0x4110 -#define TRI_FACEL1 0x4120 - -#define MAXVERTS 2000 -#define MAXTRIANGLES 750 - -typedef struct { - int v[4]; -} tri; - -float fverts[MAXVERTS][3]; -tri tris[MAXTRIANGLES]; - -int bytesread, level, numtris, totaltris; -int vertsfound, trisfound; - -triangle_t *ptri; - - -// Alias stores triangles as 3 explicit vertices in .tri files, so even though we -// start out with a vertex pool and vertex indices for triangles, we have to convert -// to raw, explicit triangles -void StoreAliasTriangles( void ){ - int i, j, k; - - if ( ( totaltris + numtris ) > MAXTRIANGLES ) { - Error( "Error: Too many triangles" ); - } - - for ( i = 0; i < numtris ; i++ ) - { - for ( j = 0 ; j < 3 ; j++ ) - { - for ( k = 0 ; k < 3 ; k++ ) - { - ptri[i + totaltris].verts[j][k] = fverts[tris[i].v[j]][k]; - } - } - } - - totaltris += numtris; - numtris = 0; - vertsfound = 0; - trisfound = 0; -} - - -int ParseVertexL( FILE *input ){ - int i, j, startbytesread, numverts; - unsigned short tshort; - - if ( vertsfound ) { - Error( "Error: Multiple vertex chunks" ); - } - - vertsfound = 1; - startbytesread = bytesread; - - if ( feof( input ) ) { - Error( "Error: unexpected end of file" ); - } - - fread( &tshort, sizeof( tshort ), 1, input ); - bytesread += sizeof( tshort ); - numverts = (int)tshort; - - if ( numverts > MAXVERTS ) { - Error( "Error: Too many vertices" ); - } - - for ( i = 0 ; i < numverts ; i++ ) - { - for ( j = 0 ; j < 3 ; j++ ) - { - if ( feof( input ) ) { - Error( "Error: unexpected end of file" ); - } - - fread( &fverts[i][j], sizeof( float ), 1, input ); - bytesread += sizeof( float ); - } - } - - if ( vertsfound && trisfound ) { - StoreAliasTriangles(); - } - - return bytesread - startbytesread; -} - - -int ParseFaceL1( FILE *input ){ - - int i, j, startbytesread; - unsigned short tshort; - - if ( trisfound ) { - Error( "Error: Multiple face chunks" ); - } - - trisfound = 1; - startbytesread = bytesread; - - if ( feof( input ) ) { - Error( "Error: unexpected end of file" ); - } - - fread( &tshort, sizeof( tshort ), 1, input ); - bytesread += sizeof( tshort ); - numtris = (int)tshort; - - if ( numtris > MAXTRIANGLES ) { - Error( "Error: Too many triangles" ); - } - - for ( i = 0 ; i < numtris ; i++ ) - { - for ( j = 0 ; j < 4 ; j++ ) - { - if ( feof( input ) ) { - Error( "Error: unexpected end of file" ); - } - - fread( &tshort, sizeof( tshort ), 1, input ); - bytesread += sizeof( tshort ); - tris[i].v[j] = (int)tshort; - } - } - - if ( vertsfound && trisfound ) { - StoreAliasTriangles(); - } - - return bytesread - startbytesread; -} - - -int ParseChunk( FILE *input ){ -#define BLOCK_SIZE 4096 - char temp[BLOCK_SIZE]; - unsigned short type; - int i, length, w, t, retval; - - level++; - retval = 0; - -// chunk type - if ( feof( input ) ) { - Error( "Error: unexpected end of file" ); - } - - fread( &type, sizeof( type ), 1, input ); - bytesread += sizeof( type ); - -// chunk length - if ( feof( input ) ) { - Error( "Error: unexpected end of file" ); - } - - fread( &length, sizeof( length ), 1, input ); - bytesread += sizeof( length ); - w = length - 6; - -// process chunk if we care about it, otherwise skip it - switch ( type ) - { - case TRI_VERTEXL: - w -= ParseVertexL( input ); - goto ParseSubchunk; - - case TRI_FACEL1: - w -= ParseFaceL1( input ); - goto ParseSubchunk; - - case EDIT_OBJECT: - // read the name - i = 0; - - do - { - if ( feof( input ) ) { - Error( "Error: unexpected end of file" ); - } - - fread( &temp[i], 1, 1, input ); - i++; - w--; - bytesread++; - } while ( temp[i - 1] ); - - case MAIN3DS: - case OBJ_TRIMESH: - case EDIT3DS: - // parse through subchunks -ParseSubchunk: - while ( w > 0 ) - { - w -= ParseChunk( input ); - } - - retval = length; - goto Done; - - default: - // skip other chunks - while ( w > 0 ) - { - t = w; - - if ( t > BLOCK_SIZE ) { - t = BLOCK_SIZE; - } - - if ( feof( input ) ) { - Error( "Error: unexpected end of file" ); - } - - fread( &temp, t, 1, input ); - bytesread += t; - - w -= t; - } - - retval = length; - goto Done; - } - -Done: - level--; - return retval; -} - - -void Load3DSTriangleList( char *filename, triangle_t **pptri, int *numtriangles ){ - FILE *input; - short int tshort; - - bytesread = 0; - level = 0; - numtris = 0; - totaltris = 0; - vertsfound = 0; - trisfound = 0; - - if ( ( input = fopen( filename, "rb" ) ) == 0 ) { - fprintf( stderr,"reader: could not open file '%s'\n", filename ); - exit( 0 ); - } - - fread( &tshort, sizeof( tshort ), 1, input ); - -// should only be MAIN3DS, but some files seem to start with EDIT3DS, with -// no MAIN3DS - if ( ( tshort != MAIN3DS ) && ( tshort != EDIT3DS ) ) { - fprintf( stderr,"File is not a 3DS file.\n" ); - exit( 0 ); - } - -// back to top of file so we can parse the first chunk descriptor - fseek( input, 0, SEEK_SET ); - - ptri = safe_malloc( MAXTRIANGLES * sizeof( triangle_t ) ); - - *pptri = ptri; - -// parse through looking for the relevant chunk tree (MAIN3DS | EDIT3DS | EDIT_OBJECT | -// OBJ_TRIMESH | {TRI_VERTEXL, TRI_FACEL1}) and skipping other chunks - ParseChunk( input ); - - if ( vertsfound || trisfound ) { - Error( "Incomplete triangle set" ); - } - - *numtriangles = totaltris; - - fclose( input ); -} diff --git a/tools/urt/tools/quake3/common/l3dslib.h b/tools/urt/tools/quake3/common/l3dslib.h deleted file mode 100644 index 98ed502..0000000 --- a/tools/urt/tools/quake3/common/l3dslib.h +++ /dev/null @@ -1,25 +0,0 @@ -/* - Copyright (C) 1999-2007 id Software, Inc. and contributors. - For a list of contributors, see the accompanying CONTRIBUTORS file. - - This file is part of GtkRadiant. - - GtkRadiant is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - GtkRadiant is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with GtkRadiant; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - */ - -// -// l3dslib.h: header file for loading triangles from a 3DS triangle file -// -void Load3DSTriangleList( char *filename, triangle_t **pptri, int *numtriangles ); diff --git a/tools/urt/tools/quake3/common/md4.c b/tools/urt/tools/quake3/common/md4.c deleted file mode 100644 index e3e40d8..0000000 --- a/tools/urt/tools/quake3/common/md4.c +++ /dev/null @@ -1,292 +0,0 @@ -/* - Copyright (C) 1999-2007 id Software, Inc. and contributors. - For a list of contributors, see the accompanying CONTRIBUTORS file. - - This file is part of GtkRadiant. - - GtkRadiant is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - GtkRadiant is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with GtkRadiant; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - */ - -/* GLOBAL.H - RSAREF types and constants */ - -#include - -/* POINTER defines a generic pointer type */ -typedef unsigned char *POINTER; - -/* UINT2 defines a two byte word */ -typedef unsigned short int UINT2; - -/* UINT4 defines a four byte word */ -typedef unsigned long int UINT4; - - -/* MD4.H - header file for MD4C.C */ - -/* Copyright (C) 1991-2, RSA Data Security, Inc. Created 1991. - - All rights reserved. - - License to copy and use this software is granted provided that it is identified as the “RSA Data Security, Inc. MD4 Message-Digest Algorithm” in all material mentioning or referencing this software or this function. - License is also granted to make and use derivative works provided that such works are identified as “derived from the RSA Data Security, Inc. MD4 Message-Digest Algorithm” in all material mentioning or referencing the derived work. - RSA Data Security, Inc. makes no representations concerning either the merchantability of this software or the suitability of this software for any particular purpose. It is provided “as is” without express or implied warranty of any kind. - - These notices must be retained in any copies of any part of this documentation and/or software. */ - -/* MD4 context. */ -typedef struct { - UINT4 state[4]; /* state (ABCD) */ - UINT4 count[2]; /* number of bits, modulo 2^64 (lsb first) */ - unsigned char buffer[64]; /* input buffer */ -} MD4_CTX; - -void MD4Init( MD4_CTX * ); -void MD4Update( MD4_CTX *, unsigned char *, unsigned int ); -void MD4Final( unsigned char [16], MD4_CTX * ); - - - -/* MD4C.C - RSA Data Security, Inc., MD4 message-digest algorithm */ -/* Copyright (C) 1990-2, RSA Data Security, Inc. All rights reserved. - - License to copy and use this software is granted provided that it is identified as the - RSA Data Security, Inc. MD4 Message-Digest Algorithm - in all material mentioning or referencing this software or this function. - License is also granted to make and use derivative works provided that such works are identified as - derived from the RSA Data Security, Inc. MD4 Message-Digest Algorithm - in all material mentioning or referencing the derived work. - RSA Data Security, Inc. makes no representations concerning either the merchantability of this software or the suitability of this software for any particular purpose. It is provided - as is without express or implied warranty of any kind. - - These notices must be retained in any copies of any part of this documentation and/or software. */ - -/* Constants for MD4Transform routine. */ -#define S11 3 -#define S12 7 -#define S13 11 -#define S14 19 -#define S21 3 -#define S22 5 -#define S23 9 -#define S24 13 -#define S31 3 -#define S32 9 -#define S33 11 -#define S34 15 - -static void MD4Transform( UINT4 [4], unsigned char [64] ); -static void Encode( unsigned char *, UINT4 *, unsigned int ); -static void Decode( UINT4 *, unsigned char *, unsigned int ); -static void MD4_memcpy( POINTER, POINTER, unsigned int ); -static void MD4_memset( POINTER, int, unsigned int ); - -static unsigned char PADDING[64] = { - 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 -}; - -/* F, G and H are basic MD4 functions. */ -#define F( x, y, z ) ( ( ( x ) & ( y ) ) | ( ( ~x ) & ( z ) ) ) -#define G( x, y, z ) ( ( ( x ) & ( y ) ) | ( ( x ) & ( z ) ) | ( ( y ) & ( z ) ) ) -#define H( x, y, z ) ( ( x ) ^ ( y ) ^ ( z ) ) - -/* ROTATE_LEFT rotates x left n bits. */ -#define ROTATE_LEFT( x, n ) ( ( ( x ) << ( n ) ) | ( ( x ) >> ( 32 - ( n ) ) ) ) - -/* FF, GG and HH are transformations for rounds 1, 2 and 3 */ -/* Rotation is separate from addition to prevent recomputation */ -#define FF( a, b, c, d, x, s ) {( a ) += F( ( b ), ( c ), ( d ) ) + ( x ); ( a ) = ROTATE_LEFT( ( a ), ( s ) ); } - -#define GG( a, b, c, d, x, s ) {( a ) += G( ( b ), ( c ), ( d ) ) + ( x ) + (UINT4)0x5a827999; ( a ) = ROTATE_LEFT( ( a ), ( s ) ); } - -#define HH( a, b, c, d, x, s ) {( a ) += H( ( b ), ( c ), ( d ) ) + ( x ) + (UINT4)0x6ed9eba1; ( a ) = \ - ROTATE_LEFT( ( a ), ( s ) ); } - - -/* MD4 initialization. Begins an MD4 operation, writing a new context. */ -void MD4Init( MD4_CTX *context ){ - context->count[0] = context->count[1] = 0; - -/* Load magic initialization constants.*/ - context->state[0] = 0x67452301; - context->state[1] = 0xefcdab89; - context->state[2] = 0x98badcfe; - context->state[3] = 0x10325476; -} - -/* MD4 block update operation. Continues an MD4 message-digest operation, processing another message block, and updating the context. */ -void MD4Update( MD4_CTX *context, unsigned char *input, unsigned int inputLen ){ - unsigned int i, index, partLen; - - /* Compute number of bytes mod 64 */ - index = (unsigned int)( ( context->count[0] >> 3 ) & 0x3F ); - - /* Update number of bits */ - if ( ( context->count[0] += ( (UINT4)inputLen << 3 ) ) < ( (UINT4)inputLen << 3 ) ) { - context->count[1]++; - } - - context->count[1] += ( (UINT4)inputLen >> 29 ); - - partLen = 64 - index; - - /* Transform as many times as possible.*/ - if ( inputLen >= partLen ) { - memcpy( (POINTER)&context->buffer[index], (POINTER)input, partLen ); - MD4Transform( context->state, context->buffer ); - - for ( i = partLen; i + 63 < inputLen; i += 64 ) - MD4Transform( context->state, &input[i] ); - - index = 0; - } - else{ - i = 0; - } - - /* Buffer remaining input */ - memcpy( (POINTER)&context->buffer[index], (POINTER)&input[i], inputLen - i ); -} - - -/* MD4 finalization. Ends an MD4 message-digest operation, writing the the message digest and zeroizing the context. */ -void MD4Final( unsigned char digest[16], MD4_CTX *context ){ - unsigned char bits[8]; - unsigned int index, padLen; - - /* Save number of bits */ - Encode( bits, context->count, 8 ); - - /* Pad out to 56 mod 64.*/ - index = (unsigned int)( ( context->count[0] >> 3 ) & 0x3f ); - padLen = ( index < 56 ) ? ( 56 - index ) : ( 120 - index ); - MD4Update( context, PADDING, padLen ); - - /* Append length (before padding) */ - MD4Update( context, bits, 8 ); - - /* Store state in digest */ - Encode( digest, context->state, 16 ); - - /* Zeroize sensitive information.*/ - memset( (POINTER)context, 0, sizeof( *context ) ); -} - - -/* MD4 basic transformation. Transforms state based on block. */ -static void MD4Transform( UINT4 state[4], unsigned char block[64] ){ - UINT4 a = state[0], b = state[1], c = state[2], d = state[3], x[16]; - - Decode( x, block, 64 ); - -/* Round 1 */ - FF( a, b, c, d, x[ 0], S11 ); /* 1 */ - FF( d, a, b, c, x[ 1], S12 ); /* 2 */ - FF( c, d, a, b, x[ 2], S13 ); /* 3 */ - FF( b, c, d, a, x[ 3], S14 ); /* 4 */ - FF( a, b, c, d, x[ 4], S11 ); /* 5 */ - FF( d, a, b, c, x[ 5], S12 ); /* 6 */ - FF( c, d, a, b, x[ 6], S13 ); /* 7 */ - FF( b, c, d, a, x[ 7], S14 ); /* 8 */ - FF( a, b, c, d, x[ 8], S11 ); /* 9 */ - FF( d, a, b, c, x[ 9], S12 ); /* 10 */ - FF( c, d, a, b, x[10], S13 ); /* 11 */ - FF( b, c, d, a, x[11], S14 ); /* 12 */ - FF( a, b, c, d, x[12], S11 ); /* 13 */ - FF( d, a, b, c, x[13], S12 ); /* 14 */ - FF( c, d, a, b, x[14], S13 ); /* 15 */ - FF( b, c, d, a, x[15], S14 ); /* 16 */ - -/* Round 2 */ - GG( a, b, c, d, x[ 0], S21 ); /* 17 */ - GG( d, a, b, c, x[ 4], S22 ); /* 18 */ - GG( c, d, a, b, x[ 8], S23 ); /* 19 */ - GG( b, c, d, a, x[12], S24 ); /* 20 */ - GG( a, b, c, d, x[ 1], S21 ); /* 21 */ - GG( d, a, b, c, x[ 5], S22 ); /* 22 */ - GG( c, d, a, b, x[ 9], S23 ); /* 23 */ - GG( b, c, d, a, x[13], S24 ); /* 24 */ - GG( a, b, c, d, x[ 2], S21 ); /* 25 */ - GG( d, a, b, c, x[ 6], S22 ); /* 26 */ - GG( c, d, a, b, x[10], S23 ); /* 27 */ - GG( b, c, d, a, x[14], S24 ); /* 28 */ - GG( a, b, c, d, x[ 3], S21 ); /* 29 */ - GG( d, a, b, c, x[ 7], S22 ); /* 30 */ - GG( c, d, a, b, x[11], S23 ); /* 31 */ - GG( b, c, d, a, x[15], S24 ); /* 32 */ - -/* Round 3 */ - HH( a, b, c, d, x[ 0], S31 ); /* 33 */ - HH( d, a, b, c, x[ 8], S32 ); /* 34 */ - HH( c, d, a, b, x[ 4], S33 ); /* 35 */ - HH( b, c, d, a, x[12], S34 ); /* 36 */ - HH( a, b, c, d, x[ 2], S31 ); /* 37 */ - HH( d, a, b, c, x[10], S32 ); /* 38 */ - HH( c, d, a, b, x[ 6], S33 ); /* 39 */ - HH( b, c, d, a, x[14], S34 ); /* 40 */ - HH( a, b, c, d, x[ 1], S31 ); /* 41 */ - HH( d, a, b, c, x[ 9], S32 ); /* 42 */ - HH( c, d, a, b, x[ 5], S33 ); /* 43 */ - HH( b, c, d, a, x[13], S34 ); /* 44 */ - HH( a, b, c, d, x[ 3], S31 ); /* 45 */ - HH( d, a, b, c, x[11], S32 ); /* 46 */ - HH( c, d, a, b, x[ 7], S33 ); /* 47 */ - HH( b, c, d, a, x[15], S34 ); /* 48 */ - - state[0] += a; - state[1] += b; - state[2] += c; - state[3] += d; - - /* Zeroize sensitive information.*/ - memset( (POINTER)x, 0, sizeof( x ) ); -} - - -/* Encodes input (UINT4) into output (unsigned char). Assumes len is a multiple of 4. */ -static void Encode( unsigned char *output, UINT4 *input, unsigned int len ){ - unsigned int i, j; - - for ( i = 0, j = 0; j < len; i++, j += 4 ) { - output[j] = (unsigned char)( input[i] & 0xff ); - output[j + 1] = (unsigned char)( ( input[i] >> 8 ) & 0xff ); - output[j + 2] = (unsigned char)( ( input[i] >> 16 ) & 0xff ); - output[j + 3] = (unsigned char)( ( input[i] >> 24 ) & 0xff ); - } -} - - -/* Decodes input (unsigned char) into output (UINT4). Assumes len is a multiple of 4. */ -static void Decode( UINT4 *output, unsigned char *input, unsigned int len ){ - unsigned int i, j; - - for ( i = 0, j = 0; j < len; i++, j += 4 ) - output[i] = ( (UINT4)input[j] ) | ( ( (UINT4)input[j + 1] ) << 8 ) | ( ( (UINT4)input[j + 2] ) << 16 ) | ( ( (UINT4)input[j + 3] ) << 24 ); -} - -//=================================================================== - -unsigned Com_BlockChecksum( void *buffer, int length ){ - int digest[4]; - unsigned val; - MD4_CTX ctx; - - MD4Init( &ctx ); - MD4Update( &ctx, (unsigned char *)buffer, length ); - MD4Final( (unsigned char *)digest, &ctx ); - - val = digest[0] ^ digest[1] ^ digest[2] ^ digest[3]; - - return val; -} diff --git a/tools/urt/tools/quake3/common/mutex.c b/tools/urt/tools/quake3/common/mutex.c deleted file mode 100644 index c9242f1..0000000 --- a/tools/urt/tools/quake3/common/mutex.c +++ /dev/null @@ -1,197 +0,0 @@ -/* - Copyright (C) 1999-2007 id Software, Inc. and contributors. - For a list of contributors, see the accompanying CONTRIBUTORS file. - - This file is part of GtkRadiant. - - GtkRadiant is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - GtkRadiant is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with GtkRadiant; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - */ - - -#include "cmdlib.h" -#include "qthreads.h" -#include "mutex.h" - -/* - =================================================================== - - WIN32 - - =================================================================== - */ -#ifdef WIN32 - -#define USED - -#include - -void MutexLock( mutex_t *m ){ - CRITICAL_SECTION *crit; - - if ( !m ) { - return; - } - crit = (CRITICAL_SECTION *) m; - EnterCriticalSection( crit ); -} - -void MutexUnlock( mutex_t *m ){ - CRITICAL_SECTION *crit; - - if ( !m ) { - return; - } - crit = (CRITICAL_SECTION *) m; - LeaveCriticalSection( crit ); -} - -mutex_t *MutexAlloc( void ){ - CRITICAL_SECTION *crit; - - if ( numthreads == 1 ) { - return NULL; - } - crit = (CRITICAL_SECTION *) safe_malloc( sizeof( CRITICAL_SECTION ) ); - InitializeCriticalSection( crit ); - return (void *) crit; -} - -#endif - -/* - =================================================================== - - OSF1 - - =================================================================== - */ - -#ifdef __osf__ -#define USED - -#include - -void MutexLock( mutex_t *m ){ - pthread_mutex_t *my_mutex; - - if ( !m ) { - return; - } - my_mutex = (pthread_mutex_t *) m; - pthread_mutex_lock( my_mutex ); -} - -void MutexUnlock( mutex_t *m ){ - pthread_mutex_t *my_mutex; - - if ( !m ) { - return; - } - my_mutex = (pthread_mutex_t *) m; - pthread_mutex_unlock( my_mutex ); -} - -mutex_t *MutexAlloc( void ){ - pthread_mutex_t *my_mutex; - pthread_mutexattr_t mattrib; - - if ( numthreads == 1 ) { - return NULL; - } - my_mutex = safe_malloc( sizeof( *my_mutex ) ); - if ( pthread_mutexattr_create( &mattrib ) == -1 ) { - Error( "pthread_mutex_attr_create failed" ); - } - if ( pthread_mutexattr_setkind_np( &mattrib, MUTEX_FAST_NP ) == -1 ) { - Error( "pthread_mutexattr_setkind_np failed" ); - } - if ( pthread_mutex_init( my_mutex, mattrib ) == -1 ) { - Error( "pthread_mutex_init failed" ); - } - return (void *) my_mutex; -} - -#endif - -/* - =================================================================== - - IRIX - - =================================================================== - */ - -#ifdef _MIPS_ISA -#define USED - -#include -#include -#include -#include - -void MutexLock( mutex_t *m ){ - abilock_t *lck; - - if ( !m ) { - return; - } - lck = (abilock_t *) m; - spin_lock( lck ); -} - -void MutexUnlock( mutex_t *m ){ - abilock_t *lck; - - if ( !m ) { - return; - } - lck = (abilock_t *) m; - release_lock( lck ); -} - -mutex_t *MutexAlloc( void ){ - abilock_t *lck; - - if ( numthreads == 1 ) { - return NULL; - } - lck = (abilock_t *) safe_malloc( sizeof( abilock_t ) ); - init_lock( lck ); - return (void *) lck; -} - -#endif - -/* - ======================================================================= - - SINGLE THREAD - - ======================================================================= - */ - -#ifndef USED - -void MutexLock( mutex_t *m ){ -} - -void MutexUnlock( mutex_t *m ){ -} - -mutex_t *MutexAlloc( void ){ - return NULL; -} - -#endif diff --git a/tools/urt/tools/quake3/common/mutex.h b/tools/urt/tools/quake3/common/mutex.h deleted file mode 100644 index cbc23f6..0000000 --- a/tools/urt/tools/quake3/common/mutex.h +++ /dev/null @@ -1,28 +0,0 @@ -/* - Copyright (C) 1999-2007 id Software, Inc. and contributors. - For a list of contributors, see the accompanying CONTRIBUTORS file. - - This file is part of GtkRadiant. - - GtkRadiant is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - GtkRadiant is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with GtkRadiant; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - */ - - - -typedef void *mutex_t; - -void MutexLock( mutex_t *m ); -void MutexUnlock( mutex_t *m ); -mutex_t *MutexAlloc( void ); diff --git a/tools/urt/tools/quake3/common/polylib.c b/tools/urt/tools/quake3/common/polylib.c deleted file mode 100644 index a052f9a..0000000 --- a/tools/urt/tools/quake3/common/polylib.c +++ /dev/null @@ -1,753 +0,0 @@ -/* - Copyright (C) 1999-2007 id Software, Inc. and contributors. - For a list of contributors, see the accompanying CONTRIBUTORS file. - - This file is part of GtkRadiant. - - GtkRadiant is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - GtkRadiant is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with GtkRadiant; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - */ - - -#include "cmdlib.h" -#include "mathlib.h" -#include "inout.h" -#include "polylib.h" -#include "qfiles.h" - - -extern int numthreads; - -// counters are only bumped when running single threaded, -// because they are an awefull coherence problem -int c_active_windings; -int c_peak_windings; -int c_winding_allocs; -int c_winding_points; - -#define BOGUS_RANGE WORLD_SIZE - -void pw( winding_t *w ){ - int i; - for ( i = 0 ; i < w->numpoints ; i++ ) - Sys_Printf( "(%5.1f, %5.1f, %5.1f)\n",w->p[i][0], w->p[i][1],w->p[i][2] ); -} - - -/* - ============= - AllocWinding - ============= - */ -winding_t *AllocWinding( int points ){ - winding_t *w; - int s; - - if ( points >= MAX_POINTS_ON_WINDING ) { - Error( "AllocWinding failed: MAX_POINTS_ON_WINDING exceeded" ); - } - - if ( numthreads == 1 ) { - c_winding_allocs++; - c_winding_points += points; - c_active_windings++; - if ( c_active_windings > c_peak_windings ) { - c_peak_windings = c_active_windings; - } - } - s = sizeof( vec_t ) * 3 * points + sizeof( int ); - w = safe_malloc( s ); - memset( w, 0, s ); - return w; -} - -void FreeWinding( winding_t *w ){ - if ( *(unsigned *)w == 0xdeaddead ) { - Error( "FreeWinding: freed a freed winding" ); - } - *(unsigned *)w = 0xdeaddead; - - if ( numthreads == 1 ) { - c_active_windings--; - } - free( w ); -} - -/* - ============ - RemoveColinearPoints - ============ - */ -int c_removed; - -void RemoveColinearPoints( winding_t *w ){ - int i, j, k; - vec3_t v1, v2; - int nump; - vec3_t p[MAX_POINTS_ON_WINDING]; - - nump = 0; - for ( i = 0 ; i < w->numpoints ; i++ ) - { - j = ( i + 1 ) % w->numpoints; - k = ( i + w->numpoints - 1 ) % w->numpoints; - VectorSubtract( w->p[j], w->p[i], v1 ); - VectorSubtract( w->p[i], w->p[k], v2 ); - VectorNormalize( v1,v1 ); - VectorNormalize( v2,v2 ); - if ( DotProduct( v1, v2 ) < 0.999 ) { - VectorCopy( w->p[i], p[nump] ); - nump++; - } - } - - if ( nump == w->numpoints ) { - return; - } - - if ( numthreads == 1 ) { - c_removed += w->numpoints - nump; - } - w->numpoints = nump; - memcpy( w->p, p, nump * sizeof( p[0] ) ); -} - -/* - ============ - WindingPlane - ============ - */ -void WindingPlane( winding_t *w, vec3_t normal, vec_t *dist ){ - vec3_t v1, v2; - - VectorSubtract( w->p[1], w->p[0], v1 ); - VectorSubtract( w->p[2], w->p[0], v2 ); - CrossProduct( v2, v1, normal ); - VectorNormalize( normal, normal ); - *dist = DotProduct( w->p[0], normal ); - -} - -/* - ============= - WindingArea - ============= - */ -vec_t WindingArea( winding_t *w ){ - int i; - vec3_t d1, d2, cross; - vec_t total; - - total = 0; - for ( i = 2 ; i < w->numpoints ; i++ ) - { - VectorSubtract( w->p[i - 1], w->p[0], d1 ); - VectorSubtract( w->p[i], w->p[0], d2 ); - CrossProduct( d1, d2, cross ); - total += 0.5 * VectorLength( cross ); - } - return total; -} - -void WindingBounds( winding_t *w, vec3_t mins, vec3_t maxs ){ - vec_t v; - int i,j; - - mins[0] = mins[1] = mins[2] = 99999; - maxs[0] = maxs[1] = maxs[2] = -99999; - - for ( i = 0 ; i < w->numpoints ; i++ ) - { - for ( j = 0 ; j < 3 ; j++ ) - { - v = w->p[i][j]; - if ( v < mins[j] ) { - mins[j] = v; - } - if ( v > maxs[j] ) { - maxs[j] = v; - } - } - } -} - -/* - ============= - WindingCenter - ============= - */ -void WindingCenter( winding_t *w, vec3_t center ){ - int i; - float scale; - - VectorCopy( vec3_origin, center ); - for ( i = 0 ; i < w->numpoints ; i++ ) - VectorAdd( w->p[i], center, center ); - - scale = 1.0 / w->numpoints; - VectorScale( center, scale, center ); -} - -/* - ================= - BaseWindingForPlane - ================= - */ -winding_t *BaseWindingForPlane( vec3_t normal, vec_t dist ){ - int i, x; - vec_t max, v; - vec3_t org, vright, vup; - winding_t *w; - -// find the major axis - - max = -BOGUS_RANGE; - x = -1; - for ( i = 0 ; i < 3; i++ ) - { - v = fabs( normal[i] ); - if ( v > max ) { - x = i; - max = v; - } - } - if ( x == -1 ) { - Error( "BaseWindingForPlane: no axis found" ); - } - - VectorCopy( vec3_origin, vup ); - switch ( x ) - { - case 0: - case 1: - vup[2] = 1; - break; - case 2: - vup[0] = 1; - break; - } - - v = DotProduct( vup, normal ); - VectorMA( vup, -v, normal, vup ); - VectorNormalize( vup, vup ); - - VectorScale( normal, dist, org ); - - CrossProduct( vup, normal, vright ); - - VectorScale( vup, MAX_WORLD_COORD, vup ); - VectorScale( vright, MAX_WORLD_COORD, vright ); - - // project a really big axis aligned box onto the plane - w = AllocWinding( 4 ); - - VectorSubtract( org, vright, w->p[0] ); - VectorAdd( w->p[0], vup, w->p[0] ); - - VectorAdd( org, vright, w->p[1] ); - VectorAdd( w->p[1], vup, w->p[1] ); - - VectorAdd( org, vright, w->p[2] ); - VectorSubtract( w->p[2], vup, w->p[2] ); - - VectorSubtract( org, vright, w->p[3] ); - VectorSubtract( w->p[3], vup, w->p[3] ); - - w->numpoints = 4; - - return w; -} - -/* - ================== - CopyWinding - ================== - */ -winding_t *CopyWinding( winding_t *w ){ - int size; - winding_t *c; - - c = AllocWinding( w->numpoints ); - size = (int)( (winding_t *)0 )->p[w->numpoints]; - memcpy( c, w, size ); - return c; -} - -/* - ================== - ReverseWinding - ================== - */ -winding_t *ReverseWinding( winding_t *w ){ - int i; - winding_t *c; - - c = AllocWinding( w->numpoints ); - for ( i = 0 ; i < w->numpoints ; i++ ) - { - VectorCopy( w->p[w->numpoints - 1 - i], c->p[i] ); - } - c->numpoints = w->numpoints; - return c; -} - - -/* - ============= - ClipWindingEpsilon - ============= - */ -void ClipWindingEpsilon( winding_t *in, vec3_t normal, vec_t dist, - vec_t epsilon, winding_t **front, winding_t **back ){ - vec_t dists[MAX_POINTS_ON_WINDING + 4]; - int sides[MAX_POINTS_ON_WINDING + 4]; - int counts[3]; - static vec_t dot; // VC 4.2 optimizer bug if not static - int i, j; - vec_t *p1, *p2; - vec3_t mid; - winding_t *f, *b; - int maxpts; - - counts[0] = counts[1] = counts[2] = 0; - -// determine sides for each point - for ( i = 0 ; i < in->numpoints ; i++ ) - { - - dot = DotProduct( in->p[i], normal ); - dot -= dist; - dists[i] = dot; - if ( dot > epsilon ) { - sides[i] = SIDE_FRONT; - } - else if ( dot < -epsilon ) { - sides[i] = SIDE_BACK; - } - else - { - sides[i] = SIDE_ON; - } - counts[sides[i]]++; - } - sides[i] = sides[0]; - dists[i] = dists[0]; - - *front = *back = NULL; - - if ( !counts[0] ) { - *back = CopyWinding( in ); - return; - } - if ( !counts[1] ) { - *front = CopyWinding( in ); - return; - } - - maxpts = in->numpoints + 4; // cant use counts[0]+2 because - // of fp grouping errors - - *front = f = AllocWinding( maxpts ); - *back = b = AllocWinding( maxpts ); - - for ( i = 0 ; i < in->numpoints ; i++ ) - { - p1 = in->p[i]; - - if ( sides[i] == SIDE_ON ) { - VectorCopy( p1, f->p[f->numpoints] ); - f->numpoints++; - VectorCopy( p1, b->p[b->numpoints] ); - b->numpoints++; - continue; - } - - if ( sides[i] == SIDE_FRONT ) { - VectorCopy( p1, f->p[f->numpoints] ); - f->numpoints++; - } - if ( sides[i] == SIDE_BACK ) { - VectorCopy( p1, b->p[b->numpoints] ); - b->numpoints++; - } - - if ( sides[i + 1] == SIDE_ON || sides[i + 1] == sides[i] ) { - continue; - } - - // generate a split point - p2 = in->p[( i + 1 ) % in->numpoints]; - - dot = dists[i] / ( dists[i] - dists[i + 1] ); - for ( j = 0 ; j < 3 ; j++ ) - { // avoid round off error when possible - if ( normal[j] == 1 ) { - mid[j] = dist; - } - else if ( normal[j] == -1 ) { - mid[j] = -dist; - } - else{ - mid[j] = p1[j] + dot * ( p2[j] - p1[j] ); - } - } - - VectorCopy( mid, f->p[f->numpoints] ); - f->numpoints++; - VectorCopy( mid, b->p[b->numpoints] ); - b->numpoints++; - } - - if ( f->numpoints > maxpts || b->numpoints > maxpts ) { - Error( "ClipWinding: points exceeded estimate" ); - } - if ( f->numpoints > MAX_POINTS_ON_WINDING || b->numpoints > MAX_POINTS_ON_WINDING ) { - Error( "ClipWinding: MAX_POINTS_ON_WINDING" ); - } -} - - -/* - ============= - ChopWindingInPlace - ============= - */ -void ChopWindingInPlace( winding_t **inout, vec3_t normal, vec_t dist, vec_t epsilon ){ - winding_t *in; - vec_t dists[MAX_POINTS_ON_WINDING + 4]; - int sides[MAX_POINTS_ON_WINDING + 4]; - int counts[3]; - static vec_t dot; // VC 4.2 optimizer bug if not static - int i, j; - vec_t *p1, *p2; - vec3_t mid; - winding_t *f; - int maxpts; - - in = *inout; - counts[0] = counts[1] = counts[2] = 0; - -// determine sides for each point - for ( i = 0 ; i < in->numpoints ; i++ ) - { - dot = DotProduct( in->p[i], normal ); - dot -= dist; - dists[i] = dot; - if ( dot > epsilon ) { - sides[i] = SIDE_FRONT; - } - else if ( dot < -epsilon ) { - sides[i] = SIDE_BACK; - } - else - { - sides[i] = SIDE_ON; - } - counts[sides[i]]++; - } - sides[i] = sides[0]; - dists[i] = dists[0]; - - if ( !counts[0] ) { - FreeWinding( in ); - *inout = NULL; - return; - } - if ( !counts[1] ) { - return; // inout stays the same - - } - maxpts = in->numpoints + 4; // cant use counts[0]+2 because - // of fp grouping errors - - f = AllocWinding( maxpts ); - - for ( i = 0 ; i < in->numpoints ; i++ ) - { - p1 = in->p[i]; - - if ( sides[i] == SIDE_ON ) { - VectorCopy( p1, f->p[f->numpoints] ); - f->numpoints++; - continue; - } - - if ( sides[i] == SIDE_FRONT ) { - VectorCopy( p1, f->p[f->numpoints] ); - f->numpoints++; - } - - if ( sides[i + 1] == SIDE_ON || sides[i + 1] == sides[i] ) { - continue; - } - - // generate a split point - p2 = in->p[( i + 1 ) % in->numpoints]; - - dot = dists[i] / ( dists[i] - dists[i + 1] ); - for ( j = 0 ; j < 3 ; j++ ) - { // avoid round off error when possible - if ( normal[j] == 1 ) { - mid[j] = dist; - } - else if ( normal[j] == -1 ) { - mid[j] = -dist; - } - else{ - mid[j] = p1[j] + dot * ( p2[j] - p1[j] ); - } - } - - VectorCopy( mid, f->p[f->numpoints] ); - f->numpoints++; - } - - if ( f->numpoints > maxpts ) { - Error( "ClipWinding: points exceeded estimate" ); - } - if ( f->numpoints > MAX_POINTS_ON_WINDING ) { - Error( "ClipWinding: MAX_POINTS_ON_WINDING" ); - } - - FreeWinding( in ); - *inout = f; -} - - -/* - ================= - ChopWinding - - Returns the fragment of in that is on the front side - of the cliping plane. The original is freed. - ================= - */ -winding_t *ChopWinding( winding_t *in, vec3_t normal, vec_t dist ){ - winding_t *f, *b; - - ClipWindingEpsilon( in, normal, dist, ON_EPSILON, &f, &b ); - FreeWinding( in ); - if ( b ) { - FreeWinding( b ); - } - return f; -} - - -/* - ================= - CheckWinding - - ================= - */ -void CheckWinding( winding_t *w ){ - int i, j; - vec_t *p1, *p2; - vec_t d, edgedist; - vec3_t dir, edgenormal, facenormal; - vec_t area; - vec_t facedist; - - if ( w->numpoints < 3 ) { - Error( "CheckWinding: %i points",w->numpoints ); - } - - area = WindingArea( w ); - if ( area < 1 ) { - Error( "CheckWinding: %f area", area ); - } - - WindingPlane( w, facenormal, &facedist ); - - for ( i = 0 ; i < w->numpoints ; i++ ) - { - p1 = w->p[i]; - - for ( j = 0 ; j < 3 ; j++ ) - if ( p1[j] > MAX_WORLD_COORD || p1[j] < MIN_WORLD_COORD ) { - Error( "CheckFace: MAX_WORLD_COORD exceeded: %f",p1[j] ); - } - - j = i + 1 == w->numpoints ? 0 : i + 1; - - // check the point is on the face plane - d = DotProduct( p1, facenormal ) - facedist; - if ( d < -ON_EPSILON || d > ON_EPSILON ) { - Error( "CheckWinding: point off plane" ); - } - - // check the edge isnt degenerate - p2 = w->p[j]; - VectorSubtract( p2, p1, dir ); - - if ( VectorLength( dir ) < ON_EPSILON ) { - Error( "CheckWinding: degenerate edge" ); - } - - CrossProduct( facenormal, dir, edgenormal ); - VectorNormalize( edgenormal, edgenormal ); - edgedist = DotProduct( p1, edgenormal ); - edgedist += ON_EPSILON; - - // all other points must be on front side - for ( j = 0 ; j < w->numpoints ; j++ ) - { - if ( j == i ) { - continue; - } - d = DotProduct( w->p[j], edgenormal ); - if ( d > edgedist ) { - Error( "CheckWinding: non-convex" ); - } - } - } -} - - -/* - ============ - WindingOnPlaneSide - ============ - */ -int WindingOnPlaneSide( winding_t *w, vec3_t normal, vec_t dist ){ - qboolean front, back; - int i; - vec_t d; - - front = qfalse; - back = qfalse; - for ( i = 0 ; i < w->numpoints ; i++ ) - { - d = DotProduct( w->p[i], normal ) - dist; - if ( d < -ON_EPSILON ) { - if ( front ) { - return SIDE_CROSS; - } - back = qtrue; - continue; - } - if ( d > ON_EPSILON ) { - if ( back ) { - return SIDE_CROSS; - } - front = qtrue; - continue; - } - } - - if ( back ) { - return SIDE_BACK; - } - if ( front ) { - return SIDE_FRONT; - } - return SIDE_ON; -} - - -/* - ================= - AddWindingToConvexHull - - Both w and *hull are on the same plane - ================= - */ -#define MAX_HULL_POINTS 128 -void AddWindingToConvexHull( winding_t *w, winding_t **hull, vec3_t normal ) { - int i, j, k; - float *p, *copy; - vec3_t dir; - float d; - int numHullPoints, numNew; - vec3_t hullPoints[MAX_HULL_POINTS]; - vec3_t newHullPoints[MAX_HULL_POINTS]; - vec3_t hullDirs[MAX_HULL_POINTS]; - qboolean hullSide[MAX_HULL_POINTS]; - qboolean outside; - - if ( !*hull ) { - *hull = CopyWinding( w ); - return; - } - - numHullPoints = ( *hull )->numpoints; - memcpy( hullPoints, ( *hull )->p, numHullPoints * sizeof( vec3_t ) ); - - for ( i = 0 ; i < w->numpoints ; i++ ) { - p = w->p[i]; - - // calculate hull side vectors - for ( j = 0 ; j < numHullPoints ; j++ ) { - k = ( j + 1 ) % numHullPoints; - - VectorSubtract( hullPoints[k], hullPoints[j], dir ); - VectorNormalize( dir, dir ); - CrossProduct( normal, dir, hullDirs[j] ); - } - - outside = qfalse; - for ( j = 0 ; j < numHullPoints ; j++ ) { - VectorSubtract( p, hullPoints[j], dir ); - d = DotProduct( dir, hullDirs[j] ); - if ( d >= ON_EPSILON ) { - outside = qtrue; - } - if ( d >= -ON_EPSILON ) { - hullSide[j] = qtrue; - } - else { - hullSide[j] = qfalse; - } - } - - // if the point is effectively inside, do nothing - if ( !outside ) { - continue; - } - - // find the back side to front side transition - for ( j = 0 ; j < numHullPoints ; j++ ) { - if ( !hullSide[ j % numHullPoints ] && hullSide[ ( j + 1 ) % numHullPoints ] ) { - break; - } - } - if ( j == numHullPoints ) { - continue; - } - - // insert the point here - VectorCopy( p, newHullPoints[0] ); - numNew = 1; - - // copy over all points that aren't double fronts - j = ( j + 1 ) % numHullPoints; - for ( k = 0 ; k < numHullPoints ; k++ ) { - if ( hullSide[ ( j + k ) % numHullPoints ] && hullSide[ ( j + k + 1 ) % numHullPoints ] ) { - continue; - } - copy = hullPoints[ ( j + k + 1 ) % numHullPoints ]; - VectorCopy( copy, newHullPoints[numNew] ); - numNew++; - } - - numHullPoints = numNew; - memcpy( hullPoints, newHullPoints, numHullPoints * sizeof( vec3_t ) ); - } - - FreeWinding( *hull ); - w = AllocWinding( numHullPoints ); - w->numpoints = numHullPoints; - *hull = w; - memcpy( w->p, hullPoints, numHullPoints * sizeof( vec3_t ) ); -} diff --git a/tools/urt/tools/quake3/common/polylib.h b/tools/urt/tools/quake3/common/polylib.h deleted file mode 100644 index 68676b2..0000000 --- a/tools/urt/tools/quake3/common/polylib.h +++ /dev/null @@ -1,57 +0,0 @@ -/* - Copyright (C) 1999-2007 id Software, Inc. and contributors. - For a list of contributors, see the accompanying CONTRIBUTORS file. - - This file is part of GtkRadiant. - - GtkRadiant is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - GtkRadiant is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with GtkRadiant; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - */ - - -typedef struct -{ - int numpoints; - vec3_t p[4]; // variable sized -} winding_t; - -#define MAX_POINTS_ON_WINDING 64 - -// you can define on_epsilon in the makefile as tighter -#ifndef ON_EPSILON -#define ON_EPSILON 0.1 -#endif - -winding_t *AllocWinding( int points ); -vec_t WindingArea( winding_t *w ); -void WindingCenter( winding_t *w, vec3_t center ); -void ClipWindingEpsilon( winding_t *in, vec3_t normal, vec_t dist, - vec_t epsilon, winding_t **front, winding_t **back ); -winding_t *ChopWinding( winding_t *in, vec3_t normal, vec_t dist ); -winding_t *CopyWinding( winding_t *w ); -winding_t *ReverseWinding( winding_t *w ); -winding_t *BaseWindingForPlane( vec3_t normal, vec_t dist ); -void CheckWinding( winding_t *w ); -void WindingPlane( winding_t *w, vec3_t normal, vec_t *dist ); -void RemoveColinearPoints( winding_t *w ); -int WindingOnPlaneSide( winding_t *w, vec3_t normal, vec_t dist ); -void FreeWinding( winding_t *w ); -void WindingBounds( winding_t *w, vec3_t mins, vec3_t maxs ); - -void AddWindingToConvexHull( winding_t *w, winding_t **hull, vec3_t normal ); - -void ChopWindingInPlace( winding_t **w, vec3_t normal, vec_t dist, vec_t epsilon ); -// frees the original if clipped - -void pw( winding_t *w ); diff --git a/tools/urt/tools/quake3/common/polyset.h b/tools/urt/tools/quake3/common/polyset.h deleted file mode 100644 index 089d0e6..0000000 --- a/tools/urt/tools/quake3/common/polyset.h +++ /dev/null @@ -1,51 +0,0 @@ -/* - Copyright (C) 1999-2007 id Software, Inc. and contributors. - For a list of contributors, see the accompanying CONTRIBUTORS file. - - This file is part of GtkRadiant. - - GtkRadiant is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - GtkRadiant is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with GtkRadiant; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - */ - -#ifndef __POLYSET_H__ -#define __POLYSET_H__ - -#define POLYSET_MAXTRIANGLES 4096 -#define POLYSET_MAXPOLYSETS 64 - -typedef float st_t[2]; -typedef float rgb_t[3]; - -typedef struct { - vec3_t verts[3]; - vec3_t normals[3]; - st_t texcoords[3]; -} triangle_t; - -typedef struct -{ - char name[100]; - char materialname[100]; - triangle_t *triangles; - int numtriangles; -} polyset_t; - -polyset_t *Polyset_LoadSets( const char *file, int *numpolysets, int maxTrisPerSet ); -polyset_t *Polyset_CollapseSets( polyset_t *psets, int numpolysets ); -polyset_t *Polyset_SplitSets( polyset_t *psets, int numpolysets, int *pNumNewPolysets, int maxTris ); -void Polyset_SnapSets( polyset_t *psets, int numpolysets ); -void Polyset_ComputeNormals( polyset_t *psets, int numpolysets ); - -#endif diff --git a/tools/urt/tools/quake3/common/qfiles.h b/tools/urt/tools/quake3/common/qfiles.h deleted file mode 100644 index 202351c..0000000 --- a/tools/urt/tools/quake3/common/qfiles.h +++ /dev/null @@ -1,489 +0,0 @@ -/* - Copyright (C) 1999-2007 id Software, Inc. and contributors. - For a list of contributors, see the accompanying CONTRIBUTORS file. - - This file is part of GtkRadiant. - - GtkRadiant is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - GtkRadiant is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with GtkRadiant; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - */ - -#ifndef __QFILES_H__ -#define __QFILES_H__ - -// -// qfiles.h: quake file formats -// This file must be identical in the quake and utils directories -// - -// surface geometry should not exceed these limits -#define SHADER_MAX_VERTEXES 1000 -#define SHADER_MAX_INDEXES ( 6 * SHADER_MAX_VERTEXES ) - - -// the maximum size of game reletive pathnames -#define MAX_QPATH 64 - -/* - ======================================================================== - - QVM files - - ======================================================================== - */ - -#define VM_MAGIC 0x12721444 -typedef struct { - int vmMagic; - - int instructionCount; - - int codeOffset; - int codeLength; - - int dataOffset; - int dataLength; - int litLength; // ( dataLength - litLength ) should be byteswapped on load - int bssLength; // zero filled memory appended to datalength -} vmHeader_t; - - -/* - ======================================================================== - - PCX files are used for 8 bit images - - ======================================================================== - */ - -typedef struct { - char manufacturer; - char version; - char encoding; - char bits_per_pixel; - unsigned short xmin,ymin,xmax,ymax; - unsigned short hres,vres; - unsigned char palette[48]; - char reserved; - char color_planes; - unsigned short bytes_per_line; - unsigned short palette_type; - char filler[58]; - unsigned char data; // unbounded -} pcx_t; - - -/* - ======================================================================== - - TGA files are used for 24/32 bit images - - ======================================================================== - */ - -typedef struct _TargaHeader { - unsigned char id_length, colormap_type, image_type; - unsigned short colormap_index, colormap_length; - unsigned char colormap_size; - unsigned short x_origin, y_origin, width, height; - unsigned char pixel_size, attributes; -} TargaHeader; - - - -/* - ======================================================================== - - .MD3 triangle model file format - - ======================================================================== - */ - -#define MD3_IDENT ( ( '3' << 24 ) + ( 'P' << 16 ) + ( 'D' << 8 ) + 'I' ) -#define MD3_VERSION 15 - -// limits -#define MD3_MAX_LODS 4 -#define MD3_MAX_TRIANGLES 8192 // per surface -#define MD3_MAX_VERTS 4096 // per surface -#define MD3_MAX_SHADERS 256 // per surface -#define MD3_MAX_FRAMES 1024 // per model -#define MD3_MAX_SURFACES 32 // per model -#define MD3_MAX_TAGS 16 // per frame - -// vertex scales -#define MD3_XYZ_SCALE ( 1.0 / 64 ) - -typedef struct md3Frame_s { - vec3_t bounds[2]; - vec3_t localOrigin; - float radius; - char name[16]; -} md3Frame_t; - -typedef struct md3Tag_s { - char name[MAX_QPATH]; // tag name - vec3_t origin; - vec3_t axis[3]; -} md3Tag_t; - -/* -** md3Surface_t -** -** CHUNK SIZE -** header sizeof( md3Surface_t ) -** shaders sizeof( md3Shader_t ) * numShaders -** triangles[0] sizeof( md3Triangle_t ) * numTriangles -** st sizeof( md3St_t ) * numVerts -** XyzNormals sizeof( md3XyzNormal_t ) * numVerts * numFrames -*/ -typedef struct { - int ident; // - - char name[MAX_QPATH]; // polyset name - - int flags; - int numFrames; // all surfaces in a model should have the same - - int numShaders; // all surfaces in a model should have the same - int numVerts; - - int numTriangles; - int ofsTriangles; - - int ofsShaders; // offset from start of md3Surface_t - int ofsSt; // texture coords are common for all frames - int ofsXyzNormals; // numVerts * numFrames - - int ofsEnd; // next surface follows -} md3Surface_t; - -typedef struct { - char name[MAX_QPATH]; - int shaderIndex; // for in-game use -} md3Shader_t; - -typedef struct { - int indexes[3]; -} md3Triangle_t; - -typedef struct { - float st[2]; -} md3St_t; - -typedef struct { - short xyz[3]; - short normal; -} md3XyzNormal_t; - -typedef struct { - int ident; - int version; - - char name[MAX_QPATH]; // model name - - int flags; - - int numFrames; - int numTags; - int numSurfaces; - - int numSkins; - - int ofsFrames; // offset for first frame - int ofsTags; // numFrames * numTags - int ofsSurfaces; // first surface, others follow - - int ofsEnd; // end of file -} md3Header_t; - -/* - ============================================================================== - - MD4 file format - - ============================================================================== - */ - -#define MD4_IDENT ( ( '4' << 24 ) + ( 'P' << 16 ) + ( 'D' << 8 ) + 'I' ) -#define MD4_VERSION 1 -#define MD4_MAX_BONES 128 - -typedef struct { - int boneIndex; // these are indexes into the boneReferences, - float boneWeight; // not the global per-frame bone list -} md4Weight_t; - -typedef struct { - vec3_t vertex; - vec3_t normal; - float texCoords[2]; - int numWeights; - md4Weight_t weights[1]; // variable sized -} md4Vertex_t; - -typedef struct { - int indexes[3]; -} md4Triangle_t; - -typedef struct { - int ident; - - char name[MAX_QPATH]; // polyset name - char shader[MAX_QPATH]; - int shaderIndex; // for in-game use - - int ofsHeader; // this will be a negative number - - int numVerts; - int ofsVerts; - - int numTriangles; - int ofsTriangles; - - // Bone references are a set of ints representing all the bones - // present in any vertex weights for this surface. This is - // needed because a model may have surfaces that need to be - // drawn at different sort times, and we don't want to have - // to re-interpolate all the bones for each surface. - int numBoneReferences; - int ofsBoneReferences; - - int ofsEnd; // next surface follows -} md4Surface_t; - -typedef struct { - float matrix[3][4]; -} md4Bone_t; - -typedef struct { - vec3_t bounds[2]; // bounds of all surfaces of all LOD's for this frame - vec3_t localOrigin; // midpoint of bounds, used for sphere cull - float radius; // dist from localOrigin to corner - char name[16]; - md4Bone_t bones[1]; // [numBones] -} md4Frame_t; - -typedef struct { - int numSurfaces; - int ofsSurfaces; // first surface, others follow - int ofsEnd; // next lod follows -} md4LOD_t; - -typedef struct { - int ident; - int version; - - char name[MAX_QPATH]; // model name - - // frames and bones are shared by all levels of detail - int numFrames; - int numBones; - int ofsFrames; // md4Frame_t[numFrames] - - // each level of detail has completely separate sets of surfaces - int numLODs; - int ofsLODs; - - int ofsEnd; // end of file -} md4Header_t; - - -/* - ============================================================================== - - .BSP file format - - ============================================================================== - */ - - -#define BSP_IDENT ( ( 'P' << 24 ) + ( 'S' << 16 ) + ( 'B' << 8 ) + 'I' ) -// little-endian "IBSP" - -//#define BSP_VERSION 46 -#define Q3_BSP_VERSION 46 -#define WOLF_BSP_VERSION 47 - -// there shouldn't be any problem with increasing these values at the -// expense of more memory allocation in the utilities -#define MAX_MAP_MODELS 0x400 -#define MAX_MAP_BRUSHES 0x8000 -#define MAX_MAP_ENTITIES 0x800 -#define MAX_MAP_ENTSTRING 0x40000 -#define MAX_MAP_SHADERS 0x400 - -#define MAX_MAP_AREAS 0x100 // MAX_MAP_AREA_BYTES in q_shared must match! -#define MAX_MAP_FOGS 0x100 -#define MAX_MAP_PLANES 0x20000 -#define MAX_MAP_NODES 0x20000 -#define MAX_MAP_BRUSHSIDES 0x40000 //% 0x20000 /* ydnar */ -#define MAX_MAP_LEAFS 0x20000 -#define MAX_MAP_LEAFFACES 0x20000 -#define MAX_MAP_LEAFBRUSHES 0x40000 -#define MAX_MAP_PORTALS 0x20000 -#define MAX_MAP_LIGHTING 0x800000 -#define MAX_MAP_LIGHTGRID 0x800000 -#define MAX_MAP_VISIBILITY 0x200000 - -#define MAX_MAP_DRAW_SURFS 0x20000 -#define MAX_MAP_DRAW_VERTS 0x80000 -#define MAX_MAP_DRAW_INDEXES 0x80000 - - -// key / value pair sizes in the entities lump -#define MAX_KEY 32 -#define MAX_VALUE 1024 - -// the editor uses these predefined yaw angles to orient entities up or down -#define ANGLE_UP -1 -#define ANGLE_DOWN -2 - -#define LIGHTMAP_WIDTH 128 -#define LIGHTMAP_HEIGHT 128 - -#define MIN_WORLD_COORD ( -65536 ) -#define MAX_WORLD_COORD ( 65536 ) -#define WORLD_SIZE ( MAX_WORLD_COORD - MIN_WORLD_COORD ) - -//============================================================================= - - -typedef struct { - int fileofs, filelen; -} lump_t; - -#define LUMP_ENTITIES 0 -#define LUMP_SHADERS 1 -#define LUMP_PLANES 2 -#define LUMP_NODES 3 -#define LUMP_LEAFS 4 -#define LUMP_LEAFSURFACES 5 -#define LUMP_LEAFBRUSHES 6 -#define LUMP_MODELS 7 -#define LUMP_BRUSHES 8 -#define LUMP_BRUSHSIDES 9 -#define LUMP_DRAWVERTS 10 -#define LUMP_DRAWINDEXES 11 -#define LUMP_FOGS 12 -#define LUMP_SURFACES 13 -#define LUMP_LIGHTMAPS 14 -#define LUMP_LIGHTGRID 15 -#define LUMP_VISIBILITY 16 -#define HEADER_LUMPS 17 - -typedef struct { - int ident; - int version; - - lump_t lumps[HEADER_LUMPS]; -} dheader_t; - -typedef struct { - float mins[3], maxs[3]; - int firstSurface, numSurfaces; - int firstBrush, numBrushes; -} dmodel_t; - -typedef struct { - char shader[MAX_QPATH]; - int surfaceFlags; - int contentFlags; -} dshader_t; - -// planes x^1 is allways the opposite of plane x - -typedef struct { - float normal[3]; - float dist; -} dplane_t; - -typedef struct { - int planeNum; - int children[2]; // negative numbers are -(leafs+1), not nodes - int mins[3]; // for frustom culling - int maxs[3]; -} dnode_t; - -typedef struct { - int cluster; // -1 = opaque cluster (do I still store these?) - int area; - - int mins[3]; // for frustum culling - int maxs[3]; - - int firstLeafSurface; - int numLeafSurfaces; - - int firstLeafBrush; - int numLeafBrushes; -} dleaf_t; - -typedef struct { - int planeNum; // positive plane side faces out of the leaf - int shaderNum; -} dbrushside_t; - -typedef struct { - int firstSide; - int numSides; - int shaderNum; // the shader that determines the contents flags -} dbrush_t; - -typedef struct { - char shader[MAX_QPATH]; - int brushNum; - int visibleSide; // the brush side that ray tests need to clip against (-1 == none) -} dfog_t; - -typedef struct { - vec3_t xyz; - float st[2]; - float lightmap[2]; - vec3_t normal; - byte color[4]; -} drawVert_t; - -typedef enum { - MST_BAD, - MST_PLANAR, - MST_PATCH, - MST_TRIANGLE_SOUP, - MST_FLARE -} mapSurfaceType_t; - -typedef struct { - int shaderNum; - int fogNum; - int surfaceType; - - int firstVert; - int numVerts; - - int firstIndex; - int numIndexes; - - int lightmapNum; - int lightmapX, lightmapY; - int lightmapWidth, lightmapHeight; - - vec3_t lightmapOrigin; - vec3_t lightmapVecs[3]; // for patches, [0] and [1] are lodbounds - - int patchWidth; - int patchHeight; -} dsurface_t; - - -#endif diff --git a/tools/urt/tools/quake3/common/qthreads.h b/tools/urt/tools/quake3/common/qthreads.h deleted file mode 100644 index 823cb63..0000000 --- a/tools/urt/tools/quake3/common/qthreads.h +++ /dev/null @@ -1,30 +0,0 @@ -/* - Copyright (C) 1999-2007 id Software, Inc. and contributors. - For a list of contributors, see the accompanying CONTRIBUTORS file. - - This file is part of GtkRadiant. - - GtkRadiant is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - GtkRadiant is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with GtkRadiant; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - */ - - -extern int numthreads; - -void ThreadSetDefault( void ); -int GetThreadWork( void ); -void RunThreadsOnIndividual( int workcnt, qboolean showpacifier, void ( *func )( int ) ); -void RunThreadsOn( int workcnt, qboolean showpacifier, void ( *func )( int ) ); -void ThreadLock( void ); -void ThreadUnlock( void ); diff --git a/tools/urt/tools/quake3/common/scriplib.c b/tools/urt/tools/quake3/common/scriplib.c deleted file mode 100644 index 2a18e96..0000000 --- a/tools/urt/tools/quake3/common/scriplib.c +++ /dev/null @@ -1,416 +0,0 @@ -/* - Copyright (C) 1999-2007 id Software, Inc. and contributors. - For a list of contributors, see the accompanying CONTRIBUTORS file. - - This file is part of GtkRadiant. - - GtkRadiant is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - GtkRadiant is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with GtkRadiant; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - */ - -// scriplib.c - -#include "cmdlib.h" -#include "mathlib.h" -#include "inout.h" -#include "scriplib.h" -#include "vfs.h" - -/* - ============================================================================= - - PARSING STUFF - - ============================================================================= - */ - -typedef struct -{ - char filename[1024]; - char *buffer,*script_p,*end_p; - int line; -} script_t; - -#define MAX_INCLUDES 8 -script_t scriptstack[MAX_INCLUDES]; -script_t *script; -int scriptline; - -char token[MAXTOKEN]; -qboolean endofscript; -qboolean tokenready; // only qtrue if UnGetToken was just called - -/* - ============== - AddScriptToStack - ============== - */ -void AddScriptToStack( const char *filename, int index ){ - int size; - - script++; - if ( script == &scriptstack[MAX_INCLUDES] ) { - Error( "script file exceeded MAX_INCLUDES" ); - } - strcpy( script->filename, ExpandPath( filename ) ); - - size = vfsLoadFile( script->filename, (void **)&script->buffer, index ); - - if ( size == -1 ) { - Sys_Printf( "Script file %s was not found\n", script->filename ); - } - else - { - if ( index > 0 ) { - Sys_Printf( "entering %s (%d)\n", script->filename, index + 1 ); - } - else{ - Sys_Printf( "entering %s\n", script->filename ); - } - } - - script->line = 1; - script->script_p = script->buffer; - script->end_p = script->buffer + size; -} - - -/* - ============== - LoadScriptFile - ============== - */ -void LoadScriptFile( const char *filename, int index ){ - script = scriptstack; - AddScriptToStack( filename, index ); - - endofscript = qfalse; - tokenready = qfalse; -} - - -/* - ============== - ParseFromMemory - ============== - */ -void ParseFromMemory( char *buffer, int size ){ - script = scriptstack; - script++; - if ( script == &scriptstack[MAX_INCLUDES] ) { - Error( "script file exceeded MAX_INCLUDES" ); - } - strcpy( script->filename, "memory buffer" ); - - script->buffer = buffer; - script->line = 1; - script->script_p = script->buffer; - script->end_p = script->buffer + size; - - endofscript = qfalse; - tokenready = qfalse; -} - - -/* - ============== - UnGetToken - - Signals that the current token was not used, and should be reported - for the next GetToken. Note that - - GetToken (qtrue); - UnGetToken (); - GetToken (qfalse); - - could cross a line boundary. - ============== - */ -void UnGetToken( void ){ - tokenready = qtrue; -} - - -qboolean EndOfScript( qboolean crossline ){ - if ( !crossline ) { - Error( "Line %i is incomplete\n",scriptline ); - } - - if ( !strcmp( script->filename, "memory buffer" ) ) { - endofscript = qtrue; - return qfalse; - } - - if ( script->buffer == NULL ) { - Sys_Printf( "WARNING: Attempt to free already freed script buffer\n" ); - } - else{ - free( script->buffer ); - } - script->buffer = NULL; - if ( script == scriptstack + 1 ) { - endofscript = qtrue; - return qfalse; - } - script--; - scriptline = script->line; - Sys_Printf( "returning to %s\n", script->filename ); - return GetToken( crossline ); -} - -/* - ============== - GetToken - ============== - */ -qboolean GetToken( qboolean crossline ){ - char *token_p; - - - /* ydnar: dummy testing */ - if ( script == NULL || script->buffer == NULL ) { - return qfalse; - } - - if ( tokenready ) { // is a token already waiting? - tokenready = qfalse; - return qtrue; - } - - if ( ( script->script_p >= script->end_p ) || ( script->script_p == NULL ) ) { - return EndOfScript( crossline ); - } - -// -// skip space -// -skipspace: - while ( *script->script_p <= 32 ) - { - if ( script->script_p >= script->end_p ) { - return EndOfScript( crossline ); - } - if ( *script->script_p++ == '\n' ) { - if ( !crossline ) { - Error( "Line %i is incomplete\n",scriptline ); - } - script->line++; - scriptline = script->line; - } - } - - if ( script->script_p >= script->end_p ) { - return EndOfScript( crossline ); - } - - // ; # // comments - if ( *script->script_p == ';' || *script->script_p == '#' - || ( script->script_p[0] == '/' && script->script_p[1] == '/' ) ) { - if ( !crossline ) { - Error( "Line %i is incomplete\n",scriptline ); - } - while ( *script->script_p++ != '\n' ) - if ( script->script_p >= script->end_p ) { - return EndOfScript( crossline ); - } - script->line++; - scriptline = script->line; - goto skipspace; - } - - // /* */ comments - if ( script->script_p[0] == '/' && script->script_p[1] == '*' ) { - if ( !crossline ) { - Error( "Line %i is incomplete\n",scriptline ); - } - script->script_p += 2; - while ( script->script_p[0] != '*' && script->script_p[1] != '/' ) - { - if ( *script->script_p == '\n' ) { - script->line++; - scriptline = script->line; - } - script->script_p++; - if ( script->script_p >= script->end_p ) { - return EndOfScript( crossline ); - } - } - script->script_p += 2; - goto skipspace; - } - -// -// copy token -// - token_p = token; - - if ( *script->script_p == '"' ) { - // quoted token - script->script_p++; - while ( *script->script_p != '"' ) - { - *token_p++ = *script->script_p++; - if ( script->script_p == script->end_p ) { - break; - } - if ( token_p == &token[MAXTOKEN] ) { - Error( "Token too large on line %i\n",scriptline ); - } - } - script->script_p++; - } - else{ // regular token - while ( *script->script_p > 32 && *script->script_p != ';' ) - { - *token_p++ = *script->script_p++; - if ( script->script_p == script->end_p ) { - break; - } - if ( token_p == &token[MAXTOKEN] ) { - Error( "Token too large on line %i\n",scriptline ); - } - } - } - - *token_p = 0; - - if ( !strcmp( token, "$include" ) ) { - GetToken( qfalse ); - AddScriptToStack( token, 0 ); - return GetToken( crossline ); - } - - return qtrue; -} - - -/* - ============== - TokenAvailable - - Returns qtrue if there is another token on the line - ============== - */ -qboolean TokenAvailable( void ) { - int oldLine, oldScriptLine; - qboolean r; - - /* save */ - oldLine = scriptline; - oldScriptLine = script->line; - - /* test */ - r = GetToken( qtrue ); - if ( !r ) { - return qfalse; - } - UnGetToken(); - if ( oldLine == scriptline ) { - return qtrue; - } - - /* restore */ - //% scriptline = oldLine; - //% script->line = oldScriptLine; - - return qfalse; -} - - -//===================================================================== - - -void MatchToken( char *match ) { - GetToken( qtrue ); - - if ( strcmp( token, match ) ) { - Error( "MatchToken( \"%s\" ) failed at line %i in file %s", match, scriptline, script->filename ); - } -} - - -void Parse1DMatrix( int x, vec_t *m ) { - int i; - - MatchToken( "(" ); - - for ( i = 0 ; i < x ; i++ ) { - GetToken( qfalse ); - m[i] = atof( token ); - } - - MatchToken( ")" ); -} - -void Parse2DMatrix( int y, int x, vec_t *m ) { - int i; - - MatchToken( "(" ); - - for ( i = 0 ; i < y ; i++ ) { - Parse1DMatrix( x, m + i * x ); - } - - MatchToken( ")" ); -} - -void Parse3DMatrix( int z, int y, int x, vec_t *m ) { - int i; - - MatchToken( "(" ); - - for ( i = 0 ; i < z ; i++ ) { - Parse2DMatrix( y, x, m + i * x * y ); - } - - MatchToken( ")" ); -} - - -void Write1DMatrix( FILE *f, int x, vec_t *m ) { - int i; - - fprintf( f, "( " ); - for ( i = 0 ; i < x ; i++ ) { - if ( m[i] == (int)m[i] ) { - fprintf( f, "%i ", (int)m[i] ); - } - else { - fprintf( f, "%f ", m[i] ); - } - } - fprintf( f, ")" ); -} - -void Write2DMatrix( FILE *f, int y, int x, vec_t *m ) { - int i; - - fprintf( f, "( " ); - for ( i = 0 ; i < y ; i++ ) { - Write1DMatrix( f, x, m + i * x ); - fprintf( f, " " ); - } - fprintf( f, ")\n" ); -} - - -void Write3DMatrix( FILE *f, int z, int y, int x, vec_t *m ) { - int i; - - fprintf( f, "(\n" ); - for ( i = 0 ; i < z ; i++ ) { - Write2DMatrix( f, y, x, m + i * ( x * y ) ); - } - fprintf( f, ")\n" ); -} diff --git a/tools/urt/tools/quake3/common/scriplib.h b/tools/urt/tools/quake3/common/scriplib.h deleted file mode 100644 index dc9b234..0000000 --- a/tools/urt/tools/quake3/common/scriplib.h +++ /dev/null @@ -1,55 +0,0 @@ -/* - Copyright (C) 1999-2007 id Software, Inc. and contributors. - For a list of contributors, see the accompanying CONTRIBUTORS file. - - This file is part of GtkRadiant. - - GtkRadiant is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - GtkRadiant is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with GtkRadiant; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - */ - -// scriplib.h - -#ifndef __CMDLIB__ -#include "../common/cmdlib.h" -#endif -#ifndef __MATHLIB__ -#include "mathlib.h" -#endif - -#define MAXTOKEN 1024 - -extern char token[MAXTOKEN]; -extern char *scriptbuffer,*script_p,*scriptend_p; -extern int grabbed; -extern int scriptline; -extern qboolean endofscript; - - -void LoadScriptFile( const char *filename, int index ); -void ParseFromMemory( char *buffer, int size ); - -qboolean GetToken( qboolean crossline ); -void UnGetToken( void ); -qboolean TokenAvailable( void ); - -void MatchToken( char *match ); - -void Parse1DMatrix( int x, vec_t *m ); -void Parse2DMatrix( int y, int x, vec_t *m ); -void Parse3DMatrix( int z, int y, int x, vec_t *m ); - -void Write1DMatrix( FILE *f, int x, vec_t *m ); -void Write2DMatrix( FILE *f, int y, int x, vec_t *m ); -void Write3DMatrix( FILE *f, int z, int y, int x, vec_t *m ); diff --git a/tools/urt/tools/quake3/common/surfaceflags.h b/tools/urt/tools/quake3/common/surfaceflags.h deleted file mode 100644 index 12b9c25..0000000 --- a/tools/urt/tools/quake3/common/surfaceflags.h +++ /dev/null @@ -1,112 +0,0 @@ -/* - Copyright (C) 1999-2007 id Software, Inc. and contributors. - For a list of contributors, see the accompanying CONTRIBUTORS file. - - This file is part of GtkRadiant. - - GtkRadiant is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - GtkRadiant is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with GtkRadiant; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - */ - -// Copyright (C) 1999-2000 Id Software, Inc. -// -// This file must be identical in the quake and utils directories - -// contents flags are seperate bits -// a given brush can contribute multiple content bits - -// these definitions also need to be in q_shared.h! - -#define CONTENTS_SOLID 1 // an eye is never valid in a solid -#define CONTENTS_LAVA 8 -#define CONTENTS_SLIME 16 -#define CONTENTS_WATER 32 -#define CONTENTS_FOG 64 - -#define CONTENTS_AREAPORTAL 0x8000 - -#define CONTENTS_PLAYERCLIP 0x10000 -#define CONTENTS_MONSTERCLIP 0x20000 -//bot specific contents types -#define CONTENTS_TELEPORTER 0x40000 -#define CONTENTS_JUMPPAD 0x80000 -#define CONTENTS_CLUSTERPORTAL 0x100000 -#define CONTENTS_DONOTENTER 0x200000 -#define CONTENTS_BOTCLIP 0x400000 - -#define CONTENTS_ORIGIN 0x1000000 // removed before bsping an entity - -#define CONTENTS_BODY 0x2000000 // should never be on a brush, only in game -#define CONTENTS_CORPSE 0x4000000 -#define CONTENTS_DETAIL 0x8000000 // brushes not used for the bsp -#define CONTENTS_STRUCTURAL 0x10000000 // brushes used for the bsp -#define CONTENTS_TRANSLUCENT 0x20000000 // don't consume surface fragments inside -#define CONTENTS_TRIGGER 0x40000000 -#define CONTENTS_NODROP 0x80000000 // don't leave bodies or items (death fog, lava) - -#define SURF_NODAMAGE 0x1 // never give falling damage -#define SURF_SLICK 0x2 // effects game physics -#define SURF_SKY 0x4 // lighting from environment map -#define SURF_LADDER 0x8 -#define SURF_NOIMPACT 0x10 // don't make missile explosions -#define SURF_NOMARKS 0x20 // don't leave missile marks -#define SURF_FLESH 0x40 // make flesh sounds and effects -#define SURF_NODRAW 0x80 // don't generate a drawsurface at all -#define SURF_HINT 0x100 // make a primary bsp splitter -#define SURF_SKIP 0x200 // completely ignore, allowing non-closed brushes -#define SURF_NOLIGHTMAP 0x400 // surface doesn't need a lightmap -#define SURF_POINTLIGHT 0x800 // generate lighting info at vertexes -#define SURF_METALSTEPS 0x1000 // clanking footsteps -#define SURF_NOSTEPS 0x2000 // no footstep sounds -#define SURF_NONSOLID 0x4000 // don't collide against curves with this set -#define SURF_LIGHTFILTER 0x8000 // act as a light filter during q3map -light -#define SURF_ALPHASHADOW 0x10000 // do per-pixel light shadow casting in q3map -#define SURF_NODLIGHT 0x20000 // don't dlight even if solid (solid lava, skies) -#define SURF_DUST 0x40000 // leave a dust trail when walking on this surface - - - - -/* ydnar flags */ - -#define CONTENTS_OPAQUE 0x02 -#define CONTENTS_LIGHTGRID 0x04 - -#define SURF_VERTEXLIT ( SURF_POINTLIGHT | SURF_NOLIGHTMAP ) - - - -/* wolfenstein flags (collisions with valid q3a flags are noted) */ - -#define CONTENTS_MISSILECLIP 0x80 -#define CONTENTS_ITEM 0x100 -#define CONTENTS_AI_NOSIGHT 0x1000 -#define CONTENTS_CLIPSHOT 0x2000 -#define CONTENTS_DONOTENTER_LARGE 0x400000 /* CONTENTS_BOTCLIP */ - -#define SURF_CERAMIC 0x40 /* SURF_FLESH */ -#define SURF_METAL 0x1000 /* SURF_METALSTEPS */ -#define SURF_WOOD 0x40000 /* SURF_DUST */ -#define SURF_GRASS 0x80000 -#define SURF_GRAVEL 0x100000 -#define SURF_GLASS 0x200000 -#define SURF_SNOW 0x400000 -#define SURF_ROOF 0x800000 -#define SURF_RUBBLE 0x1000000 -#define SURF_CARPET 0x2000000 -#define SURF_MONSTERSLICK 0x4000000 -#define SURF_MONSLICK_W 0x8000000 -#define SURF_MONSLICK_N 0x10000000 -#define SURF_MONSLICK_E 0x20000000 -#define SURF_MONSLICK_S 0x40000000 diff --git a/tools/urt/tools/quake3/common/threads.c b/tools/urt/tools/quake3/common/threads.c deleted file mode 100644 index 83a3646..0000000 --- a/tools/urt/tools/quake3/common/threads.c +++ /dev/null @@ -1,619 +0,0 @@ -/* - Copyright (C) 1999-2007 id Software, Inc. and contributors. - For a list of contributors, see the accompanying CONTRIBUTORS file. - - This file is part of GtkRadiant. - - GtkRadiant is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - GtkRadiant is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with GtkRadiant; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - */ - -#ifndef WIN32 -// The below define is necessary to use -// pthreads extensions like pthread_mutexattr_settype -#define _GNU_SOURCE -#include -#endif - -#include "cmdlib.h" -#include "mathlib.h" -#include "inout.h" -#include "qthreads.h" - -#define MAX_THREADS 64 - -int dispatch; -int workcount; -int oldf; -qboolean pacifier; - -qboolean threaded; - -/* - ============= - GetThreadWork - - ============= - */ -int GetThreadWork( void ){ - int r; - int f; - - ThreadLock(); - - if ( dispatch == workcount ) { - ThreadUnlock(); - return -1; - } - - f = 10 * dispatch / workcount; - if ( f != oldf ) { - oldf = f; - if ( pacifier ) { - Sys_Printf( "%i...", f ); - fflush( stdout ); /* ydnar */ - } - } - - r = dispatch; - dispatch++; - ThreadUnlock(); - - return r; -} - - -void ( *workfunction )( int ); - -void ThreadWorkerFunction( int threadnum ){ - int work; - - while ( 1 ) - { - work = GetThreadWork(); - if ( work == -1 ) { - break; - } -//Sys_Printf ("thread %i, work %i\n", threadnum, work); - workfunction( work ); - } -} - -void RunThreadsOnIndividual( int workcnt, qboolean showpacifier, void ( *func )( int ) ){ - if ( numthreads == -1 ) { - ThreadSetDefault(); - } - workfunction = func; - RunThreadsOn( workcnt, showpacifier, ThreadWorkerFunction ); -} - - -/* - =================================================================== - - WIN32 - - =================================================================== - */ -#ifdef WIN32 - -#define USED - -#include - -int numthreads = -1; -CRITICAL_SECTION crit; -static int enter; - -void ThreadSetDefault( void ){ - SYSTEM_INFO info; - - if ( numthreads == -1 ) { // not set manually - GetSystemInfo( &info ); - numthreads = info.dwNumberOfProcessors; - if ( numthreads < 1 || numthreads > 32 ) { - numthreads = 1; - } - } - - Sys_Printf( "%i threads\n", numthreads ); -} - - -void ThreadLock( void ){ - if ( !threaded ) { - return; - } - EnterCriticalSection( &crit ); - if ( enter ) { - Error( "Recursive ThreadLock\n" ); - } - enter = 1; -} - -void ThreadUnlock( void ){ - if ( !threaded ) { - return; - } - if ( !enter ) { - Error( "ThreadUnlock without lock\n" ); - } - enter = 0; - LeaveCriticalSection( &crit ); -} - -/* - ============= - RunThreadsOn - ============= - */ -void RunThreadsOn( int workcnt, qboolean showpacifier, void ( *func )( int ) ){ - int threadid[MAX_THREADS]; - HANDLE threadhandle[MAX_THREADS]; - int i; - int start, end; - - start = I_FloatTime(); - dispatch = 0; - workcount = workcnt; - oldf = -1; - pacifier = showpacifier; - threaded = qtrue; - - // - // run threads in parallel - // - InitializeCriticalSection( &crit ); - - if ( numthreads == 1 ) { // use same thread - func( 0 ); - } - else - { - for ( i = 0 ; i < numthreads ; i++ ) - { - threadhandle[i] = CreateThread( - NULL, // LPSECURITY_ATTRIBUTES lpsa, - //0, // DWORD cbStack, - - /* ydnar: cranking stack size to eliminate radiosity crash with 1MB stack on win32 */ - ( 4096 * 1024 ), - - (LPTHREAD_START_ROUTINE)func, // LPTHREAD_START_ROUTINE lpStartAddr, - (LPVOID)i, // LPVOID lpvThreadParm, - 0, // DWORD fdwCreate, - &threadid[i] ); - } - - for ( i = 0 ; i < numthreads ; i++ ) - WaitForSingleObject( threadhandle[i], INFINITE ); - } - DeleteCriticalSection( &crit ); - - threaded = qfalse; - end = I_FloatTime(); - if ( pacifier ) { - Sys_Printf( " (%i)\n", end - start ); - } -} - - -#endif - -/* - =================================================================== - - OSF1 - - =================================================================== - */ - -#ifdef __osf__ -#define USED - -int numthreads = 4; - -void ThreadSetDefault( void ){ - if ( numthreads == -1 ) { // not set manually - numthreads = 4; - } -} - - -#include - -pthread_mutex_t *my_mutex; - -void ThreadLock( void ){ - if ( my_mutex ) { - pthread_mutex_lock( my_mutex ); - } -} - -void ThreadUnlock( void ){ - if ( my_mutex ) { - pthread_mutex_unlock( my_mutex ); - } -} - - -/* - ============= - RunThreadsOn - ============= - */ -void RunThreadsOn( int workcnt, qboolean showpacifier, void ( *func )( int ) ){ - int i; - pthread_t work_threads[MAX_THREADS]; - pthread_addr_t status; - pthread_attr_t attrib; - pthread_mutexattr_t mattrib; - int start, end; - - start = I_FloatTime(); - dispatch = 0; - workcount = workcnt; - oldf = -1; - pacifier = showpacifier; - threaded = qtrue; - - if ( pacifier ) { - setbuf( stdout, NULL ); - } - - if ( !my_mutex ) { - my_mutex = safe_malloc( sizeof( *my_mutex ) ); - if ( pthread_mutexattr_create( &mattrib ) == -1 ) { - Error( "pthread_mutex_attr_create failed" ); - } - if ( pthread_mutexattr_setkind_np( &mattrib, MUTEX_FAST_NP ) == -1 ) { - Error( "pthread_mutexattr_setkind_np failed" ); - } - if ( pthread_mutex_init( my_mutex, mattrib ) == -1 ) { - Error( "pthread_mutex_init failed" ); - } - } - - if ( pthread_attr_create( &attrib ) == -1 ) { - Error( "pthread_attr_create failed" ); - } - if ( pthread_attr_setstacksize( &attrib, 0x100000 ) == -1 ) { - Error( "pthread_attr_setstacksize failed" ); - } - - for ( i = 0 ; i < numthreads ; i++ ) - { - if ( pthread_create( &work_threads[i], attrib - , (pthread_startroutine_t)func, (pthread_addr_t)i ) == -1 ) { - Error( "pthread_create failed" ); - } - } - - for ( i = 0 ; i < numthreads ; i++ ) - { - if ( pthread_join( work_threads[i], &status ) == -1 ) { - Error( "pthread_join failed" ); - } - } - - threaded = qfalse; - - end = I_FloatTime(); - if ( pacifier ) { - Sys_Printf( " (%i)\n", end - start ); - } -} - - -#endif - -/* - =================================================================== - - IRIX - - =================================================================== - */ - -#ifdef _MIPS_ISA -#define USED - -#include -#include -#include -#include - - -int numthreads = -1; -abilock_t lck; - -void ThreadSetDefault( void ){ - if ( numthreads == -1 ) { - numthreads = prctl( PR_MAXPPROCS ); - } - Sys_Printf( "%i threads\n", numthreads ); - usconfig( CONF_INITUSERS, numthreads ); -} - - -void ThreadLock( void ){ - spin_lock( &lck ); -} - -void ThreadUnlock( void ){ - release_lock( &lck ); -} - - -/* - ============= - RunThreadsOn - ============= - */ -void RunThreadsOn( int workcnt, qboolean showpacifier, void ( *func )( int ) ){ - int i; - int pid[MAX_THREADS]; - int start, end; - - start = I_FloatTime(); - dispatch = 0; - workcount = workcnt; - oldf = -1; - pacifier = showpacifier; - threaded = qtrue; - - if ( pacifier ) { - setbuf( stdout, NULL ); - } - - init_lock( &lck ); - - for ( i = 0 ; i < numthreads - 1 ; i++ ) - { - pid[i] = sprocsp( ( void ( * )( void *, size_t ) )func, PR_SALL, (void *)i - , NULL, 0x200000 ); // 2 meg stacks - if ( pid[i] == -1 ) { - perror( "sproc" ); - Error( "sproc failed" ); - } - } - - func( i ); - - for ( i = 0 ; i < numthreads - 1 ; i++ ) - wait( NULL ); - - threaded = qfalse; - - end = I_FloatTime(); - if ( pacifier ) { - Sys_Printf( " (%i)\n", end - start ); - } -} - - -#endif - - -/* - ======================================================================= - - Linux pthreads - - ======================================================================= - */ - -#ifdef __linux__ -#define USED - -int numthreads = 4; - -void ThreadSetDefault( void ){ - if ( numthreads == -1 ) { // not set manually - /* default to one thread, only multi-thread when specifically told to */ - numthreads = 1; - } - if ( numthreads > 1 ) { - Sys_Printf( "threads: %d\n", numthreads ); - } -} - -#include - -typedef struct pt_mutex_s -{ - pthread_t *owner; - pthread_mutex_t a_mutex; - pthread_cond_t cond; - unsigned int lock; -} pt_mutex_t; - -pt_mutex_t global_lock; - -void ThreadLock( void ){ - pt_mutex_t *pt_mutex = &global_lock; - - if ( !threaded ) { - return; - } - - pthread_mutex_lock( &pt_mutex->a_mutex ); - if ( pthread_equal( pthread_self(), (pthread_t)&pt_mutex->owner ) ) { - pt_mutex->lock++; - } - else - { - if ( ( !pt_mutex->owner ) && ( pt_mutex->lock == 0 ) ) { - pt_mutex->owner = (pthread_t *)pthread_self(); - pt_mutex->lock = 1; - } - else - { - while ( 1 ) - { - pthread_cond_wait( &pt_mutex->cond, &pt_mutex->a_mutex ); - if ( ( !pt_mutex->owner ) && ( pt_mutex->lock == 0 ) ) { - pt_mutex->owner = (pthread_t *)pthread_self(); - pt_mutex->lock = 1; - break; - } - } - } - } - pthread_mutex_unlock( &pt_mutex->a_mutex ); -} - -void ThreadUnlock( void ){ - pt_mutex_t *pt_mutex = &global_lock; - - if ( !threaded ) { - return; - } - - pthread_mutex_lock( &pt_mutex->a_mutex ); - pt_mutex->lock--; - - if ( pt_mutex->lock == 0 ) { - pt_mutex->owner = NULL; - pthread_cond_signal( &pt_mutex->cond ); - } - - pthread_mutex_unlock( &pt_mutex->a_mutex ); -} - -void recursive_mutex_init( pthread_mutexattr_t attribs ){ - pt_mutex_t *pt_mutex = &global_lock; - - pt_mutex->owner = NULL; - if ( pthread_mutex_init( &pt_mutex->a_mutex, &attribs ) != 0 ) { - Error( "pthread_mutex_init failed\n" ); - } - if ( pthread_cond_init( &pt_mutex->cond, NULL ) != 0 ) { - Error( "pthread_cond_init failed\n" ); - } - - pt_mutex->lock = 0; -} - -/* - ============= - RunThreadsOn - ============= - */ -void RunThreadsOn( int workcnt, qboolean showpacifier, void ( *func )( int ) ){ - pthread_mutexattr_t mattrib; - pthread_t work_threads[MAX_THREADS]; - - int start, end; - int i = 0, status = 0; - - start = I_FloatTime(); - pacifier = showpacifier; - - dispatch = 0; - oldf = -1; - workcount = workcnt; - - if ( numthreads == 1 ) { - func( 0 ); - } - else - { - threaded = qtrue; - - if ( pacifier ) { - setbuf( stdout, NULL ); - } - - if ( pthread_mutexattr_init( &mattrib ) != 0 ) { - Error( "pthread_mutexattr_init failed" ); - } -#if __GLIBC_MINOR__ == 1 - if ( pthread_mutexattr_settype( &mattrib, PTHREAD_MUTEX_FAST_NP ) != 0 ) -#else - if ( pthread_mutexattr_settype( &mattrib, PTHREAD_MUTEX_ADAPTIVE_NP ) != 0 ) -#endif - { Error( "pthread_mutexattr_settype failed" ); } - recursive_mutex_init( mattrib ); - - for ( i = 0 ; i < numthreads ; i++ ) - { - /* Default pthread attributes: joinable & non-realtime scheduling */ - if ( pthread_create( &work_threads[i], NULL, (void*)func, (void*)i ) != 0 ) { - Error( "pthread_create failed" ); - } - } - for ( i = 0 ; i < numthreads ; i++ ) - { - if ( pthread_join( work_threads[i], (void **)&status ) != 0 ) { - Error( "pthread_join failed" ); - } - } - pthread_mutexattr_destroy( &mattrib ); - threaded = qfalse; - } - - end = I_FloatTime(); - if ( pacifier ) { - Sys_Printf( " (%i)\n", end - start ); - } -} -#endif // ifdef __linux__ - - -/* - ======================================================================= - - SINGLE THREAD - - ======================================================================= - */ - -#ifndef USED - -int numthreads = 1; - -void ThreadSetDefault( void ){ - numthreads = 1; -} - -void ThreadLock( void ){ -} - -void ThreadUnlock( void ){ -} - -/* - ============= - RunThreadsOn - ============= - */ -void RunThreadsOn( int workcnt, qboolean showpacifier, void ( *func )( int ) ){ - int i; - int start, end; - - dispatch = 0; - workcount = workcnt; - oldf = -1; - pacifier = showpacifier; - start = I_FloatTime(); - func( 0 ); - - end = I_FloatTime(); - if ( pacifier ) { - Sys_Printf( " (%i)\n", end - start ); - } -} - -#endif diff --git a/tools/urt/tools/quake3/common/trilib.c b/tools/urt/tools/quake3/common/trilib.c deleted file mode 100644 index 6771476..0000000 --- a/tools/urt/tools/quake3/common/trilib.c +++ /dev/null @@ -1,236 +0,0 @@ -/* - Copyright (C) 1999-2007 id Software, Inc. and contributors. - For a list of contributors, see the accompanying CONTRIBUTORS file. - - This file is part of GtkRadiant. - - GtkRadiant is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - GtkRadiant is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with GtkRadiant; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - */ - -// -// trilib.c: library for loading triangles from an Alias triangle file -// - -#include -#include "cmdlib.h" -#include "mathlib.h" -#include "polyset.h" -#include "trilib.h" - -// on disk representation of a face - - -#define FLOAT_START 99999.0 -#define FLOAT_END -FLOAT_START -#define MAGIC 123322 - -//#define NOISY 1 - -#if defined ( __linux__ ) || defined ( __APPLE__ ) -#define strlwr strlower -#endif - -typedef struct { - float v[3]; -} vector; - -typedef struct -{ - vector n; /* normal */ - vector p; /* point */ - vector c; /* color */ - float u; /* u */ - float v; /* v */ -} aliaspoint_t; - -typedef struct { - aliaspoint_t pt[3]; -} tf_triangle; - - -static void ByteSwapTri( tf_triangle *tri ){ - int i; - - for ( i = 0 ; i < sizeof( tf_triangle ) / 4 ; i++ ) - { - ( (int *)tri )[i] = BigLong( ( (int *)tri )[i] ); - } -} - -static void ReadPolysetGeometry( triangle_t *tripool, FILE *input, int count, triangle_t *ptri ){ - tf_triangle tri; - int i; - - for ( i = 0; i < count; ++i ) { - int j; - - fread( &tri, sizeof( tf_triangle ), 1, input ); - ByteSwapTri( &tri ); - for ( j = 0 ; j < 3 ; j++ ) - { - int k; - - for ( k = 0 ; k < 3 ; k++ ) - { - ptri->verts[j][k] = tri.pt[j].p.v[k]; - ptri->normals[j][k] = tri.pt[j].n.v[k]; -// ptri->colors[j][k] = tri.pt[j].c.v[k]; - } - - ptri->texcoords[j][0] = tri.pt[j].u; - ptri->texcoords[j][1] = tri.pt[j].v; - } - - ptri++; - if ( ( ptri - tripool ) >= POLYSET_MAXTRIANGLES ) { - Error( "Error: too many triangles; increase POLYSET_MAXTRIANGLES\n" ); - } - } -} - -void TRI_LoadPolysets( const char *filename, polyset_t **ppPSET, int *numpsets ){ - FILE *input; - float start; - char name[256], tex[256]; - int i, count, magic, pset = 0; - triangle_t *ptri; - polyset_t *pPSET; - int iLevel; - int exitpattern; - float t; - - t = -FLOAT_START; - *( (unsigned char *)&exitpattern + 0 ) = *( (unsigned char *)&t + 3 ); - *( (unsigned char *)&exitpattern + 1 ) = *( (unsigned char *)&t + 2 ); - *( (unsigned char *)&exitpattern + 2 ) = *( (unsigned char *)&t + 1 ); - *( (unsigned char *)&exitpattern + 3 ) = *( (unsigned char *)&t + 0 ); - - if ( ( input = fopen( filename, "rb" ) ) == 0 ) { - Error( "reader: could not open file '%s'", filename ); - } - - iLevel = 0; - - fread( &magic, sizeof( int ), 1, input ); - if ( BigLong( magic ) != MAGIC ) { - Error( "%s is not a Alias object separated triangle file, magic number is wrong.", filename ); - } - - pPSET = calloc( 1, POLYSET_MAXPOLYSETS * sizeof( polyset_t ) ); - ptri = calloc( 1, POLYSET_MAXTRIANGLES * sizeof( triangle_t ) ); - - *ppPSET = pPSET; - - while ( feof( input ) == 0 ) { - if ( fread( &start, sizeof( float ), 1, input ) < 1 ) { - break; - } - *(int *)&start = BigLong( *(int *)&start ); - if ( *(int *)&start != exitpattern ) { - if ( start == FLOAT_START ) { - /* Start of an object or group of objects. */ - i = -1; - do { - /* There are probably better ways to read a string from */ - /* a file, but this does allow you to do error checking */ - /* (which I'm not doing) on a per character basis. */ - ++i; - fread( &( name[i] ), sizeof( char ), 1, input ); - } while ( name[i] != '\0' ); - - if ( i != 0 ) { - strncpy( pPSET[pset].name, name, sizeof( pPSET[pset].name ) - 1 ); - } - else{ - strcpy( pPSET[pset].name, "(unnamed)" ); - } - strlwr( pPSET[pset].name ); - -// indent(); -// fprintf(stdout,"OBJECT START: %s\n",name); - fread( &count, sizeof( int ), 1, input ); - count = BigLong( count ); - ++iLevel; - if ( count != 0 ) { -// indent(); -// fprintf(stdout,"NUMBER OF TRIANGLES: %d\n",count); - - i = -1; - do { - ++i; - fread( &( tex[i] ), sizeof( char ), 1, input ); - } while ( tex[i] != '\0' ); - -/* - if ( i != 0 ) - strncpy( pPSET[pset].texname, tex, sizeof( pPSET[pset].texname ) - 1 ); - else - strcpy( pPSET[pset].texname, "(unnamed)" ); - strlwr( pPSET[pset].texname ); - */ - -// indent(); -// fprintf(stdout," Object texture name: '%s'\n",tex); - } - - /* Else (count == 0) this is the start of a group, and */ - /* no texture name is present. */ - } - else if ( start == FLOAT_END ) { - /* End of an object or group. Yes, the name should be */ - /* obvious from context, but it is in here just to be */ - /* safe and to provide a little extra information for */ - /* those who do not wish to write a recursive reader. */ - /* Mea culpa. */ - --iLevel; - i = -1; - do { - ++i; - fread( &( name[i] ), sizeof( char ), 1, input ); - } while ( name[i] != '\0' ); - - if ( i != 0 ) { - strncpy( pPSET[pset].name, name, sizeof( pPSET[pset].name ) - 1 ); - } - else{ - strcpy( pPSET[pset].name, "(unnamed)" ); - } - - strlwr( pPSET[pset].name ); - -// indent(); -// fprintf(stdout,"OBJECT END: %s\n",name); - continue; - } - } - -// -// read the triangles -// - if ( count > 0 ) { - pPSET[pset].triangles = ptri; - ReadPolysetGeometry( pPSET[0].triangles, input, count, ptri ); - ptri += count; - pPSET[pset].numtriangles = count; - if ( ++pset >= POLYSET_MAXPOLYSETS ) { - Error( "Error: too many polysets; increase POLYSET_MAXPOLYSETS\n" ); - } - } - } - - *numpsets = pset; - - fclose( input ); -} diff --git a/tools/urt/tools/quake3/common/trilib.h b/tools/urt/tools/quake3/common/trilib.h deleted file mode 100644 index 47dc14b..0000000 --- a/tools/urt/tools/quake3/common/trilib.h +++ /dev/null @@ -1,25 +0,0 @@ -/* - Copyright (C) 1999-2007 id Software, Inc. and contributors. - For a list of contributors, see the accompanying CONTRIBUTORS file. - - This file is part of GtkRadiant. - - GtkRadiant is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - GtkRadiant is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with GtkRadiant; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - */ - -// -// trilib.h: header file for loading triangles from an Alias triangle file -// -void TRI_LoadPolysets( const char *filename, polyset_t **ppPSET, int *numpsets ); diff --git a/tools/urt/tools/quake3/common/unzip.c b/tools/urt/tools/quake3/common/unzip.c deleted file mode 100644 index 4dc10dd..0000000 --- a/tools/urt/tools/quake3/common/unzip.c +++ /dev/null @@ -1,4602 +0,0 @@ -/* -WARNING: DO NOT UNCRUSTIFY -It will still compile after an uncrustify, but it will be *broken* -See https://github.com/TTimo/GtkRadiant/issues/33 -*/ - -/* -Copyright (C) 1999-2007 id Software, Inc. and contributors. -For a list of contributors, see the accompanying CONTRIBUTORS file. - -This file is part of GtkRadiant. - -GtkRadiant is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. - -GtkRadiant is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with GtkRadiant; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - -/***************************************************************************** - * name: unzip.c - * - * desc: IO on .zip files using portions of zlib - * - * - *****************************************************************************/ - -#include -#include -#include -#include "unzip.h" - -// TTimo added for safe_malloc wrapping -#include "cmdlib.h" - -/* unzip.h -- IO for uncompress .zip files using zlib - Version 0.15 beta, Mar 19th, 1998, - - Copyright (C) 1998 Gilles Vollant - - This unzip package allow extract file from .ZIP file, compatible with PKZip 2.04g - WinZip, InfoZip tools and compatible. - Encryption and multi volume ZipFile (span) are not supported. - Old compressions used by old PKZip 1.x are not supported - - THIS IS AN ALPHA VERSION. AT THIS STAGE OF DEVELOPPEMENT, SOMES API OR STRUCTURE - CAN CHANGE IN FUTURE VERSION !! - I WAIT FEEDBACK at mail info@winimage.com - Visit also http://www.winimage.com/zLibDll/unzip.htm for evolution - - Condition of use and distribution are the same than zlib : - - This software is provided 'as-is', without any express or implied - warranty. In no event will the authors be held liable for any damages - arising from the use of this software. - - Permission is granted to anyone to use this software for any purpose, - including commercial applications, and to alter it and redistribute it - freely, subject to the following restrictions: - - 1. The origin of this software must not be misrepresented; you must not - claim that you wrote the original software. If you use this software - in a product, an acknowledgment in the product documentation would be - appreciated but is not required. - 2. Altered source versions must be plainly marked as such, and must not be - misrepresented as being the original software. - 3. This notice may not be removed or altered from any source distribution. - - -*/ -/* for more info about .ZIP format, see - ftp://ftp.cdrom.com/pub/infozip/doc/appnote-970311-iz.zip - PkWare has also a specification at : - ftp://ftp.pkware.com/probdesc.zip */ - -/* zlib.h -- interface of the 'zlib' general purpose compression library - version 1.1.3, July 9th, 1998 - - Copyright (C) 1995-1998 Jean-loup Gailly and Mark Adler - - This software is provided 'as-is', without any express or implied - warranty. In no event will the authors be held liable for any damages - arising from the use of this software. - - Permission is granted to anyone to use this software for any purpose, - including commercial applications, and to alter it and redistribute it - freely, subject to the following restrictions: - - 1. The origin of this software must not be misrepresented; you must not - claim that you wrote the original software. If you use this software - in a product, an acknowledgment in the product documentation would be - appreciated but is not required. - 2. Altered source versions must be plainly marked as such, and must not be - misrepresented as being the original software. - 3. This notice may not be removed or altered from any source distribution. - - Jean-loup Gailly Mark Adler - jloup@gzip.org madler@alumni.caltech.edu - - - The data format used by the zlib library is described by RFCs (Request for - Comments) 1950 to 1952 in the files ftp://ds.internic.net/rfc/rfc1950.txt - (zlib format), rfc1951.txt (deflate format) and rfc1952.txt (gzip format). -*/ - -/* zconf.h -- configuration of the zlib compression library - * Copyright (C) 1995-1998 Jean-loup Gailly. - * For conditions of distribution and use, see copyright notice in zlib.h - */ - - -#ifndef _ZCONF_H -#define _ZCONF_H - -/* Maximum value for memLevel in deflateInit2 */ -#ifndef MAX_MEM_LEVEL -# ifdef MAXSEG_64K -# define MAX_MEM_LEVEL 8 -# else -# define MAX_MEM_LEVEL 9 -# endif -#endif - -/* Maximum value for windowBits in deflateInit2 and inflateInit2. - * WARNING: reducing MAX_WBITS makes minigzip unable to extract .gz files - * created by gzip. (Files created by minigzip can still be extracted by - * gzip.) - */ -#ifndef MAX_WBITS -# define MAX_WBITS 15 /* 32K LZ77 window */ -#endif - -/* The memory requirements for deflate are (in bytes): - (1 << (windowBits+2)) + (1 << (memLevel+9)) - that is: 128K for windowBits=15 + 128K for memLevel = 8 (default values) - plus a few kilobytes for small objects. For example, if you want to reduce - the default memory requirements from 256K to 128K, compile with - make CFLAGS="-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7" - Of course this will generally degrade compression (there's no free lunch). - - The memory requirements for inflate are (in bytes) 1 << windowBits - that is, 32K for windowBits=15 (default value) plus a few kilobytes - for small objects. -*/ - - /* Type declarations */ - -#ifndef OF /* function prototypes */ -#define OF(args) args -#endif - -typedef unsigned char Byte; /* 8 bits */ -typedef unsigned int uInt; /* 16 bits or more */ -typedef unsigned long uLong; /* 32 bits or more */ -typedef Byte *voidp; - -#ifndef SEEK_SET -# define SEEK_SET 0 /* Seek from beginning of file. */ -# define SEEK_CUR 1 /* Seek from current position. */ -# define SEEK_END 2 /* Set file pointer to EOF plus "offset" */ -#endif - -#endif /* _ZCONF_H */ - -#define ZLIB_VERSION "1.1.3" - -/* - The 'zlib' compression library provides in-memory compression and - decompression functions, including integrity checks of the uncompressed - data. This version of the library supports only one compression method - (deflation) but other algorithms will be added later and will have the same - stream interface. - - Compression can be done in a single step if the buffers are large - enough (for example if an input file is mmap'ed), or can be done by - repeated calls of the compression function. In the latter case, the - application must provide more input and/or consume the output - (providing more output space) before each call. - - The library also supports reading and writing files in gzip (.gz) format - with an interface similar to that of stdio. - - The library does not install any signal handler. The decoder checks - the consistency of the compressed data, so the library should never - crash even in case of corrupted input. -*/ - -/* - The application must update next_in and avail_in when avail_in has - dropped to zero. It must update next_out and avail_out when avail_out - has dropped to zero. The application must initialize zalloc, zfree and - opaque before calling the init function. All other fields are set by the - compression library and must not be updated by the application. - - The opaque value provided by the application will be passed as the first - parameter for calls of zalloc and zfree. This can be useful for custom - memory management. The compression library attaches no meaning to the - opaque value. - - zalloc must return Z_NULL if there is not enough memory for the object. - If zlib is used in a multi-threaded application, zalloc and zfree must be - thread safe. - - On 16-bit systems, the functions zalloc and zfree must be able to allocate - exactly 65536 bytes, but will not be required to allocate more than this - if the symbol MAXSEG_64K is defined (see zconf.h). WARNING: On MSDOS, - pointers returned by zalloc for objects of exactly 65536 bytes *must* - have their offset normalized to zero. The default allocation function - provided by this library ensures this (see zutil.c). To reduce memory - requirements and avoid any allocation of 64K objects, at the expense of - compression ratio, compile the library with -DMAX_WBITS=14 (see zconf.h). - - The fields total_in and total_out can be used for statistics or - progress reports. After compression, total_in holds the total size of - the uncompressed data and may be saved for use in the decompressor - (particularly if the decompressor wants to decompress everything in - a single step). -*/ - - /* constants */ - -#define Z_NO_FLUSH 0 -#define Z_PARTIAL_FLUSH 1 /* will be removed, use Z_SYNC_FLUSH instead */ -#define Z_SYNC_FLUSH 2 -#define Z_FULL_FLUSH 3 -#define Z_FINISH 4 -/* Allowed flush values; see deflate() below for details */ - -#define Z_OK 0 -#define Z_STREAM_END 1 -#define Z_NEED_DICT 2 -#define Z_ERRNO (-1) -#define Z_STREAM_ERROR (-2) -#define Z_DATA_ERROR (-3) -#define Z_MEM_ERROR (-4) -#define Z_BUF_ERROR (-5) -#define Z_VERSION_ERROR (-6) -/* Return codes for the compression/decompression functions. Negative - * values are errors, positive values are used for special but normal events. - */ - -#define Z_NO_COMPRESSION 0 -#define Z_BEST_SPEED 1 -#define Z_BEST_COMPRESSION 9 -#define Z_DEFAULT_COMPRESSION (-1) -/* compression levels */ - -#define Z_FILTERED 1 -#define Z_HUFFMAN_ONLY 2 -#define Z_DEFAULT_STRATEGY 0 -/* compression strategy; see deflateInit2() below for details */ - -#define Z_BINARY 0 -#define Z_ASCII 1 -#define Z_UNKNOWN 2 -/* Possible values of the data_type field */ - -#define Z_DEFLATED 8 -/* The deflate compression method (the only one supported in this version) */ - -#define Z_NULL 0 /* for initializing zalloc, zfree, opaque */ - -#define zlib_version zlibVersion() -/* for compatibility with versions < 1.0.2 */ - - /* basic functions */ - -const char * zlibVersion OF((void)); -/* The application can compare zlibVersion and ZLIB_VERSION for consistency. - If the first character differs, the library code actually used is - not compatible with the zlib.h header file used by the application. - This check is automatically made by deflateInit and inflateInit. - */ - -/* -int deflateInit OF((z_streamp strm, int level)); - - Initializes the internal stream state for compression. The fields - zalloc, zfree and opaque must be initialized before by the caller. - If zalloc and zfree are set to Z_NULL, deflateInit updates them to - use default allocation functions. - - The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9: - 1 gives best speed, 9 gives best compression, 0 gives no compression at - all (the input data is simply copied a block at a time). - Z_DEFAULT_COMPRESSION requests a default compromise between speed and - compression (currently equivalent to level 6). - - deflateInit returns Z_OK if success, Z_MEM_ERROR if there was not - enough memory, Z_STREAM_ERROR if level is not a valid compression level, - Z_VERSION_ERROR if the zlib library version (zlib_version) is incompatible - with the version assumed by the caller (ZLIB_VERSION). - msg is set to null if there is no error message. deflateInit does not - perform any compression: this will be done by deflate(). -*/ - - -int deflate OF((z_streamp strm, int flush)); -/* - deflate compresses as much data as possible, and stops when the input - buffer becomes empty or the output buffer becomes full. It may introduce some - output latency (reading input without producing any output) except when - forced to flush. - - The detailed semantics are as follows. deflate performs one or both of the - following actions: - - - Compress more input starting at next_in and update next_in and avail_in - accordingly. If not all input can be processed (because there is not - enough room in the output buffer), next_in and avail_in are updated and - processing will resume at this point for the next call of deflate(). - - - Provide more output starting at next_out and update next_out and avail_out - accordingly. This action is forced if the parameter flush is non zero. - Forcing flush frequently degrades the compression ratio, so this parameter - should be set only when necessary (in interactive applications). - Some output may be provided even if flush is not set. - - Before the call of deflate(), the application should ensure that at least - one of the actions is possible, by providing more input and/or consuming - more output, and updating avail_in or avail_out accordingly; avail_out - should never be zero before the call. The application can consume the - compressed output when it wants, for example when the output buffer is full - (avail_out == 0), or after each call of deflate(). If deflate returns Z_OK - and with zero avail_out, it must be called again after making room in the - output buffer because there might be more output pending. - - If the parameter flush is set to Z_SYNC_FLUSH, all pending output is - flushed to the output buffer and the output is aligned on a byte boundary, so - that the decompressor can get all input data available so far. (In particular - avail_in is zero after the call if enough output space has been provided - before the call.) Flushing may degrade compression for some compression - algorithms and so it should be used only when necessary. - - If flush is set to Z_FULL_FLUSH, all output is flushed as with - Z_SYNC_FLUSH, and the compression state is reset so that decompression can - restart from this point if previous compressed data has been damaged or if - random access is desired. Using Z_FULL_FLUSH too often can seriously degrade - the compression. - - If deflate returns with avail_out == 0, this function must be called again - with the same value of the flush parameter and more output space (updated - avail_out), until the flush is complete (deflate returns with non-zero - avail_out). - - If the parameter flush is set to Z_FINISH, pending input is processed, - pending output is flushed and deflate returns with Z_STREAM_END if there - was enough output space; if deflate returns with Z_OK, this function must be - called again with Z_FINISH and more output space (updated avail_out) but no - more input data, until it returns with Z_STREAM_END or an error. After - deflate has returned Z_STREAM_END, the only possible operations on the - stream are deflateReset or deflateEnd. - - Z_FINISH can be used immediately after deflateInit if all the compression - is to be done in a single step. In this case, avail_out must be at least - 0.1% larger than avail_in plus 12 bytes. If deflate does not return - Z_STREAM_END, then it must be called again as described above. - - deflate() sets strm->adler to the adler32 checksum of all input read - so (that is, total_in bytes). - - deflate() may update data_type if it can make a good guess about - the input data type (Z_ASCII or Z_BINARY). In doubt, the data is considered - binary. This field is only for information purposes and does not affect - the compression algorithm in any manner. - - deflate() returns Z_OK if some progress has been made (more input - processed or more output produced), Z_STREAM_END if all input has been - consumed and all output has been produced (only when flush is set to - Z_FINISH), Z_STREAM_ERROR if the stream state was inconsistent (for example - if next_in or next_out was NULL), Z_BUF_ERROR if no progress is possible - (for example avail_in or avail_out was zero). -*/ - - -int deflateEnd OF((z_streamp strm)); -/* - All dynamically allocated data structures for this stream are freed. - This function discards any unprocessed input and does not flush any - pending output. - - deflateEnd returns Z_OK if success, Z_STREAM_ERROR if the - stream state was inconsistent, Z_DATA_ERROR if the stream was freed - prematurely (some input or output was discarded). In the error case, - msg may be set but then points to a static string (which must not be - deallocated). -*/ - - -/* -int inflateInit OF((z_streamp strm)); - - Initializes the internal stream state for decompression. The fields - next_in, avail_in, zalloc, zfree and opaque must be initialized before by - the caller. If next_in is not Z_NULL and avail_in is large enough (the exact - value depends on the compression method), inflateInit determines the - compression method from the zlib header and allocates all data structures - accordingly; otherwise the allocation will be deferred to the first call of - inflate. If zalloc and zfree are set to Z_NULL, inflateInit updates them to - use default allocation functions. - - inflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough - memory, Z_VERSION_ERROR if the zlib library version is incompatible with the - version assumed by the caller. msg is set to null if there is no error - message. inflateInit does not perform any decompression apart from reading - the zlib header if present: this will be done by inflate(). (So next_in and - avail_in may be modified, but next_out and avail_out are unchanged.) -*/ - - -int inflate OF((z_streamp strm, int flush)); -/* - inflate decompresses as much data as possible, and stops when the input - buffer becomes empty or the output buffer becomes full. It may some - introduce some output latency (reading input without producing any output) - except when forced to flush. - - The detailed semantics are as follows. inflate performs one or both of the - following actions: - - - Decompress more input starting at next_in and update next_in and avail_in - accordingly. If not all input can be processed (because there is not - enough room in the output buffer), next_in is updated and processing - will resume at this point for the next call of inflate(). - - - Provide more output starting at next_out and update next_out and avail_out - accordingly. inflate() provides as much output as possible, until there - is no more input data or no more space in the output buffer (see below - about the flush parameter). - - Before the call of inflate(), the application should ensure that at least - one of the actions is possible, by providing more input and/or consuming - more output, and updating the next_* and avail_* values accordingly. - The application can consume the uncompressed output when it wants, for - example when the output buffer is full (avail_out == 0), or after each - call of inflate(). If inflate returns Z_OK and with zero avail_out, it - must be called again after making room in the output buffer because there - might be more output pending. - - If the parameter flush is set to Z_SYNC_FLUSH, inflate flushes as much - output as possible to the output buffer. The flushing behavior of inflate is - not specified for values of the flush parameter other than Z_SYNC_FLUSH - and Z_FINISH, but the current implementation actually flushes as much output - as possible anyway. - - inflate() should normally be called until it returns Z_STREAM_END or an - error. However if all decompression is to be performed in a single step - (a single call of inflate), the parameter flush should be set to - Z_FINISH. In this case all pending input is processed and all pending - output is flushed; avail_out must be large enough to hold all the - uncompressed data. (The size of the uncompressed data may have been saved - by the compressor for this purpose.) The next operation on this stream must - be inflateEnd to deallocate the decompression state. The use of Z_FINISH - is never required, but can be used to inform inflate that a faster routine - may be used for the single inflate() call. - - If a preset dictionary is needed at this point (see inflateSetDictionary - below), inflate sets strm-adler to the adler32 checksum of the - dictionary chosen by the compressor and returns Z_NEED_DICT; otherwise - it sets strm->adler to the adler32 checksum of all output produced - so (that is, total_out bytes) and returns Z_OK, Z_STREAM_END or - an error code as described below. At the end of the stream, inflate() - checks that its computed adler32 checksum is equal to that saved by the - compressor and returns Z_STREAM_END only if the checksum is correct. - - inflate() returns Z_OK if some progress has been made (more input processed - or more output produced), Z_STREAM_END if the end of the compressed data has - been reached and all uncompressed output has been produced, Z_NEED_DICT if a - preset dictionary is needed at this point, Z_DATA_ERROR if the input data was - corrupted (input stream not conforming to the zlib format or incorrect - adler32 checksum), Z_STREAM_ERROR if the stream structure was inconsistent - (for example if next_in or next_out was NULL), Z_MEM_ERROR if there was not - enough memory, Z_BUF_ERROR if no progress is possible or if there was not - enough room in the output buffer when Z_FINISH is used. In the Z_DATA_ERROR - case, the application may then call inflateSync to look for a good - compression block. -*/ - - -int inflateEnd OF((z_streamp strm)); -/* - All dynamically allocated data structures for this stream are freed. - This function discards any unprocessed input and does not flush any - pending output. - - inflateEnd returns Z_OK if success, Z_STREAM_ERROR if the stream state - was inconsistent. In the error case, msg may be set but then points to a - static string (which must not be deallocated). -*/ - - /* Advanced functions */ - -/* - The following functions are needed only in some special applications. -*/ - -/* -int deflateInit2 OF((z_streamp strm, - int level, - int method, - int windowBits, - int memLevel, - int strategy)); - - This is another version of deflateInit with more compression options. The - fields next_in, zalloc, zfree and opaque must be initialized before by - the caller. - - The method parameter is the compression method. It must be Z_DEFLATED in - this version of the library. - - The windowBits parameter is the base two logarithm of the window size - (the size of the history buffer). It should be in the range 8..15 for this - version of the library. Larger values of this parameter result in better - compression at the expense of memory usage. The default value is 15 if - deflateInit is used instead. - - The memLevel parameter specifies how much memory should be allocated - for the internal compression state. memLevel=1 uses minimum memory but - is slow and reduces compression ratio; memLevel=9 uses maximum memory - for optimal speed. The default value is 8. See zconf.h for total memory - usage as a function of windowBits and memLevel. - - The strategy parameter is used to tune the compression algorithm. Use the - value Z_DEFAULT_STRATEGY for normal data, Z_FILTERED for data produced by a - filter (or predictor), or Z_HUFFMAN_ONLY to force Huffman encoding only (no - string match). Filtered data consists mostly of small values with a - somewhat random distribution. In this case, the compression algorithm is - tuned to compress them better. The effect of Z_FILTERED is to force more - Huffman coding and less string matching; it is somewhat intermediate - between Z_DEFAULT and Z_HUFFMAN_ONLY. The strategy parameter only affects - the compression ratio but not the correctness of the compressed output even - if it is not set appropriately. - - deflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough - memory, Z_STREAM_ERROR if a parameter is invalid (such as an invalid - method). msg is set to null if there is no error message. deflateInit2 does - not perform any compression: this will be done by deflate(). -*/ - -int deflateSetDictionary OF((z_streamp strm, - const Byte *dictionary, - uInt dictLength)); -/* - Initializes the compression dictionary from the given byte sequence - without producing any compressed output. This function must be called - immediately after deflateInit, deflateInit2 or deflateReset, before any - call of deflate. The compressor and decompressor must use exactly the same - dictionary (see inflateSetDictionary). - - The dictionary should consist of strings (byte sequences) that are likely - to be encountered later in the data to be compressed, with the most commonly - used strings preferably put towards the end of the dictionary. Using a - dictionary is most useful when the data to be compressed is short and can be - predicted with good accuracy; the data can then be compressed better than - with the default empty dictionary. - - Depending on the size of the compression data structures selected by - deflateInit or deflateInit2, a part of the dictionary may in effect be - discarded, for example if the dictionary is larger than the window size in - deflate or deflate2. Thus the strings most likely to be useful should be - put at the end of the dictionary, not at the front. - - Upon return of this function, strm->adler is set to the Adler32 value - of the dictionary; the decompressor may later use this value to determine - which dictionary has been used by the compressor. (The Adler32 value - applies to the whole dictionary even if only a subset of the dictionary is - actually used by the compressor.) - - deflateSetDictionary returns Z_OK if success, or Z_STREAM_ERROR if a - parameter is invalid (such as NULL dictionary) or the stream state is - inconsistent (for example if deflate has already been called for this stream - or if the compression method is bsort). deflateSetDictionary does not - perform any compression: this will be done by deflate(). -*/ - -int deflateCopy OF((z_streamp dest, - z_streamp source)); -/* - Sets the destination stream as a complete copy of the source stream. - - This function can be useful when several compression strategies will be - tried, for example when there are several ways of pre-processing the input - data with a filter. The streams that will be discarded should then be freed - by calling deflateEnd. Note that deflateCopy duplicates the internal - compression state which can be quite large, so this strategy is slow and - can consume lots of memory. - - deflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not - enough memory, Z_STREAM_ERROR if the source stream state was inconsistent - (such as zalloc being NULL). msg is left unchanged in both source and - destination. -*/ - -int deflateReset OF((z_streamp strm)); -/* - This function is equivalent to deflateEnd followed by deflateInit, - but does not free and reallocate all the internal compression state. - The stream will keep the same compression level and any other attributes - that may have been set by deflateInit2. - - deflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source - stream state was inconsistent (such as zalloc or state being NULL). -*/ - -int deflateParams OF((z_streamp strm, - int level, - int strategy)); -/* - Dynamically update the compression level and compression strategy. The - interpretation of level and strategy is as in deflateInit2. This can be - used to switch between compression and straight copy of the input data, or - to switch to a different kind of input data requiring a different - strategy. If the compression level is changed, the input available so far - is compressed with the old level (and may be flushed); the new level will - take effect only at the next call of deflate(). - - Before the call of deflateParams, the stream state must be set as for - a call of deflate(), since the currently available input may have to - be compressed and flushed. In particular, strm->avail_out must be non-zero. - - deflateParams returns Z_OK if success, Z_STREAM_ERROR if the source - stream state was inconsistent or if a parameter was invalid, Z_BUF_ERROR - if strm->avail_out was zero. -*/ - -/* -int inflateInit2 OF((z_streamp strm, - int windowBits)); - - This is another version of inflateInit with an extra parameter. The - fields next_in, avail_in, zalloc, zfree and opaque must be initialized - before by the caller. - - The windowBits parameter is the base two logarithm of the maximum window - size (the size of the history buffer). It should be in the range 8..15 for - this version of the library. The default value is 15 if inflateInit is used - instead. If a compressed stream with a larger window size is given as - input, inflate() will return with the error code Z_DATA_ERROR instead of - trying to allocate a larger window. - - inflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough - memory, Z_STREAM_ERROR if a parameter is invalid (such as a negative - memLevel). msg is set to null if there is no error message. inflateInit2 - does not perform any decompression apart from reading the zlib header if - present: this will be done by inflate(). (So next_in and avail_in may be - modified, but next_out and avail_out are unchanged.) -*/ - -int inflateSetDictionary OF((z_streamp strm, - const Byte *dictionary, - uInt dictLength)); -/* - Initializes the decompression dictionary from the given uncompressed byte - sequence. This function must be called immediately after a call of inflate - if this call returned Z_NEED_DICT. The dictionary chosen by the compressor - can be determined from the Adler32 value returned by this call of - inflate. The compressor and decompressor must use exactly the same - dictionary (see deflateSetDictionary). - - inflateSetDictionary returns Z_OK if success, Z_STREAM_ERROR if a - parameter is invalid (such as NULL dictionary) or the stream state is - inconsistent, Z_DATA_ERROR if the given dictionary doesn't match the - expected one (incorrect Adler32 value). inflateSetDictionary does not - perform any decompression: this will be done by subsequent calls of - inflate(). -*/ - -int inflateSync OF((z_streamp strm)); -/* - Skips invalid compressed data until a full flush point (see above the - description of deflate with Z_FULL_FLUSH) can be found, or until all - available input is skipped. No output is provided. - - inflateSync returns Z_OK if a full flush point has been found, Z_BUF_ERROR - if no more input was provided, Z_DATA_ERROR if no flush point has been found, - or Z_STREAM_ERROR if the stream structure was inconsistent. In the success - case, the application may save the current current value of total_in which - indicates where valid compressed data was found. In the error case, the - application may repeatedly call inflateSync, providing more input each time, - until success or end of the input data. -*/ - -int inflateReset OF((z_streamp strm)); -/* - This function is equivalent to inflateEnd followed by inflateInit, - but does not free and reallocate all the internal decompression state. - The stream will keep attributes that may have been set by inflateInit2. - - inflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source - stream state was inconsistent (such as zalloc or state being NULL). -*/ - - - /* utility functions */ - -/* - The following utility functions are implemented on top of the - basic stream-oriented functions. To simplify the interface, some - default options are assumed (compression level and memory usage, - standard memory allocation functions). The source code of these - utility functions can easily be modified if you need special options. -*/ - -int compress OF((Byte *dest, uLong *destLen, - const Byte *source, uLong sourceLen)); -/* - Compresses the source buffer into the destination buffer. sourceLen is - the byte length of the source buffer. Upon entry, destLen is the total - size of the destination buffer, which must be at least 0.1% larger than - sourceLen plus 12 bytes. Upon exit, destLen is the actual size of the - compressed buffer. - This function can be used to compress a whole file at once if the - input file is mmap'ed. - compress returns Z_OK if success, Z_MEM_ERROR if there was not - enough memory, Z_BUF_ERROR if there was not enough room in the output - buffer. -*/ - -int compress2 OF((Byte *dest, uLong *destLen, - const Byte *source, uLong sourceLen, - int level)); -/* - Compresses the source buffer into the destination buffer. The level - parameter has the same meaning as in deflateInit. sourceLen is the byte - length of the source buffer. Upon entry, destLen is the total size of the - destination buffer, which must be at least 0.1% larger than sourceLen plus - 12 bytes. Upon exit, destLen is the actual size of the compressed buffer. - - compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough - memory, Z_BUF_ERROR if there was not enough room in the output buffer, - Z_STREAM_ERROR if the level parameter is invalid. -*/ - -int uncompress OF((Byte *dest, uLong *destLen, - const Byte *source, uLong sourceLen)); -/* - Decompresses the source buffer into the destination buffer. sourceLen is - the byte length of the source buffer. Upon entry, destLen is the total - size of the destination buffer, which must be large enough to hold the - entire uncompressed data. (The size of the uncompressed data must have - been saved previously by the compressor and transmitted to the decompressor - by some mechanism outside the scope of this compression library.) - Upon exit, destLen is the actual size of the compressed buffer. - This function can be used to decompress a whole file at once if the - input file is mmap'ed. - - uncompress returns Z_OK if success, Z_MEM_ERROR if there was not - enough memory, Z_BUF_ERROR if there was not enough room in the output - buffer, or Z_DATA_ERROR if the input data was corrupted. -*/ - - -typedef voidp gzFile; - -gzFile gzopen OF((const char *path, const char *mode)); -/* - Opens a gzip (.gz) file for reading or writing. The mode parameter - is as in fopen ("rb" or "wb") but can also include a compression level - ("wb9") or a strategy: 'f' for filtered data as in "wb6f", 'h' for - Huffman only compression as in "wb1h". (See the description - of deflateInit2 for more information about the strategy parameter.) - - gzopen can be used to read a file which is not in gzip format; in this - case gzread will directly read from the file without decompression. - - gzopen returns NULL if the file could not be opened or if there was - insufficient memory to allocate the (de)compression state; errno - can be checked to distinguish the two cases (if errno is zero, the - zlib error is Z_MEM_ERROR). */ - -gzFile gzdopen OF((int fd, const char *mode)); -/* - gzdopen() associates a gzFile with the file descriptor fd. File - descriptors are obtained from calls like open, dup, creat, pipe or - fileno (in the file has been previously opened with fopen). - The mode parameter is as in gzopen. - The next call of gzclose on the returned gzFile will also close the - file descriptor fd, just like fclose(fdopen(fd), mode) closes the file - descriptor fd. If you want to keep fd open, use gzdopen(dup(fd), mode). - gzdopen returns NULL if there was insufficient memory to allocate - the (de)compression state. -*/ - -int gzsetparams OF((gzFile file, int level, int strategy)); -/* - Dynamically update the compression level or strategy. See the description - of deflateInit2 for the meaning of these parameters. - gzsetparams returns Z_OK if success, or Z_STREAM_ERROR if the file was not - opened for writing. -*/ - -int gzread OF((gzFile file, voidp buf, unsigned len)); -/* - Reads the given number of uncompressed bytes from the compressed file. - If the input file was not in gzip format, gzread copies the given number - of bytes into the buffer. - gzread returns the number of uncompressed bytes actually read (0 for - end of file, -1 for error). */ - -int gzwrite OF((gzFile file, - const voidp buf, unsigned len)); -/* - Writes the given number of uncompressed bytes into the compressed file. - gzwrite returns the number of uncompressed bytes actually written - (0 in case of error). -*/ - -int gzprintf OF((gzFile file, const char *format, ...)); -/* - Converts, formats, and writes the args to the compressed file under - control of the format string, as in fprintf. gzprintf returns the number of - uncompressed bytes actually written (0 in case of error). -*/ - -int gzputs OF((gzFile file, const char *s)); -/* - Writes the given null-terminated string to the compressed file, excluding - the terminating null character. - gzputs returns the number of characters written, or -1 in case of error. -*/ - -char * gzgets OF((gzFile file, char *buf, int len)); -/* - Reads bytes from the compressed file until len-1 characters are read, or - a newline character is read and transferred to buf, or an end-of-file - condition is encountered. The string is then terminated with a null - character. - gzgets returns buf, or Z_NULL in case of error. -*/ - -int gzputc OF((gzFile file, int c)); -/* - Writes c, converted to an unsigned char, into the compressed file. - gzputc returns the value that was written, or -1 in case of error. -*/ - -int gzgetc OF((gzFile file)); -/* - Reads one byte from the compressed file. gzgetc returns this byte - or -1 in case of end of file or error. -*/ - -int gzflush OF((gzFile file, int flush)); -/* - Flushes all pending output into the compressed file. The parameter - flush is as in the deflate() function. The return value is the zlib - error number (see function gzerror below). gzflush returns Z_OK if - the flush parameter is Z_FINISH and all output could be flushed. - gzflush should be called only when strictly necessary because it can - degrade compression. -*/ - -long gzseek OF((gzFile file, - long offset, int whence)); -/* - Sets the starting position for the next gzread or gzwrite on the - given compressed file. The offset represents a number of bytes in the - uncompressed data stream. The whence parameter is defined as in lseek(2); - the value SEEK_END is not supported. - If the file is opened for reading, this function is emulated but can be - extremely slow. If the file is opened for writing, only forward seeks are - supported; gzseek then compresses a sequence of zeroes up to the new - starting position. - - gzseek returns the resulting offset location as measured in bytes from - the beginning of the uncompressed stream, or -1 in case of error, in - particular if the file is opened for writing and the new starting position - would be before the current position. -*/ - -int gzrewind OF((gzFile file)); -/* - Rewinds the given file. This function is supported only for reading. - - gzrewind(file) is equivalent to (int)gzseek(file, 0L, SEEK_SET) -*/ - -long gztell OF((gzFile file)); -/* - Returns the starting position for the next gzread or gzwrite on the - given compressed file. This position represents a number of bytes in the - uncompressed data stream. - - gztell(file) is equivalent to gzseek(file, 0L, SEEK_CUR) -*/ - -int gzeof OF((gzFile file)); -/* - Returns 1 when EOF has previously been detected reading the given - input stream, otherwise zero. -*/ - -int gzclose OF((gzFile file)); -/* - Flushes all pending output if necessary, closes the compressed file - and deallocates all the (de)compression state. The return value is the zlib - error number (see function gzerror below). -*/ - -const char * gzerror OF((gzFile file, int *errnum)); -/* - Returns the error message for the last error which occurred on the - given compressed file. errnum is set to zlib error number. If an - error occurred in the file system and not in the compression library, - errnum is set to Z_ERRNO and the application may consult errno - to get the exact error code. -*/ - - /* checksum functions */ - -/* - These functions are not related to compression but are exported - anyway because they might be useful in applications using the - compression library. -*/ - -uLong adler32 OF((uLong adler, const Byte *buf, uInt len)); - -/* - Update a running Adler-32 checksum with the bytes buf[0..len-1] and - return the updated checksum. If buf is NULL, this function returns - the required initial value for the checksum. - An Adler-32 checksum is almost as reliable as a CRC32 but can be computed - much faster. Usage example: - - uLong adler = adler32(0L, Z_NULL, 0); - - while (read_buffer(buffer, length) != EOF) { - adler = adler32(adler, buffer, length); - } - if (adler != original_adler) error(); -*/ - -uLong crc32 OF((uLong crc, const Byte *buf, uInt len)); -/* - Update a running crc with the bytes buf[0..len-1] and return the updated - crc. If buf is NULL, this function returns the required initial value - for the crc. Pre- and post-conditioning (one's complement) is performed - within this function so it shouldn't be done by the application. - Usage example: - - uLong crc = crc32(0L, Z_NULL, 0); - - while (read_buffer(buffer, length) != EOF) { - crc = crc32(crc, buffer, length); - } - if (crc != original_crc) error(); -*/ - -// private stuff to not include cmdlib.h -/* -============================================================================ - - BYTE ORDER FUNCTIONS - -============================================================================ -*/ - -#ifdef _SGI_SOURCE -#define __BIG_ENDIAN__ -#endif - -#ifdef __BIG_ENDIAN__ - -short __LittleShort (short l) -{ - byte b1,b2; - - b1 = l&255; - b2 = (l>>8)&255; - - return (b1<<8) + b2; -} - -short __BigShort (short l) -{ - return l; -} - - -int __LittleLong (int l) -{ - byte b1,b2,b3,b4; - - b1 = l&255; - b2 = (l>>8)&255; - b3 = (l>>16)&255; - b4 = (l>>24)&255; - - return ((int)b1<<24) + ((int)b2<<16) + ((int)b3<<8) + b4; -} - -int __BigLong (int l) -{ - return l; -} - - -float __LittleFloat (float l) -{ - union {byte b[4]; float f;} in, out; - - in.f = l; - out.b[0] = in.b[3]; - out.b[1] = in.b[2]; - out.b[2] = in.b[1]; - out.b[3] = in.b[0]; - - return out.f; -} - -float __BigFloat (float l) -{ - return l; -} - - -#else - - -short __BigShort (short l) -{ - byte b1,b2; - - b1 = l&255; - b2 = (l>>8)&255; - - return (b1<<8) + b2; -} - -short __LittleShort (short l) -{ - return l; -} - - -int __BigLong (int l) -{ - byte b1,b2,b3,b4; - - b1 = l&255; - b2 = (l>>8)&255; - b3 = (l>>16)&255; - b4 = (l>>24)&255; - - return ((int)b1<<24) + ((int)b2<<16) + ((int)b3<<8) + b4; -} - -int __LittleLong (int l) -{ - return l; -} - -float __BigFloat (float l) -{ - union {byte b[4]; float f;} in, out; - - in.f = l; - out.b[0] = in.b[3]; - out.b[1] = in.b[2]; - out.b[2] = in.b[1]; - out.b[3] = in.b[0]; - - return out.f; -} - -float __LittleFloat (float l) -{ - return l; -} - - - -#endif - - - - - /* various hacks, don't look :) */ - -/* deflateInit and inflateInit are macros to allow checking the zlib version - * and the compiler's view of z_stream: - */ -int deflateInit_ OF((z_streamp strm, int level, - const char *version, int stream_size)); -int inflateInit_ OF((z_streamp strm, - const char *version, int stream_size)); -int deflateInit2_ OF((z_streamp strm, int level, int method, - int windowBits, int memLevel, - int strategy, const char *version, - int stream_size)); -int inflateInit2_ OF((z_streamp strm, int windowBits, - const char *version, int stream_size)); -#define deflateInit(strm, level) \ - deflateInit_((strm), (level), ZLIB_VERSION, sizeof(z_stream)) -#define inflateInit(strm) \ - inflateInit_((strm), ZLIB_VERSION, sizeof(z_stream)) -#define deflateInit2(strm, level, method, windowBits, memLevel, strategy) \ - deflateInit2_((strm),(level),(method),(windowBits),(memLevel),\ - (strategy), ZLIB_VERSION, sizeof(z_stream)) -#define inflateInit2(strm, windowBits) \ - inflateInit2_((strm), (windowBits), ZLIB_VERSION, sizeof(z_stream)) - - -const char * zError OF((int err)); -int inflateSyncPoint OF((z_streamp z)); -const uLong * get_crc_table OF((void)); - -typedef unsigned char uch; -typedef unsigned short ush; -typedef unsigned long ulg; - -extern const char *z_errmsg[10]; /* indexed by 2-zlib_error */ -/* (size given to avoid silly warnings with Visual C++) */ - -#define ERR_MSG(err) z_errmsg[Z_NEED_DICT-(err)] - -#define ERR_RETURN(strm,err) \ - return (strm->msg = (char*)ERR_MSG(err), (err)) -/* To be used only when the state is known to be valid */ - - /* common constants */ - -#ifndef DEF_WBITS -# define DEF_WBITS MAX_WBITS -#endif -/* default windowBits for decompression. MAX_WBITS is for compression only */ - -#if MAX_MEM_LEVEL >= 8 -# define DEF_MEM_LEVEL 8 -#else -# define DEF_MEM_LEVEL MAX_MEM_LEVEL -#endif -/* default memLevel */ - -#define STORED_BLOCK 0 -#define STATIC_TREES 1 -#define DYN_TREES 2 -/* The three kinds of block type */ - -#define MIN_MATCH 3 -#define MAX_MATCH 258 -/* The minimum and maximum match lengths */ - -#define PRESET_DICT 0x20 /* preset dictionary flag in zlib header */ - - /* target dependencies */ - - /* Common defaults */ - -#ifndef OS_CODE -# define OS_CODE 0x03 /* assume Unix */ -#endif - -#ifndef F_OPEN -# define F_OPEN(name, mode) fopen((name), (mode)) -#endif - - /* functions */ - -#ifdef HAVE_STRERROR - extern char *strerror OF((int)); -# define zstrerror(errnum) strerror(errnum) -#else -# define zstrerror(errnum) "" -#endif - -#define zmemcpy memcpy -#define zmemcmp memcmp -#define zmemzero(dest, len) memset(dest, 0, len) - -/* Diagnostic functions */ -#ifdef _ZIP_DEBUG_ - int z_verbose = 0; -# define Assert(cond,msg) assert(cond); - //{if(!(cond)) Sys_Error(msg);} -# define Trace(x) {if (z_verbose>=0) Sys_Error x ;} -# define Tracev(x) {if (z_verbose>0) Sys_Error x ;} -# define Tracevv(x) {if (z_verbose>1) Sys_Error x ;} -# define Tracec(c,x) {if (z_verbose>0 && (c)) Sys_Error x ;} -# define Tracecv(c,x) {if (z_verbose>1 && (c)) Sys_Error x ;} -#else -# define Assert(cond,msg) -# define Trace(x) -# define Tracev(x) -# define Tracevv(x) -# define Tracec(c,x) -# define Tracecv(c,x) -#endif - - -typedef uLong (*check_func) OF((uLong check, const Byte *buf, uInt len)); -voidp zcalloc OF((voidp opaque, unsigned items, unsigned size)); -void zcfree OF((voidp opaque, voidp ptr)); - -#define ZALLOC(strm, items, size) \ - (*((strm)->zalloc))((strm)->opaque, (items), (size)) -#define ZFREE(strm, addr) (*((strm)->zfree))((strm)->opaque, (voidp)(addr)) -#define TRY_FREE(s, p) {if (p) ZFREE(s, p);} - - -#if !defined(unix) && !defined(CASESENSITIVITYDEFAULT_YES) && \ - !defined(CASESENSITIVITYDEFAULT_NO) -#define CASESENSITIVITYDEFAULT_NO -#endif - - -#ifndef UNZ_BUFSIZE -#define UNZ_BUFSIZE (65536) -#endif - -#ifndef UNZ_MAXFILENAMEINZIP -#define UNZ_MAXFILENAMEINZIP (256) -#endif - -#ifndef ALLOC -# define ALLOC(size) (safe_malloc(size)) -#endif -#ifndef TRYFREE -# define TRYFREE(p) {if (p) free(p);} -#endif - -#define SIZECENTRALDIRITEM (0x2e) -#define SIZEZIPLOCALHEADER (0x1e) - - - -/* =========================================================================== - Read a byte from a gz_stream; update next_in and avail_in. Return EOF - for end of file. - IN assertion: the stream s has been sucessfully opened for reading. -*/ - -/* -static int unzlocal_getByte(FILE *fin,int *pi) -{ - unsigned char c; - int err = fread(&c, 1, 1, fin); - if (err==1) - { - *pi = (int)c; - return UNZ_OK; - } - else - { - if (ferror(fin)) - return UNZ_ERRNO; - else - return UNZ_EOF; - } -} -*/ - -/* =========================================================================== - Reads a long in LSB order from the given gz_stream. Sets -*/ -static int unzlocal_getShort (FILE* fin, uLong *pX) -{ - short v; - - fread( &v, sizeof(v), 1, fin ); - - *pX = __LittleShort( v); - return UNZ_OK; - -/* - uLong x ; - int i; - int err; - - err = unzlocal_getByte(fin,&i); - x = (uLong)i; - - if (err==UNZ_OK) - err = unzlocal_getByte(fin,&i); - x += ((uLong)i)<<8; - - if (err==UNZ_OK) - *pX = x; - else - *pX = 0; - return err; -*/ -} - -static int unzlocal_getLong (FILE *fin, uLong *pX) -{ - int v; - - fread( &v, sizeof(v), 1, fin ); - - *pX = __LittleLong( v); - return UNZ_OK; - -/* - uLong x ; - int i; - int err; - - err = unzlocal_getByte(fin,&i); - x = (uLong)i; - - if (err==UNZ_OK) - err = unzlocal_getByte(fin,&i); - x += ((uLong)i)<<8; - - if (err==UNZ_OK) - err = unzlocal_getByte(fin,&i); - x += ((uLong)i)<<16; - - if (err==UNZ_OK) - err = unzlocal_getByte(fin,&i); - x += ((uLong)i)<<24; - - if (err==UNZ_OK) - *pX = x; - else - *pX = 0; - return err; -*/ -} - - -/* My own strcmpi / strcasecmp */ -static int strcmpcasenosensitive_internal (const char* fileName1,const char* fileName2) -{ - for (;;) - { - char c1=*(fileName1++); - char c2=*(fileName2++); - if ((c1>='a') && (c1<='z')) - c1 -= 0x20; - if ((c2>='a') && (c2<='z')) - c2 -= 0x20; - if (c1=='\0') - return ((c2=='\0') ? 0 : -1); - if (c2=='\0') - return 1; - if (c1c2) - return 1; - } -} - - -#ifdef CASESENSITIVITYDEFAULT_NO -#define CASESENSITIVITYDEFAULTVALUE 2 -#else -#define CASESENSITIVITYDEFAULTVALUE 1 -#endif - -#ifndef STRCMPCASENOSENTIVEFUNCTION -#define STRCMPCASENOSENTIVEFUNCTION strcmpcasenosensitive_internal -#endif - -/* - Compare two filename (fileName1,fileName2). - If iCaseSenisivity = 1, comparision is case sensitivity (like strcmp) - If iCaseSenisivity = 2, comparision is not case sensitivity (like strcmpi - or strcasecmp) - If iCaseSenisivity = 0, case sensitivity is defaut of your operating system - (like 1 on Unix, 2 on Windows) - -*/ -extern int unzStringFileNameCompare (const char* fileName1,const char* fileName2,int iCaseSensitivity) -{ - if (iCaseSensitivity==0) - iCaseSensitivity=CASESENSITIVITYDEFAULTVALUE; - - if (iCaseSensitivity==1) - return strcmp(fileName1,fileName2); - - return STRCMPCASENOSENTIVEFUNCTION(fileName1,fileName2); -} - -#define BUFREADCOMMENT (0x400) - -/* - Locate the Central directory of a zipfile (at the end, just before - the global comment) -*/ -static uLong unzlocal_SearchCentralDir(FILE *fin) -{ - unsigned char* buf; - uLong uSizeFile; - uLong uBackRead; - uLong uMaxBack=0xffff; /* maximum size of global comment */ - uLong uPosFound=0; - - if (fseek(fin,0,SEEK_END) != 0) - return 0; - - - uSizeFile = ftell( fin ); - - if (uMaxBack>uSizeFile) - uMaxBack = uSizeFile; - - buf = (unsigned char*)safe_malloc(BUFREADCOMMENT+4); - if (buf==NULL) - return 0; - - uBackRead = 4; - while (uBackReaduMaxBack) - uBackRead = uMaxBack; - else - uBackRead+=BUFREADCOMMENT; - uReadPos = uSizeFile-uBackRead ; - - uReadSize = ((BUFREADCOMMENT+4) < (uSizeFile-uReadPos)) ? - (BUFREADCOMMENT+4) : (uSizeFile-uReadPos); - if (fseek(fin,uReadPos,SEEK_SET)!=0) - break; - - if (fread(buf,(uInt)uReadSize,1,fin)!=1) - break; - - for (i=(int)uReadSize-3; (i--)>0;) - if (((*(buf+i))==0x50) && ((*(buf+i+1))==0x4b) && - ((*(buf+i+2))==0x05) && ((*(buf+i+3))==0x06)) - { - uPosFound = uReadPos+i; - break; - } - - if (uPosFound!=0) - break; - } - free(buf); - return uPosFound; -} - -extern unzFile unzReOpen (const char* path, unzFile file) -{ - unz_s *s; - FILE * fin; - - fin=fopen(path,"rb"); - if (fin==NULL) - return NULL; - - s=(unz_s*)safe_malloc(sizeof(unz_s)); - memcpy(s, (unz_s*)file, sizeof(unz_s)); - - s->file = fin; - return (unzFile)s; -} - -/* - Open a Zip file. path contain the full pathname (by example, - on a Windows NT computer "c:\\test\\zlib109.zip" or on an Unix computer - "zlib/zlib109.zip". - If the zipfile cannot be opened (file don't exist or in not valid), the - return value is NULL. - Else, the return value is a unzFile Handle, usable with other function - of this unzip package. -*/ -extern unzFile unzOpen (const char* path) -{ - unz_s us; - unz_s *s; - uLong central_pos,uL; - FILE * fin ; - - uLong number_disk; /* number of the current dist, used for - spaning ZIP, unsupported, always 0*/ - uLong number_disk_with_CD; /* number the the disk with central dir, used - for spaning ZIP, unsupported, always 0*/ - uLong number_entry_CD; /* total number of entries in - the central dir - (same than number_entry on nospan) */ - - int err=UNZ_OK; - - fin=fopen(path,"rb"); - if (fin==NULL) - return NULL; - - central_pos = unzlocal_SearchCentralDir(fin); - if (central_pos==0) - err=UNZ_ERRNO; - - if (fseek(fin,central_pos,SEEK_SET)!=0) - err=UNZ_ERRNO; - - /* the signature, already checked */ - if (unzlocal_getLong(fin,&uL)!=UNZ_OK) - err=UNZ_ERRNO; - - /* number of this disk */ - if (unzlocal_getShort(fin,&number_disk)!=UNZ_OK) - err=UNZ_ERRNO; - - /* number of the disk with the start of the central directory */ - if (unzlocal_getShort(fin,&number_disk_with_CD)!=UNZ_OK) - err=UNZ_ERRNO; - - /* total number of entries in the central dir on this disk */ - if (unzlocal_getShort(fin,&us.gi.number_entry)!=UNZ_OK) - err=UNZ_ERRNO; - - /* total number of entries in the central dir */ - if (unzlocal_getShort(fin,&number_entry_CD)!=UNZ_OK) - err=UNZ_ERRNO; - - if ((number_entry_CD!=us.gi.number_entry) || - (number_disk_with_CD!=0) || - (number_disk!=0)) - err=UNZ_BADZIPFILE; - - /* size of the central directory */ - if (unzlocal_getLong(fin,&us.size_central_dir)!=UNZ_OK) - err=UNZ_ERRNO; - - /* offset of start of central directory with respect to the - starting disk number */ - if (unzlocal_getLong(fin,&us.offset_central_dir)!=UNZ_OK) - err=UNZ_ERRNO; - - /* zipfile comment length */ - if (unzlocal_getShort(fin,&us.gi.size_comment)!=UNZ_OK) - err=UNZ_ERRNO; - - if ((central_pospfile_in_zip_read!=NULL) - unzCloseCurrentFile(file); - - fclose(s->file); - free(s); - return UNZ_OK; -} - - -/* - Write info about the ZipFile in the *pglobal_info structure. - No preparation of the structure is needed - return UNZ_OK if there is no problem. */ -extern int unzGetGlobalInfo (unzFile file,unz_global_info *pglobal_info) -{ - unz_s* s; - if (file==NULL) - return UNZ_PARAMERROR; - s=(unz_s*)file; - *pglobal_info=s->gi; - return UNZ_OK; -} - - -/* - Translate date/time from Dos format to tm_unz (readable more easilty) -*/ -static void unzlocal_DosDateToTmuDate (uLong ulDosDate, tm_unz* ptm) -{ - uLong uDate; - uDate = (uLong)(ulDosDate>>16); - ptm->tm_mday = (uInt)(uDate&0x1f) ; - ptm->tm_mon = (uInt)((((uDate)&0x1E0)/0x20)-1) ; - ptm->tm_year = (uInt)(((uDate&0x0FE00)/0x0200)+1980) ; - - ptm->tm_hour = (uInt) ((ulDosDate &0xF800)/0x800); - ptm->tm_min = (uInt) ((ulDosDate&0x7E0)/0x20) ; - ptm->tm_sec = (uInt) (2*(ulDosDate&0x1f)) ; -} - -/* - Get Info about the current file in the zipfile, with internal only info -*/ -static int unzlocal_GetCurrentFileInfoInternal (unzFile file, - unz_file_info *pfile_info, - unz_file_info_internal - *pfile_info_internal, - char *szFileName, - uLong fileNameBufferSize, - void *extraField, - uLong extraFieldBufferSize, - char *szComment, - uLong commentBufferSize) -{ - unz_s* s; - unz_file_info file_info; - unz_file_info_internal file_info_internal; - int err=UNZ_OK; - uLong uMagic; - long lSeek=0; - - if (file==NULL) - return UNZ_PARAMERROR; - s=(unz_s*)file; - if (fseek(s->file,s->pos_in_central_dir+s->byte_before_the_zipfile,SEEK_SET)!=0) - err=UNZ_ERRNO; - - - /* we check the magic */ - if (err==UNZ_OK) - if (unzlocal_getLong(s->file,&uMagic) != UNZ_OK) - err=UNZ_ERRNO; - else if (uMagic!=0x02014b50) - err=UNZ_BADZIPFILE; - - if (unzlocal_getShort(s->file,&file_info.version) != UNZ_OK) - err=UNZ_ERRNO; - - if (unzlocal_getShort(s->file,&file_info.version_needed) != UNZ_OK) - err=UNZ_ERRNO; - - if (unzlocal_getShort(s->file,&file_info.flag) != UNZ_OK) - err=UNZ_ERRNO; - - if (unzlocal_getShort(s->file,&file_info.compression_method) != UNZ_OK) - err=UNZ_ERRNO; - - if (unzlocal_getLong(s->file,&file_info.dosDate) != UNZ_OK) - err=UNZ_ERRNO; - - unzlocal_DosDateToTmuDate(file_info.dosDate,&file_info.tmu_date); - - if (unzlocal_getLong(s->file,&file_info.crc) != UNZ_OK) - err=UNZ_ERRNO; - - if (unzlocal_getLong(s->file,&file_info.compressed_size) != UNZ_OK) - err=UNZ_ERRNO; - - if (unzlocal_getLong(s->file,&file_info.uncompressed_size) != UNZ_OK) - err=UNZ_ERRNO; - - if (unzlocal_getShort(s->file,&file_info.size_filename) != UNZ_OK) - err=UNZ_ERRNO; - - if (unzlocal_getShort(s->file,&file_info.size_file_extra) != UNZ_OK) - err=UNZ_ERRNO; - - if (unzlocal_getShort(s->file,&file_info.size_file_comment) != UNZ_OK) - err=UNZ_ERRNO; - - if (unzlocal_getShort(s->file,&file_info.disk_num_start) != UNZ_OK) - err=UNZ_ERRNO; - - if (unzlocal_getShort(s->file,&file_info.internal_fa) != UNZ_OK) - err=UNZ_ERRNO; - - if (unzlocal_getLong(s->file,&file_info.external_fa) != UNZ_OK) - err=UNZ_ERRNO; - - if (unzlocal_getLong(s->file,&file_info_internal.offset_curfile) != UNZ_OK) - err=UNZ_ERRNO; - - lSeek+=file_info.size_filename; - if ((err==UNZ_OK) && (szFileName!=NULL)) - { - uLong uSizeRead ; - if (file_info.size_filename0) && (fileNameBufferSize>0)) - if (fread(szFileName,(uInt)uSizeRead,1,s->file)!=1) - err=UNZ_ERRNO; - lSeek -= uSizeRead; - } - - - if ((err==UNZ_OK) && (extraField!=NULL)) - { - uLong uSizeRead ; - if (file_info.size_file_extrafile,lSeek,SEEK_CUR)==0) - lSeek=0; - else - err=UNZ_ERRNO; - if ((file_info.size_file_extra>0) && (extraFieldBufferSize>0)) - if (fread(extraField,(uInt)uSizeRead,1,s->file)!=1) - err=UNZ_ERRNO; - lSeek += file_info.size_file_extra - uSizeRead; - } - else - lSeek+=file_info.size_file_extra; - - - if ((err==UNZ_OK) && (szComment!=NULL)) - { - uLong uSizeRead ; - if (file_info.size_file_commentfile,lSeek,SEEK_CUR)==0) - lSeek=0; - else - err=UNZ_ERRNO; - if ((file_info.size_file_comment>0) && (commentBufferSize>0)) - if (fread(szComment,(uInt)uSizeRead,1,s->file)!=1) - err=UNZ_ERRNO; - lSeek+=file_info.size_file_comment - uSizeRead; - } - else - lSeek+=file_info.size_file_comment; - - if ((err==UNZ_OK) && (pfile_info!=NULL)) - *pfile_info=file_info; - - if ((err==UNZ_OK) && (pfile_info_internal!=NULL)) - *pfile_info_internal=file_info_internal; - - return err; -} - - - -/* - Write info about the ZipFile in the *pglobal_info structure. - No preparation of the structure is needed - return UNZ_OK if there is no problem. -*/ -extern int unzGetCurrentFileInfo ( unzFile file, unz_file_info *pfile_info, - char *szFileName, uLong fileNameBufferSize, - void *extraField, uLong extraFieldBufferSize, - char *szComment, uLong commentBufferSize) -{ - return unzlocal_GetCurrentFileInfoInternal(file,pfile_info,NULL, - szFileName,fileNameBufferSize, - extraField,extraFieldBufferSize, - szComment,commentBufferSize); -} - -/* - Set the current file of the zipfile to the first file. - return UNZ_OK if there is no problem -*/ -extern int unzGoToFirstFile (unzFile file) -{ - int err=UNZ_OK; - unz_s* s; - if (file==NULL) - return UNZ_PARAMERROR; - s=(unz_s*)file; - s->pos_in_central_dir=s->offset_central_dir; - s->num_file=0; - err=unzlocal_GetCurrentFileInfoInternal(file,&s->cur_file_info, - &s->cur_file_info_internal, - NULL,0,NULL,0,NULL,0); - s->current_file_ok = (err == UNZ_OK); - return err; -} - - -/* - Set the current file of the zipfile to the next file. - return UNZ_OK if there is no problem - return UNZ_END_OF_LIST_OF_FILE if the actual file was the latest. -*/ -extern int unzGoToNextFile (unzFile file) -{ - unz_s* s; - int err; - - if (file==NULL) - return UNZ_PARAMERROR; - s=(unz_s*)file; - if (!s->current_file_ok) - return UNZ_END_OF_LIST_OF_FILE; - if (s->num_file+1==s->gi.number_entry) - return UNZ_END_OF_LIST_OF_FILE; - - s->pos_in_central_dir += SIZECENTRALDIRITEM + s->cur_file_info.size_filename + - s->cur_file_info.size_file_extra + s->cur_file_info.size_file_comment ; - s->num_file++; - err = unzlocal_GetCurrentFileInfoInternal(file,&s->cur_file_info, - &s->cur_file_info_internal, - NULL,0,NULL,0,NULL,0); - s->current_file_ok = (err == UNZ_OK); - return err; -} - - -/* - Try locate the file szFileName in the zipfile. - For the iCaseSensitivity signification, see unzipStringFileNameCompare - - return value : - UNZ_OK if the file is found. It becomes the current file. - UNZ_END_OF_LIST_OF_FILE if the file is not found -*/ -extern int unzLocateFile (unzFile file, const char *szFileName, int iCaseSensitivity) -{ - unz_s* s; - int err; - - - uLong num_fileSaved; - uLong pos_in_central_dirSaved; - - - if (file==NULL) - return UNZ_PARAMERROR; - - if (strlen(szFileName)>=UNZ_MAXFILENAMEINZIP) - return UNZ_PARAMERROR; - - s=(unz_s*)file; - if (!s->current_file_ok) - return UNZ_END_OF_LIST_OF_FILE; - - num_fileSaved = s->num_file; - pos_in_central_dirSaved = s->pos_in_central_dir; - - err = unzGoToFirstFile(file); - - while (err == UNZ_OK) - { - char szCurrentFileName[UNZ_MAXFILENAMEINZIP+1]; - unzGetCurrentFileInfo(file,NULL, - szCurrentFileName,sizeof(szCurrentFileName)-1, - NULL,0,NULL,0); - if (unzStringFileNameCompare(szCurrentFileName, - szFileName,iCaseSensitivity)==0) - return UNZ_OK; - err = unzGoToNextFile(file); - } - - s->num_file = num_fileSaved ; - s->pos_in_central_dir = pos_in_central_dirSaved ; - return err; -} - - -/* - Read the static header of the current zipfile - Check the coherency of the static header and info in the end of central - directory about this file - store in *piSizeVar the size of extra info in static header - (filename and size of extra field data) -*/ -static int unzlocal_CheckCurrentFileCoherencyHeader (unz_s* s, uInt* piSizeVar, - uLong *poffset_local_extrafield, - uInt *psize_local_extrafield) -{ - uLong uMagic,uData,uFlags; - uLong size_filename; - uLong size_extra_field; - int err=UNZ_OK; - - *piSizeVar = 0; - *poffset_local_extrafield = 0; - *psize_local_extrafield = 0; - - if (fseek(s->file,s->cur_file_info_internal.offset_curfile + - s->byte_before_the_zipfile,SEEK_SET)!=0) - return UNZ_ERRNO; - - - if (err==UNZ_OK) - if (unzlocal_getLong(s->file,&uMagic) != UNZ_OK) - err=UNZ_ERRNO; - else if (uMagic!=0x04034b50) - err=UNZ_BADZIPFILE; - - if (unzlocal_getShort(s->file,&uData) != UNZ_OK) - err=UNZ_ERRNO; -/* - else if ((err==UNZ_OK) && (uData!=s->cur_file_info.wVersion)) - err=UNZ_BADZIPFILE; -*/ - if (unzlocal_getShort(s->file,&uFlags) != UNZ_OK) - err=UNZ_ERRNO; - - if (unzlocal_getShort(s->file,&uData) != UNZ_OK) - err=UNZ_ERRNO; - else if ((err==UNZ_OK) && (uData!=s->cur_file_info.compression_method)) - err=UNZ_BADZIPFILE; - - if ((err==UNZ_OK) && (s->cur_file_info.compression_method!=0) && - (s->cur_file_info.compression_method!=Z_DEFLATED)) - err=UNZ_BADZIPFILE; - - if (unzlocal_getLong(s->file,&uData) != UNZ_OK) /* date/time */ - err=UNZ_ERRNO; - - if (unzlocal_getLong(s->file,&uData) != UNZ_OK) /* crc */ - err=UNZ_ERRNO; - else if ((err==UNZ_OK) && (uData!=s->cur_file_info.crc) && - ((uFlags & 8)==0)) - err=UNZ_BADZIPFILE; - - if (unzlocal_getLong(s->file,&uData) != UNZ_OK) /* size compr */ - err=UNZ_ERRNO; - else if ((err==UNZ_OK) && (uData!=s->cur_file_info.compressed_size) && - ((uFlags & 8)==0)) - err=UNZ_BADZIPFILE; - - if (unzlocal_getLong(s->file,&uData) != UNZ_OK) /* size uncompr */ - err=UNZ_ERRNO; - else if ((err==UNZ_OK) && (uData!=s->cur_file_info.uncompressed_size) && - ((uFlags & 8)==0)) - err=UNZ_BADZIPFILE; - - - if (unzlocal_getShort(s->file,&size_filename) != UNZ_OK) - err=UNZ_ERRNO; - else if ((err==UNZ_OK) && (size_filename!=s->cur_file_info.size_filename)) - err=UNZ_BADZIPFILE; - - *piSizeVar += (uInt)size_filename; - - if (unzlocal_getShort(s->file,&size_extra_field) != UNZ_OK) - err=UNZ_ERRNO; - *poffset_local_extrafield= s->cur_file_info_internal.offset_curfile + - SIZEZIPLOCALHEADER + size_filename; - *psize_local_extrafield = (uInt)size_extra_field; - - *piSizeVar += (uInt)size_extra_field; - - return err; -} - -/* - Open for reading data the current file in the zipfile. - If there is no error and the file is opened, the return value is UNZ_OK. -*/ -extern int unzOpenCurrentFile (unzFile file) -{ - int err=UNZ_OK; - int Store; - uInt iSizeVar; - unz_s* s; - file_in_zip_read_info_s* pfile_in_zip_read_info; - uLong offset_local_extrafield; /* offset of the static extra field */ - uInt size_local_extrafield; /* size of the static extra field */ - - if (file==NULL) - return UNZ_PARAMERROR; - s=(unz_s*)file; - if (!s->current_file_ok) - return UNZ_PARAMERROR; - - if (s->pfile_in_zip_read != NULL) - unzCloseCurrentFile(file); - - if (unzlocal_CheckCurrentFileCoherencyHeader(s,&iSizeVar, - &offset_local_extrafield,&size_local_extrafield)!=UNZ_OK) - return UNZ_BADZIPFILE; - - pfile_in_zip_read_info = (file_in_zip_read_info_s*) - safe_malloc(sizeof(file_in_zip_read_info_s)); - if (pfile_in_zip_read_info==NULL) - return UNZ_INTERNALERROR; - - pfile_in_zip_read_info->read_buffer=(char*)safe_malloc(UNZ_BUFSIZE); - pfile_in_zip_read_info->offset_local_extrafield = offset_local_extrafield; - pfile_in_zip_read_info->size_local_extrafield = size_local_extrafield; - pfile_in_zip_read_info->pos_local_extrafield=0; - - if (pfile_in_zip_read_info->read_buffer==NULL) - { - free(pfile_in_zip_read_info); - return UNZ_INTERNALERROR; - } - - pfile_in_zip_read_info->stream_initialised=0; - - if ((s->cur_file_info.compression_method!=0) && - (s->cur_file_info.compression_method!=Z_DEFLATED)) - err=UNZ_BADZIPFILE; - Store = s->cur_file_info.compression_method==0; - - pfile_in_zip_read_info->crc32_wait=s->cur_file_info.crc; - pfile_in_zip_read_info->crc32=0; - pfile_in_zip_read_info->compression_method = - s->cur_file_info.compression_method; - pfile_in_zip_read_info->file=s->file; - pfile_in_zip_read_info->byte_before_the_zipfile=s->byte_before_the_zipfile; - - pfile_in_zip_read_info->stream.total_out = 0; - - if (!Store) - { - pfile_in_zip_read_info->stream.zalloc = (alloc_func)0; - pfile_in_zip_read_info->stream.zfree = (free_func)0; - pfile_in_zip_read_info->stream.opaque = (voidp)0; - - err=inflateInit2(&pfile_in_zip_read_info->stream, -MAX_WBITS); - if (err == Z_OK) - pfile_in_zip_read_info->stream_initialised=1; - /* windowBits is passed < 0 to tell that there is no zlib header. - * Note that in this case inflate *requires* an extra "dummy" byte - * after the compressed stream in order to complete decompression and - * return Z_STREAM_END. - * In unzip, i don't wait absolutely Z_STREAM_END because I known the - * size of both compressed and uncompressed data - */ - } - pfile_in_zip_read_info->rest_read_compressed = - s->cur_file_info.compressed_size ; - pfile_in_zip_read_info->rest_read_uncompressed = - s->cur_file_info.uncompressed_size ; - - - pfile_in_zip_read_info->pos_in_zipfile = - s->cur_file_info_internal.offset_curfile + SIZEZIPLOCALHEADER + - iSizeVar; - - pfile_in_zip_read_info->stream.avail_in = (uInt)0; - - - s->pfile_in_zip_read = pfile_in_zip_read_info; - return UNZ_OK; -} - - -/* - Read bytes from the current file. - buf contain buffer where data must be copied - len the size of buf. - - return the number of byte copied if somes bytes are copied - return 0 if the end of file was reached - return <0 with error code if there is an error - (UNZ_ERRNO for IO error, or zLib error for uncompress error) -*/ -extern int unzReadCurrentFile (unzFile file, void *buf, unsigned len) -{ - int err=UNZ_OK; - uInt iRead = 0; - unz_s* s; - file_in_zip_read_info_s* pfile_in_zip_read_info; - if (file==NULL) - return UNZ_PARAMERROR; - s=(unz_s*)file; - pfile_in_zip_read_info=s->pfile_in_zip_read; - - if (pfile_in_zip_read_info==NULL) - return UNZ_PARAMERROR; - - - if ((pfile_in_zip_read_info->read_buffer == NULL)) - return UNZ_END_OF_LIST_OF_FILE; - if (len==0) - return 0; - - pfile_in_zip_read_info->stream.next_out = (Byte*)buf; - - pfile_in_zip_read_info->stream.avail_out = (uInt)len; - - if (len>pfile_in_zip_read_info->rest_read_uncompressed) - pfile_in_zip_read_info->stream.avail_out = - (uInt)pfile_in_zip_read_info->rest_read_uncompressed; - - while (pfile_in_zip_read_info->stream.avail_out>0) - { - if ((pfile_in_zip_read_info->stream.avail_in==0) && - (pfile_in_zip_read_info->rest_read_compressed>0)) - { - uInt uReadThis = UNZ_BUFSIZE; - if (pfile_in_zip_read_info->rest_read_compressedrest_read_compressed; - if (uReadThis == 0) - return UNZ_EOF; - if (s->cur_file_info.compressed_size == pfile_in_zip_read_info->rest_read_compressed) - if (fseek(pfile_in_zip_read_info->file, - pfile_in_zip_read_info->pos_in_zipfile + - pfile_in_zip_read_info->byte_before_the_zipfile,SEEK_SET)!=0) - return UNZ_ERRNO; - if (fread(pfile_in_zip_read_info->read_buffer,uReadThis,1, - pfile_in_zip_read_info->file)!=1) - return UNZ_ERRNO; - pfile_in_zip_read_info->pos_in_zipfile += uReadThis; - - pfile_in_zip_read_info->rest_read_compressed-=uReadThis; - - pfile_in_zip_read_info->stream.next_in = - (Byte*)pfile_in_zip_read_info->read_buffer; - pfile_in_zip_read_info->stream.avail_in = (uInt)uReadThis; - } - - if (pfile_in_zip_read_info->compression_method==0) - { - uInt uDoCopy,i ; - if (pfile_in_zip_read_info->stream.avail_out < - pfile_in_zip_read_info->stream.avail_in) - uDoCopy = pfile_in_zip_read_info->stream.avail_out ; - else - uDoCopy = pfile_in_zip_read_info->stream.avail_in ; - - for (i=0;istream.next_out+i) = - *(pfile_in_zip_read_info->stream.next_in+i); - - pfile_in_zip_read_info->crc32 = crc32(pfile_in_zip_read_info->crc32, - pfile_in_zip_read_info->stream.next_out, - uDoCopy); - pfile_in_zip_read_info->rest_read_uncompressed-=uDoCopy; - pfile_in_zip_read_info->stream.avail_in -= uDoCopy; - pfile_in_zip_read_info->stream.avail_out -= uDoCopy; - pfile_in_zip_read_info->stream.next_out += uDoCopy; - pfile_in_zip_read_info->stream.next_in += uDoCopy; - pfile_in_zip_read_info->stream.total_out += uDoCopy; - iRead += uDoCopy; - } - else - { - uLong uTotalOutBefore,uTotalOutAfter; - const Byte *bufBefore; - uLong uOutThis; - int flush=Z_SYNC_FLUSH; - - uTotalOutBefore = pfile_in_zip_read_info->stream.total_out; - bufBefore = pfile_in_zip_read_info->stream.next_out; - - /* - if ((pfile_in_zip_read_info->rest_read_uncompressed == - pfile_in_zip_read_info->stream.avail_out) && - (pfile_in_zip_read_info->rest_read_compressed == 0)) - flush = Z_FINISH; - */ - err=inflate(&pfile_in_zip_read_info->stream,flush); - - uTotalOutAfter = pfile_in_zip_read_info->stream.total_out; - uOutThis = uTotalOutAfter-uTotalOutBefore; - - pfile_in_zip_read_info->crc32 = - crc32(pfile_in_zip_read_info->crc32,bufBefore, - (uInt)(uOutThis)); - - pfile_in_zip_read_info->rest_read_uncompressed -= - uOutThis; - - iRead += (uInt)(uTotalOutAfter - uTotalOutBefore); - - if (err==Z_STREAM_END) - return (iRead==0) ? UNZ_EOF : iRead; - if (err!=Z_OK) - break; - } - } - - if (err==Z_OK) - return iRead; - return err; -} - - -/* - Give the current position in uncompressed data -*/ -extern long unztell (unzFile file) -{ - unz_s* s; - file_in_zip_read_info_s* pfile_in_zip_read_info; - if (file==NULL) - return UNZ_PARAMERROR; - s=(unz_s*)file; - pfile_in_zip_read_info=s->pfile_in_zip_read; - - if (pfile_in_zip_read_info==NULL) - return UNZ_PARAMERROR; - - return (long)pfile_in_zip_read_info->stream.total_out; -} - - -/* - return 1 if the end of file was reached, 0 elsewhere -*/ -extern int unzeof (unzFile file) -{ - unz_s* s; - file_in_zip_read_info_s* pfile_in_zip_read_info; - if (file==NULL) - return UNZ_PARAMERROR; - s=(unz_s*)file; - pfile_in_zip_read_info=s->pfile_in_zip_read; - - if (pfile_in_zip_read_info==NULL) - return UNZ_PARAMERROR; - - if (pfile_in_zip_read_info->rest_read_uncompressed == 0) - return 1; - else - return 0; -} - - - -/* - Read extra field from the current file (opened by unzOpenCurrentFile) - This is the static-header version of the extra field (sometimes, there is - more info in the static-header version than in the central-header) - - if buf==NULL, it return the size of the static extra field that can be read - - if buf!=NULL, len is the size of the buffer, the extra header is copied in - buf. - the return value is the number of bytes copied in buf, or (if <0) - the error code -*/ -extern int unzGetLocalExtrafield (unzFile file,void *buf,unsigned len) -{ - unz_s* s; - file_in_zip_read_info_s* pfile_in_zip_read_info; - uInt read_now; - uLong size_to_read; - - if (file==NULL) - return UNZ_PARAMERROR; - s=(unz_s*)file; - pfile_in_zip_read_info=s->pfile_in_zip_read; - - if (pfile_in_zip_read_info==NULL) - return UNZ_PARAMERROR; - - size_to_read = (pfile_in_zip_read_info->size_local_extrafield - - pfile_in_zip_read_info->pos_local_extrafield); - - if (buf==NULL) - return (int)size_to_read; - - if (len>size_to_read) - read_now = (uInt)size_to_read; - else - read_now = (uInt)len ; - - if (read_now==0) - return 0; - - if (fseek(pfile_in_zip_read_info->file, - pfile_in_zip_read_info->offset_local_extrafield + - pfile_in_zip_read_info->pos_local_extrafield,SEEK_SET)!=0) - return UNZ_ERRNO; - - if (fread(buf,(uInt)size_to_read,1,pfile_in_zip_read_info->file)!=1) - return UNZ_ERRNO; - - return (int)read_now; -} - -/* - Close the file in zip opened with unzipOpenCurrentFile - Return UNZ_CRCERROR if all the file was read but the CRC is not good -*/ -extern int unzCloseCurrentFile (unzFile file) -{ - int err=UNZ_OK; - - unz_s* s; - file_in_zip_read_info_s* pfile_in_zip_read_info; - if (file==NULL) - return UNZ_PARAMERROR; - s=(unz_s*)file; - pfile_in_zip_read_info=s->pfile_in_zip_read; - - if (pfile_in_zip_read_info==NULL) - return UNZ_PARAMERROR; - - - if (pfile_in_zip_read_info->rest_read_uncompressed == 0) - { - if (pfile_in_zip_read_info->crc32 != pfile_in_zip_read_info->crc32_wait) - err=UNZ_CRCERROR; - } - - - free(pfile_in_zip_read_info->read_buffer); - pfile_in_zip_read_info->read_buffer = NULL; - if (pfile_in_zip_read_info->stream_initialised) - inflateEnd(&pfile_in_zip_read_info->stream); - - pfile_in_zip_read_info->stream_initialised = 0; - free(pfile_in_zip_read_info); - - s->pfile_in_zip_read=NULL; - - return err; -} - - -/* - Get the global comment string of the ZipFile, in the szComment buffer. - uSizeBuf is the size of the szComment buffer. - return the number of byte copied or an error code <0 -*/ -extern int unzGetGlobalComment (unzFile file, char *szComment, uLong uSizeBuf) -{ - unz_s* s; - uLong uReadThis ; - if (file==NULL) - return UNZ_PARAMERROR; - s=(unz_s*)file; - - uReadThis = uSizeBuf; - if (uReadThis>s->gi.size_comment) - uReadThis = s->gi.size_comment; - - if (fseek(s->file,s->central_pos+22,SEEK_SET)!=0) - return UNZ_ERRNO; - - if (uReadThis>0) - { - *szComment='\0'; - if (fread(szComment,(uInt)uReadThis,1,s->file)!=1) - return UNZ_ERRNO; - } - - if ((szComment != NULL) && (uSizeBuf > s->gi.size_comment)) - *(szComment+s->gi.size_comment)='\0'; - return (int)uReadThis; -} - -/* crc32.c -- compute the CRC-32 of a data stream - * Copyright (C) 1995-1998 Mark Adler - * For conditions of distribution and use, see copyright notice in zlib.h - */ - - -#ifdef DYNAMIC_CRC_TABLE - -static int crc_table_empty = 1; -static uLong crc_table[256]; -static void make_crc_table OF((void)); - -/* - Generate a table for a byte-wise 32-bit CRC calculation on the polynomial: - x^32+x^26+x^23+x^22+x^16+x^12+x^11+x^10+x^8+x^7+x^5+x^4+x^2+x+1. - - Polynomials over GF(2) are represented in binary, one bit per coefficient, - with the lowest powers in the most significant bit. Then adding polynomials - is just exclusive-or, and multiplying a polynomial by x is a right shift by - one. If we call the above polynomial p, and represent a byte as the - polynomial q, also with the lowest power in the most significant bit (so the - byte 0xb1 is the polynomial x^7+x^3+x+1), then the CRC is (q*x^32) mod p, - where a mod b means the remainder after dividing a by b. - - This calculation is done using the shift-register method of multiplying and - taking the remainder. The register is initialized to zero, and for each - incoming bit, x^32 is added mod p to the register if the bit is a one (where - x^32 mod p is p+x^32 = x^26+...+1), and the register is multiplied mod p by - x (which is shifting right by one and adding x^32 mod p if the bit shifted - out is a one). We start with the highest power (least significant bit) of - q and repeat for all eight bits of q. - - The table is simply the CRC of all possible eight bit values. This is all - the information needed to generate CRC's on data a byte at a time for all - combinations of CRC register values and incoming bytes. -*/ -static void make_crc_table() -{ - uLong c; - int n, k; - uLong poly; /* polynomial exclusive-or pattern */ - /* terms of polynomial defining this crc (except x^32): */ - static const Byte p[] = {0,1,2,4,5,7,8,10,11,12,16,22,23,26}; - - /* make exclusive-or pattern from polynomial (0xedb88320L) */ - poly = 0L; - for (n = 0; n < sizeof(p)/sizeof(Byte); n++) - poly |= 1L << (31 - p[n]); - - for (n = 0; n < 256; n++) - { - c = (uLong)n; - for (k = 0; k < 8; k++) - c = c & 1 ? poly ^ (c >> 1) : c >> 1; - crc_table[n] = c; - } - crc_table_empty = 0; -} -#else -/* ======================================================================== - * Table of CRC-32's of all single-byte values (made by make_crc_table) - */ -static const uLong crc_table[256] = { - 0x00000000L, 0x77073096L, 0xee0e612cL, 0x990951baL, 0x076dc419L, - 0x706af48fL, 0xe963a535L, 0x9e6495a3L, 0x0edb8832L, 0x79dcb8a4L, - 0xe0d5e91eL, 0x97d2d988L, 0x09b64c2bL, 0x7eb17cbdL, 0xe7b82d07L, - 0x90bf1d91L, 0x1db71064L, 0x6ab020f2L, 0xf3b97148L, 0x84be41deL, - 0x1adad47dL, 0x6ddde4ebL, 0xf4d4b551L, 0x83d385c7L, 0x136c9856L, - 0x646ba8c0L, 0xfd62f97aL, 0x8a65c9ecL, 0x14015c4fL, 0x63066cd9L, - 0xfa0f3d63L, 0x8d080df5L, 0x3b6e20c8L, 0x4c69105eL, 0xd56041e4L, - 0xa2677172L, 0x3c03e4d1L, 0x4b04d447L, 0xd20d85fdL, 0xa50ab56bL, - 0x35b5a8faL, 0x42b2986cL, 0xdbbbc9d6L, 0xacbcf940L, 0x32d86ce3L, - 0x45df5c75L, 0xdcd60dcfL, 0xabd13d59L, 0x26d930acL, 0x51de003aL, - 0xc8d75180L, 0xbfd06116L, 0x21b4f4b5L, 0x56b3c423L, 0xcfba9599L, - 0xb8bda50fL, 0x2802b89eL, 0x5f058808L, 0xc60cd9b2L, 0xb10be924L, - 0x2f6f7c87L, 0x58684c11L, 0xc1611dabL, 0xb6662d3dL, 0x76dc4190L, - 0x01db7106L, 0x98d220bcL, 0xefd5102aL, 0x71b18589L, 0x06b6b51fL, - 0x9fbfe4a5L, 0xe8b8d433L, 0x7807c9a2L, 0x0f00f934L, 0x9609a88eL, - 0xe10e9818L, 0x7f6a0dbbL, 0x086d3d2dL, 0x91646c97L, 0xe6635c01L, - 0x6b6b51f4L, 0x1c6c6162L, 0x856530d8L, 0xf262004eL, 0x6c0695edL, - 0x1b01a57bL, 0x8208f4c1L, 0xf50fc457L, 0x65b0d9c6L, 0x12b7e950L, - 0x8bbeb8eaL, 0xfcb9887cL, 0x62dd1ddfL, 0x15da2d49L, 0x8cd37cf3L, - 0xfbd44c65L, 0x4db26158L, 0x3ab551ceL, 0xa3bc0074L, 0xd4bb30e2L, - 0x4adfa541L, 0x3dd895d7L, 0xa4d1c46dL, 0xd3d6f4fbL, 0x4369e96aL, - 0x346ed9fcL, 0xad678846L, 0xda60b8d0L, 0x44042d73L, 0x33031de5L, - 0xaa0a4c5fL, 0xdd0d7cc9L, 0x5005713cL, 0x270241aaL, 0xbe0b1010L, - 0xc90c2086L, 0x5768b525L, 0x206f85b3L, 0xb966d409L, 0xce61e49fL, - 0x5edef90eL, 0x29d9c998L, 0xb0d09822L, 0xc7d7a8b4L, 0x59b33d17L, - 0x2eb40d81L, 0xb7bd5c3bL, 0xc0ba6cadL, 0xedb88320L, 0x9abfb3b6L, - 0x03b6e20cL, 0x74b1d29aL, 0xead54739L, 0x9dd277afL, 0x04db2615L, - 0x73dc1683L, 0xe3630b12L, 0x94643b84L, 0x0d6d6a3eL, 0x7a6a5aa8L, - 0xe40ecf0bL, 0x9309ff9dL, 0x0a00ae27L, 0x7d079eb1L, 0xf00f9344L, - 0x8708a3d2L, 0x1e01f268L, 0x6906c2feL, 0xf762575dL, 0x806567cbL, - 0x196c3671L, 0x6e6b06e7L, 0xfed41b76L, 0x89d32be0L, 0x10da7a5aL, - 0x67dd4accL, 0xf9b9df6fL, 0x8ebeeff9L, 0x17b7be43L, 0x60b08ed5L, - 0xd6d6a3e8L, 0xa1d1937eL, 0x38d8c2c4L, 0x4fdff252L, 0xd1bb67f1L, - 0xa6bc5767L, 0x3fb506ddL, 0x48b2364bL, 0xd80d2bdaL, 0xaf0a1b4cL, - 0x36034af6L, 0x41047a60L, 0xdf60efc3L, 0xa867df55L, 0x316e8eefL, - 0x4669be79L, 0xcb61b38cL, 0xbc66831aL, 0x256fd2a0L, 0x5268e236L, - 0xcc0c7795L, 0xbb0b4703L, 0x220216b9L, 0x5505262fL, 0xc5ba3bbeL, - 0xb2bd0b28L, 0x2bb45a92L, 0x5cb36a04L, 0xc2d7ffa7L, 0xb5d0cf31L, - 0x2cd99e8bL, 0x5bdeae1dL, 0x9b64c2b0L, 0xec63f226L, 0x756aa39cL, - 0x026d930aL, 0x9c0906a9L, 0xeb0e363fL, 0x72076785L, 0x05005713L, - 0x95bf4a82L, 0xe2b87a14L, 0x7bb12baeL, 0x0cb61b38L, 0x92d28e9bL, - 0xe5d5be0dL, 0x7cdcefb7L, 0x0bdbdf21L, 0x86d3d2d4L, 0xf1d4e242L, - 0x68ddb3f8L, 0x1fda836eL, 0x81be16cdL, 0xf6b9265bL, 0x6fb077e1L, - 0x18b74777L, 0x88085ae6L, 0xff0f6a70L, 0x66063bcaL, 0x11010b5cL, - 0x8f659effL, 0xf862ae69L, 0x616bffd3L, 0x166ccf45L, 0xa00ae278L, - 0xd70dd2eeL, 0x4e048354L, 0x3903b3c2L, 0xa7672661L, 0xd06016f7L, - 0x4969474dL, 0x3e6e77dbL, 0xaed16a4aL, 0xd9d65adcL, 0x40df0b66L, - 0x37d83bf0L, 0xa9bcae53L, 0xdebb9ec5L, 0x47b2cf7fL, 0x30b5ffe9L, - 0xbdbdf21cL, 0xcabac28aL, 0x53b39330L, 0x24b4a3a6L, 0xbad03605L, - 0xcdd70693L, 0x54de5729L, 0x23d967bfL, 0xb3667a2eL, 0xc4614ab8L, - 0x5d681b02L, 0x2a6f2b94L, 0xb40bbe37L, 0xc30c8ea1L, 0x5a05df1bL, - 0x2d02ef8dL -}; -#endif - -/* ========================================================================= - * This function can be used by asm versions of crc32() - */ -#ifndef __APPLE__ -const uLong * get_crc_table() -{ -#ifdef DYNAMIC_CRC_TABLE - if (crc_table_empty) make_crc_table(); -#endif - return (const uLong *)crc_table; -} -#endif - -/* ========================================================================= */ -#define DO1(buf) crc = crc_table[((int)crc ^ (*buf++)) & 0xff] ^ (crc >> 8); -#define DO2(buf) DO1(buf); DO1(buf); -#define DO4(buf) DO2(buf); DO2(buf); -#define DO8(buf) DO4(buf); DO4(buf); - -/* ========================================================================= */ -#ifndef __APPLE__ -uLong crc32(uLong crc, const Byte *buf, uInt len) -{ - if (buf == Z_NULL) return 0L; -#ifdef DYNAMIC_CRC_TABLE - if (crc_table_empty) - make_crc_table(); -#endif - crc = crc ^ 0xffffffffL; - while (len >= 8) - { - DO8(buf); - len -= 8; - } - if (len) do { - DO1(buf); - } while (--len); - return crc ^ 0xffffffffL; -} -#endif - -/* infblock.h -- header to use infblock.c - * Copyright (C) 1995-1998 Mark Adler - * For conditions of distribution and use, see copyright notice in zlib.h - */ - -/* WARNING: this file should *not* be used by applications. It is - part of the implementation of the compression library and is - subject to change. Applications should only use zlib.h. - */ - -struct inflate_blocks_state; -typedef struct inflate_blocks_state inflate_blocks_statef; - -extern inflate_blocks_statef * inflate_blocks_new OF(( - z_streamp z, - check_func c, /* check function */ - uInt w)); /* window size */ - -extern int inflate_blocks OF(( - inflate_blocks_statef *, - z_streamp , - int)); /* initial return code */ - -extern void inflate_blocks_reset OF(( - inflate_blocks_statef *, - z_streamp , - uLong *)); /* check value on output */ - -extern int inflate_blocks_free OF(( - inflate_blocks_statef *, - z_streamp)); - -extern void inflate_set_dictionary OF(( - inflate_blocks_statef *s, - const Byte *d, /* dictionary */ - uInt n)); /* dictionary length */ - -extern int inflate_blocks_sync_point OF(( - inflate_blocks_statef *s)); - -/* simplify the use of the inflate_huft type with some defines */ -#define exop word.what.Exop -#define bits word.what.Bits - -/* Table for deflate from PKZIP's appnote.txt. */ -static const uInt border[] = { /* Order of the bit length code lengths */ - 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}; - -/* inftrees.h -- header to use inftrees.c - * Copyright (C) 1995-1998 Mark Adler - * For conditions of distribution and use, see copyright notice in zlib.h - */ - -/* WARNING: this file should *not* be used by applications. It is - part of the implementation of the compression library and is - subject to change. Applications should only use zlib.h. - */ - -/* Huffman code lookup table entry--this entry is four bytes for machines - that have 16-bit pointers (e.g. PC's in the small or medium model). */ - -typedef struct inflate_huft_s inflate_huft; - -struct inflate_huft_s { - union { - struct { - Byte Exop; /* number of extra bits or operation */ - Byte Bits; /* number of bits in this code or subcode */ - } what; - uInt pad; /* pad structure to a power of 2 (4 bytes for */ - } word; /* 16-bit, 8 bytes for 32-bit int's) */ - uInt base; /* literal, length base, distance base, - or table offset */ -}; - -/* Maximum size of dynamic tree. The maximum found in a long but non- - exhaustive search was 1004 huft structures (850 for length/literals - and 154 for distances, the latter actually the result of an - exhaustive search). The actual maximum is not known, but the - value below is more than safe. */ -#define MANY 1440 - -extern int inflate_trees_bits OF(( - uInt *, /* 19 code lengths */ - uInt *, /* bits tree desired/actual depth */ - inflate_huft * *, /* bits tree result */ - inflate_huft *, /* space for trees */ - z_streamp)); /* for messages */ - -extern int inflate_trees_dynamic OF(( - uInt, /* number of literal/length codes */ - uInt, /* number of distance codes */ - uInt *, /* that many (total) code lengths */ - uInt *, /* literal desired/actual bit depth */ - uInt *, /* distance desired/actual bit depth */ - inflate_huft * *, /* literal/length tree result */ - inflate_huft * *, /* distance tree result */ - inflate_huft *, /* space for trees */ - z_streamp)); /* for messages */ - -extern int inflate_trees_fixed OF(( - uInt *, /* literal desired/actual bit depth */ - uInt *, /* distance desired/actual bit depth */ - inflate_huft * *, /* literal/length tree result */ - inflate_huft * *, /* distance tree result */ - z_streamp)); /* for memory allocation */ - - -/* infcodes.h -- header to use infcodes.c - * Copyright (C) 1995-1998 Mark Adler - * For conditions of distribution and use, see copyright notice in zlib.h - */ - -/* WARNING: this file should *not* be used by applications. It is - part of the implementation of the compression library and is - subject to change. Applications should only use zlib.h. - */ - -struct inflate_codes_state; -typedef struct inflate_codes_state inflate_codes_statef; - -extern inflate_codes_statef *inflate_codes_new OF(( - uInt, uInt, - inflate_huft *, inflate_huft *, - z_streamp )); - -extern int inflate_codes OF(( - inflate_blocks_statef *, - z_streamp , - int)); - -extern void inflate_codes_free OF(( - inflate_codes_statef *, - z_streamp )); - -/* infutil.h -- types and macros common to blocks and codes - * Copyright (C) 1995-1998 Mark Adler - * For conditions of distribution and use, see copyright notice in zlib.h - */ - -/* WARNING: this file should *not* be used by applications. It is - part of the implementation of the compression library and is - subject to change. Applications should only use zlib.h. - */ - -#ifndef _INFUTIL_H -#define _INFUTIL_H - -typedef enum { - TYPE, /* get type bits (3, including end bit) */ - LENS, /* get lengths for stored */ - STORED, /* processing stored block */ - TABLE, /* get table lengths */ - BTREE, /* get bit lengths tree for a dynamic block */ - DTREE, /* get length, distance trees for a dynamic block */ - CODES, /* processing fixed or dynamic block */ - DRY, /* output remaining window bytes */ - DONE, /* finished last block, done */ - BAD} /* got a data error--stuck here */ -inflate_block_mode; - -/* inflate blocks semi-private state */ -struct inflate_blocks_state { - - /* mode */ - inflate_block_mode mode; /* current inflate_block mode */ - - /* mode dependent information */ - union { - uInt left; /* if STORED, bytes left to copy */ - struct { - uInt table; /* table lengths (14 bits) */ - uInt index; /* index into blens (or border) */ - uInt *blens; /* bit lengths of codes */ - uInt bb; /* bit length tree depth */ - inflate_huft *tb; /* bit length decoding tree */ - } trees; /* if DTREE, decoding info for trees */ - struct { - inflate_codes_statef - *codes; - } decode; /* if CODES, current state */ - } sub; /* submode */ - uInt last; /* true if this block is the last block */ - - /* mode independent information */ - uInt bitk; /* bits in bit buffer */ - uLong bitb; /* bit buffer */ - inflate_huft *hufts; /* single safe_malloc for tree space */ - Byte *window; /* sliding window */ - Byte *end; /* one byte after sliding window */ - Byte *read; /* window read pointer */ - Byte *write; /* window write pointer */ - check_func checkfn; /* check function */ - uLong check; /* check on output */ - -}; - - -/* defines for inflate input/output */ -/* update pointers and return */ -#define UPDBITS {s->bitb=b;s->bitk=k;} -#define UPDIN {z->avail_in=n;z->total_in+=p-z->next_in;z->next_in=p;} -#define UPDOUT {s->write=q;} -#define UPDATE {UPDBITS UPDIN UPDOUT} -#define LEAVE {UPDATE return inflate_flush(s,z,r);} -/* get bytes and bits */ -#define LOADIN {p=z->next_in;n=z->avail_in;b=s->bitb;k=s->bitk;} -#define NEEDBYTE {if(n)r=Z_OK;else LEAVE} -#define NEXTBYTE (n--,*p++) -#define NEEDBITS(j) {while(k<(j)){NEEDBYTE;b|=((uLong)NEXTBYTE)<>=(j);k-=(j);} -/* output bytes */ -#define WAVAIL (uInt)(qread?s->read-q-1:s->end-q) -#define LOADOUT {q=s->write;m=(uInt)WAVAIL;} -#define WRAP {if(q==s->end&&s->read!=s->window){q=s->window;m=(uInt)WAVAIL;}} -#define FLUSH {UPDOUT r=inflate_flush(s,z,r); LOADOUT} -#define NEEDOUT {if(m==0){WRAP if(m==0){FLUSH WRAP if(m==0) LEAVE}}r=Z_OK;} -#define OUTBYTE(a) {*q++=(Byte)(a);m--;} -/* load static pointers */ -#define LOAD {LOADIN LOADOUT} - -/* masks for lower bits (size given to avoid silly warnings with Visual C++) */ -extern uInt inflate_mask[17]; - -/* copy as much as possible from the sliding window to the output area */ -extern int inflate_flush OF(( - inflate_blocks_statef *, - z_streamp , - int)); - -#endif - - -/* - Notes beyond the 1.93a appnote.txt: - - 1. Distance pointers never point before the beginning of the output - stream. - 2. Distance pointers can point back across blocks, up to 32k away. - 3. There is an implied maximum of 7 bits for the bit length table and - 15 bits for the actual data. - 4. If only one code exists, then it is encoded using one bit. (Zero - would be more efficient, but perhaps a little confusing.) If two - codes exist, they are coded using one bit each (0 and 1). - 5. There is no way of sending zero distance codes--a dummy must be - sent if there are none. (History: a pre 2.0 version of PKZIP would - store blocks with no distance codes, but this was discovered to be - too harsh a criterion.) Valid only for 1.93a. 2.04c does allow - zero distance codes, which is sent as one code of zero bits in - length. - 6. There are up to 286 literal/length codes. Code 256 represents the - end-of-block. Note however that the static length tree defines - 288 codes just to fill out the Huffman codes. Codes 286 and 287 - cannot be used though, since there is no length base or extra bits - defined for them. Similarily, there are up to 30 distance codes. - However, static trees define 32 codes (all 5 bits) to fill out the - Huffman codes, but the last two had better not show up in the data. - 7. Unzip can check dynamic Huffman blocks for complete code sets. - The exception is that a single code would not be complete (see #4). - 8. The five bits following the block type is really the number of - literal codes sent minus 257. - 9. Length codes 8,16,16 are interpreted as 13 length codes of 8 bits - (1+6+6). Therefore, to output three times the length, you output - three codes (1+1+1), whereas to output four times the same length, - you only need two codes (1+3). Hmm. - 10. In the tree reconstruction algorithm, Code = Code + Increment - only if BitLength(i) is not zero. (Pretty obvious.) - 11. Correction: 4 Bits: # of Bit Length codes - 4 (4 - 19) - 12. Note: length code 284 can represent 227-258, but length code 285 - really is 258. The last length deserves its own, short code - since it gets used a lot in very redundant files. The length - 258 is special since 258 - 3 (the min match length) is 255. - 13. The literal/length and distance code bit lengths are read as a - single stream of lengths. It is possible (and advantageous) for - a repeat code (16, 17, or 18) to go across the boundary between - the two sets of lengths. - */ - - -#ifndef __APPLE__ -void inflate_blocks_reset(inflate_blocks_statef *s, z_streamp z, uLong *c) -{ - if (c != Z_NULL) - *c = s->check; - if (s->mode == BTREE || s->mode == DTREE) - ZFREE(z, s->sub.trees.blens); - if (s->mode == CODES) - inflate_codes_free(s->sub.decode.codes, z); - s->mode = TYPE; - s->bitk = 0; - s->bitb = 0; - s->read = s->write = s->window; - if (s->checkfn != Z_NULL) - z->adler = s->check = (*s->checkfn)(0L, (const Byte *)Z_NULL, 0); - Tracev(("inflate: blocks reset\n")); -} -#endif - -#ifndef __APPLE__ -inflate_blocks_statef *inflate_blocks_new(z_streamp z, check_func c, uInt w) -{ - inflate_blocks_statef *s; - - if ((s = (inflate_blocks_statef *)ZALLOC - (z,1,sizeof(struct inflate_blocks_state))) == Z_NULL) - return s; - if ((s->hufts = - (inflate_huft *)ZALLOC(z, sizeof(inflate_huft), MANY)) == Z_NULL) - { - ZFREE(z, s); - return Z_NULL; - } - if ((s->window = (Byte *)ZALLOC(z, 1, w)) == Z_NULL) - { - ZFREE(z, s->hufts); - ZFREE(z, s); - return Z_NULL; - } - s->end = s->window + w; - s->checkfn = c; - s->mode = TYPE; - Tracev(("inflate: blocks allocated\n")); - inflate_blocks_reset(s, z, Z_NULL); - return s; -} -#endif - -#ifndef __APPLE__ -int inflate_blocks(inflate_blocks_statef *s, z_streamp z, int r) -{ - uInt t; /* temporary storage */ - uLong b; /* bit buffer */ - uInt k; /* bits in bit buffer */ - Byte *p; /* input data pointer */ - uInt n; /* bytes available there */ - Byte *q; /* output window write pointer */ - uInt m; /* bytes to end of window or read pointer */ - - /* copy input/output information to locals (UPDATE macro restores) */ - LOAD - - /* process input based on current state */ - while (1) switch (s->mode) - { - case TYPE: - NEEDBITS(3) - t = (uInt)b & 7; - s->last = t & 1; - switch (t >> 1) - { - case 0: /* stored */ - Tracev(("inflate: stored block%s\n", - s->last ? " (last)" : "")); - DUMPBITS(3) - t = k & 7; /* go to byte boundary */ - DUMPBITS(t) - s->mode = LENS; /* get length of stored block */ - break; - case 1: /* fixed */ - Tracev(("inflate: fixed codes block%s\n", - s->last ? " (last)" : "")); - { - uInt bl, bd; - inflate_huft *tl, *td; - - inflate_trees_fixed(&bl, &bd, &tl, &td, z); - s->sub.decode.codes = inflate_codes_new(bl, bd, tl, td, z); - if (s->sub.decode.codes == Z_NULL) - { - r = Z_MEM_ERROR; - LEAVE - } - } - DUMPBITS(3) - s->mode = CODES; - break; - case 2: /* dynamic */ - Tracev(("inflate: dynamic codes block%s\n", - s->last ? " (last)" : "")); - DUMPBITS(3) - s->mode = TABLE; - break; - case 3: /* illegal */ - DUMPBITS(3) - s->mode = BAD; - z->msg = (char*)"invalid block type"; - r = Z_DATA_ERROR; - LEAVE - } - break; - case LENS: - NEEDBITS(32) - if ((((~b) >> 16) & 0xffff) != (b & 0xffff)) - { - s->mode = BAD; - z->msg = (char*)"invalid stored block lengths"; - r = Z_DATA_ERROR; - LEAVE - } - s->sub.left = (uInt)b & 0xffff; - b = k = 0; /* dump bits */ - Tracev(("inflate: stored length %u\n", s->sub.left)); - s->mode = s->sub.left ? STORED : (s->last ? DRY : TYPE); - break; - case STORED: - if (n == 0) - LEAVE - NEEDOUT - t = s->sub.left; - if (t > n) t = n; - if (t > m) t = m; - zmemcpy(q, p, t); - p += t; n -= t; - q += t; m -= t; - if ((s->sub.left -= t) != 0) - break; - Tracev(("inflate: stored end, %lu total out\n", - z->total_out + (q >= s->read ? q - s->read : - (s->end - s->read) + (q - s->window)))); - s->mode = s->last ? DRY : TYPE; - break; - case TABLE: - NEEDBITS(14) - s->sub.trees.table = t = (uInt)b & 0x3fff; -#ifndef PKZIP_BUG_WORKAROUND - if ((t & 0x1f) > 29 || ((t >> 5) & 0x1f) > 29) - { - s->mode = BAD; - z->msg = (char*)"too many length or distance symbols"; - r = Z_DATA_ERROR; - LEAVE - } -#endif - t = 258 + (t & 0x1f) + ((t >> 5) & 0x1f); - if ((s->sub.trees.blens = (uInt*)ZALLOC(z, t, sizeof(uInt))) == Z_NULL) - { - r = Z_MEM_ERROR; - LEAVE - } - DUMPBITS(14) - s->sub.trees.index = 0; - Tracev(("inflate: table sizes ok\n")); - s->mode = BTREE; - case BTREE: - while (s->sub.trees.index < 4 + (s->sub.trees.table >> 10)) - { - NEEDBITS(3) - s->sub.trees.blens[border[s->sub.trees.index++]] = (uInt)b & 7; - DUMPBITS(3) - } - while (s->sub.trees.index < 19) - s->sub.trees.blens[border[s->sub.trees.index++]] = 0; - s->sub.trees.bb = 7; - t = inflate_trees_bits(s->sub.trees.blens, &s->sub.trees.bb, - &s->sub.trees.tb, s->hufts, z); - if (t != Z_OK) - { - ZFREE(z, s->sub.trees.blens); - r = t; - if (r == Z_DATA_ERROR) - s->mode = BAD; - LEAVE - } - s->sub.trees.index = 0; - Tracev(("inflate: bits tree ok\n")); - s->mode = DTREE; - case DTREE: - while (t = s->sub.trees.table, - s->sub.trees.index < 258 + (t & 0x1f) + ((t >> 5) & 0x1f)) - { - inflate_huft *h; - uInt i, j, c; - - t = s->sub.trees.bb; - NEEDBITS(t) - h = s->sub.trees.tb + ((uInt)b & inflate_mask[t]); - t = h->bits; - c = h->base; - if (c < 16) - { - DUMPBITS(t) - s->sub.trees.blens[s->sub.trees.index++] = c; - } - else /* c == 16..18 */ - { - i = c == 18 ? 7 : c - 14; - j = c == 18 ? 11 : 3; - NEEDBITS(t + i) - DUMPBITS(t) - j += (uInt)b & inflate_mask[i]; - DUMPBITS(i) - i = s->sub.trees.index; - t = s->sub.trees.table; - if (i + j > 258 + (t & 0x1f) + ((t >> 5) & 0x1f) || - (c == 16 && i < 1)) - { - ZFREE(z, s->sub.trees.blens); - s->mode = BAD; - z->msg = (char*)"invalid bit length repeat"; - r = Z_DATA_ERROR; - LEAVE - } - c = c == 16 ? s->sub.trees.blens[i - 1] : 0; - do { - s->sub.trees.blens[i++] = c; - } while (--j); - s->sub.trees.index = i; - } - } - s->sub.trees.tb = Z_NULL; - { - uInt bl, bd; - inflate_huft *tl, *td; - inflate_codes_statef *c; - - bl = 9; /* must be <= 9 for lookahead assumptions */ - bd = 6; /* must be <= 9 for lookahead assumptions */ - t = s->sub.trees.table; - t = inflate_trees_dynamic(257 + (t & 0x1f), 1 + ((t >> 5) & 0x1f), - s->sub.trees.blens, &bl, &bd, &tl, &td, - s->hufts, z); - ZFREE(z, s->sub.trees.blens); - if (t != Z_OK) - { - if (t == (uInt)Z_DATA_ERROR) - s->mode = BAD; - r = t; - LEAVE - } - Tracev(("inflate: trees ok\n")); - if ((c = inflate_codes_new(bl, bd, tl, td, z)) == Z_NULL) - { - r = Z_MEM_ERROR; - LEAVE - } - s->sub.decode.codes = c; - } - s->mode = CODES; - case CODES: - UPDATE - if ((r = inflate_codes(s, z, r)) != Z_STREAM_END) - return inflate_flush(s, z, r); - r = Z_OK; - inflate_codes_free(s->sub.decode.codes, z); - LOAD - Tracev(("inflate: codes end, %lu total out\n", - z->total_out + (q >= s->read ? q - s->read : - (s->end - s->read) + (q - s->window)))); - if (!s->last) - { - s->mode = TYPE; - break; - } - s->mode = DRY; - case DRY: - FLUSH - if (s->read != s->write) - LEAVE - s->mode = DONE; - case DONE: - r = Z_STREAM_END; - LEAVE - case BAD: - r = Z_DATA_ERROR; - LEAVE - default: - r = Z_STREAM_ERROR; - LEAVE - } -} -#endif - -#ifndef __APPLE__ -int inflate_blocks_free(inflate_blocks_statef *s, z_streamp z) -{ - inflate_blocks_reset(s, z, Z_NULL); - ZFREE(z, s->window); - ZFREE(z, s->hufts); - ZFREE(z, s); - Tracev(("inflate: blocks freed\n")); - return Z_OK; -} -#endif - -#ifndef __APPLE__ -void inflate_set_dictionary(inflate_blocks_statef *s, const Byte *d, uInt n) -{ - zmemcpy(s->window, d, n); - s->read = s->write = s->window + n; -} -#endif - -/* Returns true if inflate is currently at the end of a block generated - * by Z_SYNC_FLUSH or Z_FULL_FLUSH. - * IN assertion: s != Z_NULL - */ -#ifndef __APPLE__ -int inflate_blocks_sync_point(inflate_blocks_statef *s) -{ - return s->mode == LENS; -} -#endif - -/* And'ing with mask[n] masks the lower n bits */ -uInt inflate_mask[17] = { - 0x0000, - 0x0001, 0x0003, 0x0007, 0x000f, 0x001f, 0x003f, 0x007f, 0x00ff, - 0x01ff, 0x03ff, 0x07ff, 0x0fff, 0x1fff, 0x3fff, 0x7fff, 0xffff -}; - -/* copy as much as possible from the sliding window to the output area */ -#ifndef __APPLE__ -int inflate_flush(inflate_blocks_statef *s, z_streamp z, int r) -{ - uInt n; - Byte *p; - Byte *q; - - /* static copies of source and destination pointers */ - p = z->next_out; - q = s->read; - - /* compute number of bytes to copy as as end of window */ - n = (uInt)((q <= s->write ? s->write : s->end) - q); - if (n > z->avail_out) n = z->avail_out; - if (n && r == Z_BUF_ERROR) r = Z_OK; - - /* update counters */ - z->avail_out -= n; - z->total_out += n; - - /* update check information */ - if (s->checkfn != Z_NULL) - z->adler = s->check = (*s->checkfn)(s->check, q, n); - - /* copy as as end of window */ - zmemcpy(p, q, n); - p += n; - q += n; - - /* see if more to copy at beginning of window */ - if (q == s->end) - { - /* wrap pointers */ - q = s->window; - if (s->write == s->end) - s->write = s->window; - - /* compute bytes to copy */ - n = (uInt)(s->write - q); - if (n > z->avail_out) n = z->avail_out; - if (n && r == Z_BUF_ERROR) r = Z_OK; - - /* update counters */ - z->avail_out -= n; - z->total_out += n; - - /* update check information */ - if (s->checkfn != Z_NULL) - z->adler = s->check = (*s->checkfn)(s->check, q, n); - - /* copy */ - zmemcpy(p, q, n); - p += n; - q += n; - } - - /* update pointers */ - z->next_out = p; - s->read = q; - - /* done */ - return r; -} -#endif - -/* inftrees.c -- generate Huffman trees for efficient decoding - * Copyright (C) 1995-1998 Mark Adler - * For conditions of distribution and use, see copyright notice in zlib.h - */ - -#ifndef __APPLE__ -const char inflate_copyright[] = - " inflate 1.1.3 Copyright 1995-1998 Mark Adler "; -#endif - -/* - If you use the zlib library in a product, an acknowledgment is welcome - in the documentation of your product. If for some reason you cannot - include such an acknowledgment, I would appreciate that you keep this - copyright string in the executable of your product. - */ - -/* simplify the use of the inflate_huft type with some defines */ -#define exop word.what.Exop -#define bits word.what.Bits - - -static int huft_build OF(( - uInt *, /* code lengths in bits */ - uInt, /* number of codes */ - uInt, /* number of "simple" codes */ - const uInt *, /* list of base values for non-simple codes */ - const uInt *, /* list of extra bits for non-simple codes */ - inflate_huft **, /* result: starting table */ - uInt *, /* maximum lookup bits (returns actual) */ - inflate_huft *, /* space for trees */ - uInt *, /* hufts used in space */ - uInt * )); /* space for values */ - -/* Tables for deflate from PKZIP's appnote.txt. */ -static const uInt cplens[31] = { /* Copy lengths for literal codes 257..285 */ - 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, - 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0}; - /* see note #13 above about 258 */ -static const uInt cplext[31] = { /* Extra bits for literal codes 257..285 */ - 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, - 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, 112, 112}; /* 112==invalid */ -static const uInt cpdist[30] = { /* Copy offsets for distance codes 0..29 */ - 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, - 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, - 8193, 12289, 16385, 24577}; -static const uInt cpdext[30] = { /* Extra bits for distance codes */ - 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, - 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, - 12, 12, 13, 13}; - -/* - Huffman code decoding is performed using a multi-level table lookup. - The fastest way to decode is to simply build a lookup table whose - size is determined by the longest code. However, the time it takes - to build this table can also be a factor if the data being decoded - is not very long. The most common codes are necessarily the - shortest codes, so those codes dominate the decoding time, and hence - the speed. The idea is you can have a shorter table that decodes the - shorter, more probable codes, and then point to subsidiary tables for - the longer codes. The time it costs to decode the longer codes is - then traded against the time it takes to make longer tables. - - This results of this trade are in the variables lbits and dbits - below. lbits is the number of bits the first level table for literal/ - length codes can decode in one step, and dbits is the same thing for - the distance codes. Subsequent tables are also less than or equal to - those sizes. These values may be adjusted either when all of the - codes are shorter than that, in which case the longest code length in - bits is used, or when the shortest code is *longer* than the requested - table size, in which case the length of the shortest code in bits is - used. - - There are two different values for the two tables, since they code a - different number of possibilities each. The literal/length table - codes 286 possible values, or in a flat code, a little over eight - bits. The distance table codes 30 possible values, or a little less - than five bits, flat. The optimum values for speed end up being - about one bit more than those, so lbits is 8+1 and dbits is 5+1. - The optimum values may differ though from machine to machine, and - possibly even between compilers. Your mileage may vary. - */ - - -/* If BMAX needs to be larger than 16, then h and x[] should be uLong. */ -#define BMAX 15 /* maximum bit length of any code */ - -static int huft_build(uInt *b, uInt n, uInt s, const uInt *d, const uInt *e, inflate_huft ** t, uInt *m, inflate_huft *hp, uInt *hn, uInt *v) -//uInt *b; /* code lengths in bits (all assumed <= BMAX) */ -//uInt n; /* number of codes (assumed <= 288) */ -//uInt s; /* number of simple-valued codes (0..s-1) */ -//const uInt *d; /* list of base values for non-simple codes */ -//const uInt *e; /* list of extra bits for non-simple codes */ -//inflate_huft ** t; /* result: starting table */ -//uInt *m; /* maximum lookup bits, returns actual */ -//inflate_huft *hp; /* space for trees */ -//uInt *hn; /* hufts used in space */ -//uInt *v; /* working area: values in order of bit length */ -/* Given a list of code lengths and a maximum table size, make a set of - tables to decode that set of codes. Return Z_OK on success, Z_BUF_ERROR - if the given code set is incomplete (the tables are still built in this - case), Z_DATA_ERROR if the input is invalid (an over-subscribed set of - lengths), or Z_MEM_ERROR if not enough memory. */ -{ - - uInt a; /* counter for codes of length k */ - uInt c[BMAX+1]; /* bit length count table */ - uInt f; /* i repeats in table every f entries */ - int g; /* maximum code length */ - int h; /* table level */ - register uInt i; /* counter, current code */ - register uInt j; /* counter */ - register int k; /* number of bits in current code */ - int l; /* bits per table (returned in m) */ - uInt mask; /* (1 << w) - 1, to avoid cc -O bug on HP */ - register uInt *p; /* pointer into c[], b[], or v[] */ - inflate_huft *q; /* points to current table */ - struct inflate_huft_s r; /* table entry for structure assignment */ - inflate_huft *u[BMAX]; /* table stack */ - register int w; /* bits before this table == (l * h) */ - uInt x[BMAX+1]; /* bit offsets, then code stack */ - uInt *xp; /* pointer into x */ - int y; /* number of dummy codes added */ - uInt z; /* number of entries in current table */ - - - /* Generate counts for each bit length */ - p = c; -#define C0 *p++ = 0; -#define C2 C0 C0 C0 C0 -#define C4 C2 C2 C2 C2 - C4 /* clear c[]--assume BMAX+1 is 16 */ - p = b; i = n; - do { - c[*p++]++; /* assume all entries <= BMAX */ - } while (--i); - if (c[0] == n) /* null input--all zero length codes */ - { - *t = (inflate_huft *)Z_NULL; - *m = 0; - return Z_OK; - } - - - /* Find minimum and maximum length, bound *m by those */ - l = *m; - for (j = 1; j <= BMAX; j++) - if (c[j]) - break; - k = j; /* minimum code length */ - if ((uInt)l < j) - l = j; - for (i = BMAX; i; i--) - if (c[i]) - break; - g = i; /* maximum code length */ - if ((uInt)l > i) - l = i; - *m = l; - - - /* Adjust last length count to fill out codes, if needed */ - for (y = 1 << j; j < i; j++, y <<= 1) - if ((y -= c[j]) < 0) - return Z_DATA_ERROR; - if ((y -= c[i]) < 0) - return Z_DATA_ERROR; - c[i] += y; - - - /* Generate starting offsets into the value table for each length */ - x[1] = j = 0; - p = c + 1; xp = x + 2; - while (--i) { /* note that i == g from above */ - *xp++ = (j += *p++); - } - - - /* Make a table of values in order of bit lengths */ - p = b; i = 0; - do { - if ((j = *p++) != 0) - v[x[j]++] = i; - } while (++i < n); - n = x[g]; /* set n to length of v */ - - - /* Generate the Huffman codes and for each, make the table entries */ - x[0] = i = 0; /* first Huffman code is zero */ - p = v; /* grab values in bit order */ - h = -1; /* no tables yet--level -1 */ - w = -l; /* bits decoded == (l * h) */ - u[0] = (inflate_huft *)Z_NULL; /* just to keep compilers happy */ - q = (inflate_huft *)Z_NULL; /* ditto */ - z = 0; /* ditto */ - - /* go through the bit lengths (k already is bits in shortest code) */ - for (; k <= g; k++) - { - a = c[k]; - while (a--) - { - /* here i is the Huffman code of length k bits for value *p */ - /* make tables up to required level */ - while (k > w + l) - { - h++; - w += l; /* previous table always l bits */ - - /* compute minimum size table less than or equal to l bits */ - z = g - w; - z = z > (uInt)l ? l : z; /* table size upper limit */ - if ((f = 1 << (j = k - w)) > a + 1) /* try a k-w bit table */ - { /* too few codes for k-w bit table */ - f -= a + 1; /* deduct codes from patterns left */ - xp = c + k; - if (j < z) - while (++j < z) /* try smaller tables up to z bits */ - { - if ((f <<= 1) <= *++xp) - break; /* enough codes to use up j bits */ - f -= *xp; /* else deduct codes from patterns */ - } - } - z = 1 << j; /* table entries for j-bit table */ - - /* allocate new table */ - if (*hn + z > MANY) /* (note: doesn't matter for fixed) */ - return Z_MEM_ERROR; /* not enough memory */ - u[h] = q = hp + *hn; - *hn += z; - - /* connect to last table, if there is one */ - if (h) - { - x[h] = i; /* save pattern for backing up */ - r.bits = (Byte)l; /* bits to dump before this table */ - r.exop = (Byte)j; /* bits in this table */ - j = i >> (w - l); - r.base = (uInt)(q - u[h-1] - j); /* offset to this table */ - u[h-1][j] = r; /* connect to last table */ - } - else - *t = q; /* first table is returned result */ - } - - /* set up table entry in r */ - r.bits = (Byte)(k - w); - if (p >= v + n) - r.exop = 128 + 64; /* out of values--invalid code */ - else if (*p < s) - { - r.exop = (Byte)(*p < 256 ? 0 : 32 + 64); /* 256 is end-of-block */ - r.base = *p++; /* simple code is just the value */ - } - else - { - r.exop = (Byte)(e[*p - s] + 16 + 64);/* non-simple--look up in lists */ - r.base = d[*p++ - s]; - } - - /* fill code-like entries with r */ - f = 1 << (k - w); - for (j = i >> w; j < z; j += f) - q[j] = r; - - /* backwards increment the k-bit code i */ - for (j = 1 << (k - 1); i & j; j >>= 1) - i ^= j; - i ^= j; - - /* backup over finished tables */ - mask = (1 << w) - 1; /* needed on HP, cc -O bug */ - while ((i & mask) != x[h]) - { - h--; /* don't need to update q */ - w -= l; - mask = (1 << w) - 1; - } - } - } - - - /* Return Z_BUF_ERROR if we were given an incomplete table */ - return y != 0 && g != 1 ? Z_BUF_ERROR : Z_OK; -} - - -#ifndef __APPLE__ -int inflate_trees_bits(uInt *c, uInt *bb, inflate_huft * *tb, inflate_huft *hp, z_streamp z) -//uInt *c; /* 19 code lengths */ -//uInt *bb; /* bits tree desired/actual depth */ -//inflate_huft * *tb; /* bits tree result */ -//inflate_huft *hp; /* space for trees */ -//z_streamp z; /* for messages */ -{ - int r; - uInt hn = 0; /* hufts used in space */ - uInt *v; /* work area for huft_build */ - - if ((v = (uInt*)ZALLOC(z, 19, sizeof(uInt))) == Z_NULL) - return Z_MEM_ERROR; - r = huft_build(c, 19, 19, (uInt*)Z_NULL, (uInt*)Z_NULL, - tb, bb, hp, &hn, v); - if (r == Z_DATA_ERROR) - z->msg = (char*)"oversubscribed dynamic bit lengths tree"; - else if (r == Z_BUF_ERROR || *bb == 0) - { - z->msg = (char*)"incomplete dynamic bit lengths tree"; - r = Z_DATA_ERROR; - } - ZFREE(z, v); - return r; -} -#endif - -#ifndef __APPLE__ -int inflate_trees_dynamic(uInt nl, uInt nd, uInt *c, uInt *bl, uInt *bd, inflate_huft * *tl, inflate_huft * *td, inflate_huft *hp, z_streamp z) -//uInt nl; /* number of literal/length codes */ -//uInt nd; /* number of distance codes */ -//uInt *c; /* that many (total) code lengths */ -//uInt *bl; /* literal desired/actual bit depth */ -//uInt *bd; /* distance desired/actual bit depth */ -//inflate_huft * *tl; /* literal/length tree result */ -//inflate_huft * *td; /* distance tree result */ -//inflate_huft *hp; /* space for trees */ -//z_streamp z; /* for messages */ -{ - int r; - uInt hn = 0; /* hufts used in space */ - uInt *v; /* work area for huft_build */ - - /* allocate work area */ - if ((v = (uInt*)ZALLOC(z, 288, sizeof(uInt))) == Z_NULL) - return Z_MEM_ERROR; - - /* build literal/length tree */ - r = huft_build(c, nl, 257, cplens, cplext, tl, bl, hp, &hn, v); - if (r != Z_OK || *bl == 0) - { - if (r == Z_DATA_ERROR) - z->msg = (char*)"oversubscribed literal/length tree"; - else if (r != Z_MEM_ERROR) - { - z->msg = (char*)"incomplete literal/length tree"; - r = Z_DATA_ERROR; - } - ZFREE(z, v); - return r; - } - - /* build distance tree */ - r = huft_build(c + nl, nd, 0, cpdist, cpdext, td, bd, hp, &hn, v); - if (r != Z_OK || (*bd == 0 && nl > 257)) - { - if (r == Z_DATA_ERROR) - z->msg = (char*)"oversubscribed distance tree"; - else if (r == Z_BUF_ERROR) { -#ifdef PKZIP_BUG_WORKAROUND - r = Z_OK; - } -#else - z->msg = (char*)"incomplete distance tree"; - r = Z_DATA_ERROR; - } - else if (r != Z_MEM_ERROR) - { - z->msg = (char*)"empty distance tree with lengths"; - r = Z_DATA_ERROR; - } - ZFREE(z, v); - return r; -#endif - } - - /* done */ - ZFREE(z, v); - return Z_OK; -} -#endif - -/* inffixed.h -- table for decoding fixed codes - * Generated automatically by the maketree.c program - */ - -/* WARNING: this file should *not* be used by applications. It is - part of the implementation of the compression library and is - subject to change. Applications should only use zlib.h. - */ - -static uInt fixed_bl = 9; -static uInt fixed_bd = 5; -static inflate_huft fixed_tl[] = { - {{{96,7}},256}, {{{0,8}},80}, {{{0,8}},16}, {{{84,8}},115}, - {{{82,7}},31}, {{{0,8}},112}, {{{0,8}},48}, {{{0,9}},192}, - {{{80,7}},10}, {{{0,8}},96}, {{{0,8}},32}, {{{0,9}},160}, - {{{0,8}},0}, {{{0,8}},128}, {{{0,8}},64}, {{{0,9}},224}, - {{{80,7}},6}, {{{0,8}},88}, {{{0,8}},24}, {{{0,9}},144}, - {{{83,7}},59}, {{{0,8}},120}, {{{0,8}},56}, {{{0,9}},208}, - {{{81,7}},17}, {{{0,8}},104}, {{{0,8}},40}, {{{0,9}},176}, - {{{0,8}},8}, {{{0,8}},136}, {{{0,8}},72}, {{{0,9}},240}, - {{{80,7}},4}, {{{0,8}},84}, {{{0,8}},20}, {{{85,8}},227}, - {{{83,7}},43}, {{{0,8}},116}, {{{0,8}},52}, {{{0,9}},200}, - {{{81,7}},13}, {{{0,8}},100}, {{{0,8}},36}, {{{0,9}},168}, - {{{0,8}},4}, {{{0,8}},132}, {{{0,8}},68}, {{{0,9}},232}, - {{{80,7}},8}, {{{0,8}},92}, {{{0,8}},28}, {{{0,9}},152}, - {{{84,7}},83}, {{{0,8}},124}, {{{0,8}},60}, {{{0,9}},216}, - {{{82,7}},23}, {{{0,8}},108}, {{{0,8}},44}, {{{0,9}},184}, - {{{0,8}},12}, {{{0,8}},140}, {{{0,8}},76}, {{{0,9}},248}, - {{{80,7}},3}, {{{0,8}},82}, {{{0,8}},18}, {{{85,8}},163}, - {{{83,7}},35}, {{{0,8}},114}, {{{0,8}},50}, {{{0,9}},196}, - {{{81,7}},11}, {{{0,8}},98}, {{{0,8}},34}, {{{0,9}},164}, - {{{0,8}},2}, {{{0,8}},130}, {{{0,8}},66}, {{{0,9}},228}, - {{{80,7}},7}, {{{0,8}},90}, {{{0,8}},26}, {{{0,9}},148}, - {{{84,7}},67}, {{{0,8}},122}, {{{0,8}},58}, {{{0,9}},212}, - {{{82,7}},19}, {{{0,8}},106}, {{{0,8}},42}, {{{0,9}},180}, - {{{0,8}},10}, {{{0,8}},138}, {{{0,8}},74}, {{{0,9}},244}, - {{{80,7}},5}, {{{0,8}},86}, {{{0,8}},22}, {{{192,8}},0}, - {{{83,7}},51}, {{{0,8}},118}, {{{0,8}},54}, {{{0,9}},204}, - {{{81,7}},15}, {{{0,8}},102}, {{{0,8}},38}, {{{0,9}},172}, - {{{0,8}},6}, {{{0,8}},134}, {{{0,8}},70}, {{{0,9}},236}, - {{{80,7}},9}, {{{0,8}},94}, {{{0,8}},30}, {{{0,9}},156}, - {{{84,7}},99}, {{{0,8}},126}, {{{0,8}},62}, {{{0,9}},220}, - {{{82,7}},27}, {{{0,8}},110}, {{{0,8}},46}, {{{0,9}},188}, - {{{0,8}},14}, {{{0,8}},142}, {{{0,8}},78}, {{{0,9}},252}, - {{{96,7}},256}, {{{0,8}},81}, {{{0,8}},17}, {{{85,8}},131}, - {{{82,7}},31}, {{{0,8}},113}, {{{0,8}},49}, {{{0,9}},194}, - {{{80,7}},10}, {{{0,8}},97}, {{{0,8}},33}, {{{0,9}},162}, - {{{0,8}},1}, {{{0,8}},129}, {{{0,8}},65}, {{{0,9}},226}, - {{{80,7}},6}, {{{0,8}},89}, {{{0,8}},25}, {{{0,9}},146}, - {{{83,7}},59}, {{{0,8}},121}, {{{0,8}},57}, {{{0,9}},210}, - {{{81,7}},17}, {{{0,8}},105}, {{{0,8}},41}, {{{0,9}},178}, - {{{0,8}},9}, {{{0,8}},137}, {{{0,8}},73}, {{{0,9}},242}, - {{{80,7}},4}, {{{0,8}},85}, {{{0,8}},21}, {{{80,8}},258}, - {{{83,7}},43}, {{{0,8}},117}, {{{0,8}},53}, {{{0,9}},202}, - {{{81,7}},13}, {{{0,8}},101}, {{{0,8}},37}, {{{0,9}},170}, - {{{0,8}},5}, {{{0,8}},133}, {{{0,8}},69}, {{{0,9}},234}, - {{{80,7}},8}, {{{0,8}},93}, {{{0,8}},29}, {{{0,9}},154}, - {{{84,7}},83}, {{{0,8}},125}, {{{0,8}},61}, {{{0,9}},218}, - {{{82,7}},23}, {{{0,8}},109}, {{{0,8}},45}, {{{0,9}},186}, - {{{0,8}},13}, {{{0,8}},141}, {{{0,8}},77}, {{{0,9}},250}, - {{{80,7}},3}, {{{0,8}},83}, {{{0,8}},19}, {{{85,8}},195}, - {{{83,7}},35}, {{{0,8}},115}, {{{0,8}},51}, {{{0,9}},198}, - {{{81,7}},11}, {{{0,8}},99}, {{{0,8}},35}, {{{0,9}},166}, - {{{0,8}},3}, {{{0,8}},131}, {{{0,8}},67}, {{{0,9}},230}, - {{{80,7}},7}, {{{0,8}},91}, {{{0,8}},27}, {{{0,9}},150}, - {{{84,7}},67}, {{{0,8}},123}, {{{0,8}},59}, {{{0,9}},214}, - {{{82,7}},19}, {{{0,8}},107}, {{{0,8}},43}, {{{0,9}},182}, - {{{0,8}},11}, {{{0,8}},139}, {{{0,8}},75}, {{{0,9}},246}, - {{{80,7}},5}, {{{0,8}},87}, {{{0,8}},23}, {{{192,8}},0}, - {{{83,7}},51}, {{{0,8}},119}, {{{0,8}},55}, {{{0,9}},206}, - {{{81,7}},15}, {{{0,8}},103}, {{{0,8}},39}, {{{0,9}},174}, - {{{0,8}},7}, {{{0,8}},135}, {{{0,8}},71}, {{{0,9}},238}, - {{{80,7}},9}, {{{0,8}},95}, {{{0,8}},31}, {{{0,9}},158}, - {{{84,7}},99}, {{{0,8}},127}, {{{0,8}},63}, {{{0,9}},222}, - {{{82,7}},27}, {{{0,8}},111}, {{{0,8}},47}, {{{0,9}},190}, - {{{0,8}},15}, {{{0,8}},143}, {{{0,8}},79}, {{{0,9}},254}, - {{{96,7}},256}, {{{0,8}},80}, {{{0,8}},16}, {{{84,8}},115}, - {{{82,7}},31}, {{{0,8}},112}, {{{0,8}},48}, {{{0,9}},193}, - {{{80,7}},10}, {{{0,8}},96}, {{{0,8}},32}, {{{0,9}},161}, - {{{0,8}},0}, {{{0,8}},128}, {{{0,8}},64}, {{{0,9}},225}, - {{{80,7}},6}, {{{0,8}},88}, {{{0,8}},24}, {{{0,9}},145}, - {{{83,7}},59}, {{{0,8}},120}, {{{0,8}},56}, {{{0,9}},209}, - {{{81,7}},17}, {{{0,8}},104}, {{{0,8}},40}, {{{0,9}},177}, - {{{0,8}},8}, {{{0,8}},136}, {{{0,8}},72}, {{{0,9}},241}, - {{{80,7}},4}, {{{0,8}},84}, {{{0,8}},20}, {{{85,8}},227}, - {{{83,7}},43}, {{{0,8}},116}, {{{0,8}},52}, {{{0,9}},201}, - {{{81,7}},13}, {{{0,8}},100}, {{{0,8}},36}, {{{0,9}},169}, - {{{0,8}},4}, {{{0,8}},132}, {{{0,8}},68}, {{{0,9}},233}, - {{{80,7}},8}, {{{0,8}},92}, {{{0,8}},28}, {{{0,9}},153}, - {{{84,7}},83}, {{{0,8}},124}, {{{0,8}},60}, {{{0,9}},217}, - {{{82,7}},23}, {{{0,8}},108}, {{{0,8}},44}, {{{0,9}},185}, - {{{0,8}},12}, {{{0,8}},140}, {{{0,8}},76}, {{{0,9}},249}, - {{{80,7}},3}, {{{0,8}},82}, {{{0,8}},18}, {{{85,8}},163}, - {{{83,7}},35}, {{{0,8}},114}, {{{0,8}},50}, {{{0,9}},197}, - {{{81,7}},11}, {{{0,8}},98}, {{{0,8}},34}, {{{0,9}},165}, - {{{0,8}},2}, {{{0,8}},130}, {{{0,8}},66}, {{{0,9}},229}, - {{{80,7}},7}, {{{0,8}},90}, {{{0,8}},26}, {{{0,9}},149}, - {{{84,7}},67}, {{{0,8}},122}, {{{0,8}},58}, {{{0,9}},213}, - {{{82,7}},19}, {{{0,8}},106}, {{{0,8}},42}, {{{0,9}},181}, - {{{0,8}},10}, {{{0,8}},138}, {{{0,8}},74}, {{{0,9}},245}, - {{{80,7}},5}, {{{0,8}},86}, {{{0,8}},22}, {{{192,8}},0}, - {{{83,7}},51}, {{{0,8}},118}, {{{0,8}},54}, {{{0,9}},205}, - {{{81,7}},15}, {{{0,8}},102}, {{{0,8}},38}, {{{0,9}},173}, - {{{0,8}},6}, {{{0,8}},134}, {{{0,8}},70}, {{{0,9}},237}, - {{{80,7}},9}, {{{0,8}},94}, {{{0,8}},30}, {{{0,9}},157}, - {{{84,7}},99}, {{{0,8}},126}, {{{0,8}},62}, {{{0,9}},221}, - {{{82,7}},27}, {{{0,8}},110}, {{{0,8}},46}, {{{0,9}},189}, - {{{0,8}},14}, {{{0,8}},142}, {{{0,8}},78}, {{{0,9}},253}, - {{{96,7}},256}, {{{0,8}},81}, {{{0,8}},17}, {{{85,8}},131}, - {{{82,7}},31}, {{{0,8}},113}, {{{0,8}},49}, {{{0,9}},195}, - {{{80,7}},10}, {{{0,8}},97}, {{{0,8}},33}, {{{0,9}},163}, - {{{0,8}},1}, {{{0,8}},129}, {{{0,8}},65}, {{{0,9}},227}, - {{{80,7}},6}, {{{0,8}},89}, {{{0,8}},25}, {{{0,9}},147}, - {{{83,7}},59}, {{{0,8}},121}, {{{0,8}},57}, {{{0,9}},211}, - {{{81,7}},17}, {{{0,8}},105}, {{{0,8}},41}, {{{0,9}},179}, - {{{0,8}},9}, {{{0,8}},137}, {{{0,8}},73}, {{{0,9}},243}, - {{{80,7}},4}, {{{0,8}},85}, {{{0,8}},21}, {{{80,8}},258}, - {{{83,7}},43}, {{{0,8}},117}, {{{0,8}},53}, {{{0,9}},203}, - {{{81,7}},13}, {{{0,8}},101}, {{{0,8}},37}, {{{0,9}},171}, - {{{0,8}},5}, {{{0,8}},133}, {{{0,8}},69}, {{{0,9}},235}, - {{{80,7}},8}, {{{0,8}},93}, {{{0,8}},29}, {{{0,9}},155}, - {{{84,7}},83}, {{{0,8}},125}, {{{0,8}},61}, {{{0,9}},219}, - {{{82,7}},23}, {{{0,8}},109}, {{{0,8}},45}, {{{0,9}},187}, - {{{0,8}},13}, {{{0,8}},141}, {{{0,8}},77}, {{{0,9}},251}, - {{{80,7}},3}, {{{0,8}},83}, {{{0,8}},19}, {{{85,8}},195}, - {{{83,7}},35}, {{{0,8}},115}, {{{0,8}},51}, {{{0,9}},199}, - {{{81,7}},11}, {{{0,8}},99}, {{{0,8}},35}, {{{0,9}},167}, - {{{0,8}},3}, {{{0,8}},131}, {{{0,8}},67}, {{{0,9}},231}, - {{{80,7}},7}, {{{0,8}},91}, {{{0,8}},27}, {{{0,9}},151}, - {{{84,7}},67}, {{{0,8}},123}, {{{0,8}},59}, {{{0,9}},215}, - {{{82,7}},19}, {{{0,8}},107}, {{{0,8}},43}, {{{0,9}},183}, - {{{0,8}},11}, {{{0,8}},139}, {{{0,8}},75}, {{{0,9}},247}, - {{{80,7}},5}, {{{0,8}},87}, {{{0,8}},23}, {{{192,8}},0}, - {{{83,7}},51}, {{{0,8}},119}, {{{0,8}},55}, {{{0,9}},207}, - {{{81,7}},15}, {{{0,8}},103}, {{{0,8}},39}, {{{0,9}},175}, - {{{0,8}},7}, {{{0,8}},135}, {{{0,8}},71}, {{{0,9}},239}, - {{{80,7}},9}, {{{0,8}},95}, {{{0,8}},31}, {{{0,9}},159}, - {{{84,7}},99}, {{{0,8}},127}, {{{0,8}},63}, {{{0,9}},223}, - {{{82,7}},27}, {{{0,8}},111}, {{{0,8}},47}, {{{0,9}},191}, - {{{0,8}},15}, {{{0,8}},143}, {{{0,8}},79}, {{{0,9}},255} - }; -static inflate_huft fixed_td[] = { - {{{80,5}},1}, {{{87,5}},257}, {{{83,5}},17}, {{{91,5}},4097}, - {{{81,5}},5}, {{{89,5}},1025}, {{{85,5}},65}, {{{93,5}},16385}, - {{{80,5}},3}, {{{88,5}},513}, {{{84,5}},33}, {{{92,5}},8193}, - {{{82,5}},9}, {{{90,5}},2049}, {{{86,5}},129}, {{{192,5}},24577}, - {{{80,5}},2}, {{{87,5}},385}, {{{83,5}},25}, {{{91,5}},6145}, - {{{81,5}},7}, {{{89,5}},1537}, {{{85,5}},97}, {{{93,5}},24577}, - {{{80,5}},4}, {{{88,5}},769}, {{{84,5}},49}, {{{92,5}},12289}, - {{{82,5}},13}, {{{90,5}},3073}, {{{86,5}},193}, {{{192,5}},24577} - }; - -#ifndef __APPLE__ -int inflate_trees_fixed(uInt *bl, uInt *bd, inflate_huft * *tl, inflate_huft * *td, z_streamp z) -//uInt *bl; /* literal desired/actual bit depth */ -//uInt *bd; /* distance desired/actual bit depth */ -//inflate_huft * *tl; /* literal/length tree result */ -//inflate_huft * *td; /* distance tree result */ -//z_streamp z; /* for memory allocation */ -{ - *bl = fixed_bl; - *bd = fixed_bd; - *tl = fixed_tl; - *td = fixed_td; - return Z_OK; -} -#endif - -/* simplify the use of the inflate_huft type with some defines */ -#define exop word.what.Exop -#define bits word.what.Bits - -/* macros for bit input with no checking and for returning unused bytes */ -#define GRABBITS(j) {while(k<(j)){b|=((uLong)NEXTBYTE)<avail_in-n;c=(k>>3)>3:c;n+=c;p-=c;k-=c<<3;} - -/* Called with number of bytes left to write in window at least 258 - (the maximum string length) and number of input bytes available - at least ten. The ten bytes are six bytes for the longest length/ - distance pair plus four bytes for overloading the bit buffer. */ - -#ifndef __APPLE__ -int inflate_fast(uInt bl, uInt bd, inflate_huft *tl, inflate_huft *td, inflate_blocks_statef *s, z_streamp z) -{ - inflate_huft *t; /* temporary pointer */ - uInt e; /* extra bits or operation */ - uLong b; /* bit buffer */ - uInt k; /* bits in bit buffer */ - Byte *p; /* input data pointer */ - uInt n; /* bytes available there */ - Byte *q; /* output window write pointer */ - uInt m; /* bytes to end of window or read pointer */ - uInt ml; /* mask for literal/length tree */ - uInt md; /* mask for distance tree */ - uInt c; /* bytes to copy */ - uInt d; /* distance back to copy from */ - Byte *r; /* copy source pointer */ - - /* load input, output, bit values */ - LOAD - - /* initialize masks */ - ml = inflate_mask[bl]; - md = inflate_mask[bd]; - - /* do until not enough input or output space for fast loop */ - do { /* assume called with m >= 258 && n >= 10 */ - /* get literal/length code */ - GRABBITS(20) /* max bits for literal/length code */ - if ((e = (t = tl + ((uInt)b & ml))->exop) == 0) - { - DUMPBITS(t->bits) - Tracevv((t->base >= 0x20 && t->base < 0x7f ? - "inflate: * literal '%c'\n" : - "inflate: * literal 0x%02x\n", t->base)); - *q++ = (Byte)t->base; - m--; - continue; - } - do { - DUMPBITS(t->bits) - if (e & 16) - { - /* get extra bits for length */ - e &= 15; - c = t->base + ((uInt)b & inflate_mask[e]); - DUMPBITS(e) - Tracevv(("inflate: * length %u\n", c)); - - /* decode distance base of block to copy */ - GRABBITS(15); /* max bits for distance code */ - e = (t = td + ((uInt)b & md))->exop; - do { - DUMPBITS(t->bits) - if (e & 16) - { - /* get extra bits to add to distance base */ - e &= 15; - GRABBITS(e) /* get extra bits (up to 13) */ - d = t->base + ((uInt)b & inflate_mask[e]); - DUMPBITS(e) - Tracevv(("inflate: * distance %u\n", d)); - - /* do the copy */ - m -= c; - if ((uInt)(q - s->window) >= d) /* offset before dest */ - { /* just copy */ - r = q - d; - *q++ = *r++; c--; /* minimum count is three, */ - *q++ = *r++; c--; /* so unroll loop a little */ - } - else /* else offset after destination */ - { - e = d - (uInt)(q - s->window); /* bytes from offset to end */ - r = s->end - e; /* pointer to offset */ - if (c > e) /* if source crosses, */ - { - c -= e; /* copy to end of window */ - do { - *q++ = *r++; - } while (--e); - r = s->window; /* copy rest from start of window */ - } - } - do { /* copy all or what's left */ - *q++ = *r++; - } while (--c); - break; - } - else if ((e & 64) == 0) - { - t += t->base; - e = (t += ((uInt)b & inflate_mask[e]))->exop; - } - else - { - z->msg = (char*)"invalid distance code"; - UNGRAB - UPDATE - return Z_DATA_ERROR; - } - } while (1); - break; - } - if ((e & 64) == 0) - { - t += t->base; - if ((e = (t += ((uInt)b & inflate_mask[e]))->exop) == 0) - { - DUMPBITS(t->bits) - Tracevv((t->base >= 0x20 && t->base < 0x7f ? - "inflate: * literal '%c'\n" : - "inflate: * literal 0x%02x\n", t->base)); - *q++ = (Byte)t->base; - m--; - break; - } - } - else if (e & 32) - { - Tracevv(("inflate: * end of block\n")); - UNGRAB - UPDATE - return Z_STREAM_END; - } - else - { - z->msg = (char*)"invalid literal/length code"; - UNGRAB - UPDATE - return Z_DATA_ERROR; - } - } while (1); - } while (m >= 258 && n >= 10); - - /* not enough input or output--restore pointers and return */ - UNGRAB - UPDATE - return Z_OK; -} -#endif - -/* infcodes.c -- process literals and length/distance pairs - * Copyright (C) 1995-1998 Mark Adler - * For conditions of distribution and use, see copyright notice in zlib.h - */ - -/* simplify the use of the inflate_huft type with some defines */ -#define exop word.what.Exop -#define bits word.what.Bits - -typedef enum { /* waiting for "i:"=input, "o:"=output, "x:"=nothing */ - START, /* x: set up for LEN */ - LEN, /* i: get length/literal/eob next */ - LENEXT, /* i: getting length extra (have base) */ - DIST, /* i: get distance next */ - DISTEXT, /* i: getting distance extra */ - COPY, /* o: copying bytes in window, waiting for space */ - LIT, /* o: got literal, waiting for output space */ - WASH, /* o: got eob, possibly still output waiting */ - END, /* x: got eob and all data flushed */ - BADCODE} /* x: got error */ -inflate_codes_mode; - -/* inflate codes private state */ -struct inflate_codes_state { - - /* mode */ - inflate_codes_mode mode; /* current inflate_codes mode */ - - /* mode dependent information */ - uInt len; - union { - struct { - inflate_huft *tree; /* pointer into tree */ - uInt need; /* bits needed */ - } code; /* if LEN or DIST, where in tree */ - uInt lit; /* if LIT, literal */ - struct { - uInt get; /* bits to get for extra */ - uInt dist; /* distance back to copy from */ - } copy; /* if EXT or COPY, where and how much */ - } sub; /* submode */ - - /* mode independent information */ - Byte lbits; /* ltree bits decoded per branch */ - Byte dbits; /* dtree bits decoder per branch */ - inflate_huft *ltree; /* literal/length/eob tree */ - inflate_huft *dtree; /* distance tree */ - -}; - -#ifndef __APPLE__ -inflate_codes_statef *inflate_codes_new(uInt bl, uInt bd, inflate_huft *tl, inflate_huft *td, z_streamp z) -{ - inflate_codes_statef *c; - - if ((c = (inflate_codes_statef *) - ZALLOC(z,1,sizeof(struct inflate_codes_state))) != Z_NULL) - { - c->mode = START; - c->lbits = (Byte)bl; - c->dbits = (Byte)bd; - c->ltree = tl; - c->dtree = td; - Tracev(("inflate: codes new\n")); - } - return c; -} -#endif - -#ifndef __APPLE__ -int inflate_codes(inflate_blocks_statef *s, z_streamp z, int r) -{ - uInt j; /* temporary storage */ - inflate_huft *t; /* temporary pointer */ - uInt e; /* extra bits or operation */ - uLong b; /* bit buffer */ - uInt k; /* bits in bit buffer */ - Byte *p; /* input data pointer */ - uInt n; /* bytes available there */ - Byte *q; /* output window write pointer */ - uInt m; /* bytes to end of window or read pointer */ - Byte *f; /* pointer to copy strings from */ - inflate_codes_statef *c = s->sub.decode.codes; /* codes state */ - - /* copy input/output information to locals (UPDATE macro restores) */ - LOAD - - /* process input and output based on current state */ - while (1) switch (c->mode) - { /* waiting for "i:"=input, "o:"=output, "x:"=nothing */ - case START: /* x: set up for LEN */ -#ifndef SLOW - if (m >= 258 && n >= 10) - { - UPDATE - r = inflate_fast(c->lbits, c->dbits, c->ltree, c->dtree, s, z); - LOAD - if (r != Z_OK) - { - c->mode = r == Z_STREAM_END ? WASH : BADCODE; - break; - } - } -#endif /* !SLOW */ - c->sub.code.need = c->lbits; - c->sub.code.tree = c->ltree; - c->mode = LEN; - case LEN: /* i: get length/literal/eob next */ - j = c->sub.code.need; - NEEDBITS(j) - t = c->sub.code.tree + ((uInt)b & inflate_mask[j]); - DUMPBITS(t->bits) - e = (uInt)(t->exop); - if (e == 0) /* literal */ - { - c->sub.lit = t->base; - Tracevv((t->base >= 0x20 && t->base < 0x7f ? - "inflate: literal '%c'\n" : - "inflate: literal 0x%02x\n", t->base)); - c->mode = LIT; - break; - } - if (e & 16) /* length */ - { - c->sub.copy.get = e & 15; - c->len = t->base; - c->mode = LENEXT; - break; - } - if ((e & 64) == 0) /* next table */ - { - c->sub.code.need = e; - c->sub.code.tree = t + t->base; - break; - } - if (e & 32) /* end of block */ - { - Tracevv(("inflate: end of block\n")); - c->mode = WASH; - break; - } - c->mode = BADCODE; /* invalid code */ - z->msg = (char*)"invalid literal/length code"; - r = Z_DATA_ERROR; - LEAVE - case LENEXT: /* i: getting length extra (have base) */ - j = c->sub.copy.get; - NEEDBITS(j) - c->len += (uInt)b & inflate_mask[j]; - DUMPBITS(j) - c->sub.code.need = c->dbits; - c->sub.code.tree = c->dtree; - Tracevv(("inflate: length %u\n", c->len)); - c->mode = DIST; - case DIST: /* i: get distance next */ - j = c->sub.code.need; - NEEDBITS(j) - t = c->sub.code.tree + ((uInt)b & inflate_mask[j]); - DUMPBITS(t->bits) - e = (uInt)(t->exop); - if (e & 16) /* distance */ - { - c->sub.copy.get = e & 15; - c->sub.copy.dist = t->base; - c->mode = DISTEXT; - break; - } - if ((e & 64) == 0) /* next table */ - { - c->sub.code.need = e; - c->sub.code.tree = t + t->base; - break; - } - c->mode = BADCODE; /* invalid code */ - z->msg = (char*)"invalid distance code"; - r = Z_DATA_ERROR; - LEAVE - case DISTEXT: /* i: getting distance extra */ - j = c->sub.copy.get; - NEEDBITS(j) - c->sub.copy.dist += (uInt)b & inflate_mask[j]; - DUMPBITS(j) - Tracevv(("inflate: distance %u\n", c->sub.copy.dist)); - c->mode = COPY; - case COPY: /* o: copying bytes in window, waiting for space */ -#ifndef __TURBOC__ /* Turbo C bug for following expression */ - f = (uInt)(q - s->window) < c->sub.copy.dist ? - s->end - (c->sub.copy.dist - (q - s->window)) : - q - c->sub.copy.dist; -#else - f = q - c->sub.copy.dist; - if ((uInt)(q - s->window) < c->sub.copy.dist) - f = s->end - (c->sub.copy.dist - (uInt)(q - s->window)); -#endif - while (c->len) - { - NEEDOUT - OUTBYTE(*f++) - if (f == s->end) - f = s->window; - c->len--; - } - c->mode = START; - break; - case LIT: /* o: got literal, waiting for output space */ - NEEDOUT - OUTBYTE(c->sub.lit) - c->mode = START; - break; - case WASH: /* o: got eob, possibly more output */ - if (k > 7) /* return unused byte, if any */ - { - Assert(k < 16, "inflate_codes grabbed too many bytes") - k -= 8; - n++; - p--; /* can always return one */ - } - FLUSH - if (s->read != s->write) - LEAVE - c->mode = END; - case END: - r = Z_STREAM_END; - LEAVE - case BADCODE: /* x: got error */ - r = Z_DATA_ERROR; - LEAVE - default: - r = Z_STREAM_ERROR; - LEAVE - } -#ifdef NEED_DUMMY_RETURN - return Z_STREAM_ERROR; /* Some dumb compilers complain without this */ -#endif -} -#endif - -#ifndef __APPLE__ -void inflate_codes_free(inflate_codes_statef *c, z_streamp z) -{ - ZFREE(z, c); - Tracev(("inflate: codes free\n")); -} -#endif - -/* adler32.c -- compute the Adler-32 checksum of a data stream - * Copyright (C) 1995-1998 Mark Adler - * For conditions of distribution and use, see copyright notice in zlib.h - */ - -#define BASE 65521L /* largest prime smaller than 65536 */ -#define NMAX 5552 -/* NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 */ - -#undef DO1 -#undef DO2 -#undef DO4 -#undef DO8 - -#define DO1(buf,i) {s1 += buf[i]; s2 += s1;} -#define DO2(buf,i) DO1(buf,i); DO1(buf,i+1); -#define DO4(buf,i) DO2(buf,i); DO2(buf,i+2); -#define DO8(buf,i) DO4(buf,i); DO4(buf,i+4); -#define DO16(buf) DO8(buf,0); DO8(buf,8); - -/* ========================================================================= */ -#ifndef __APPLE__ -uLong adler32(uLong adler, const Byte *buf, uInt len) -{ - unsigned long s1 = adler & 0xffff; - unsigned long s2 = (adler >> 16) & 0xffff; - int k; - - if (buf == Z_NULL) return 1L; - - while (len > 0) { - k = len < NMAX ? len : NMAX; - len -= k; - while (k >= 16) { - DO16(buf); - buf += 16; - k -= 16; - } - if (k != 0) do { - s1 += *buf++; - s2 += s1; - } while (--k); - s1 %= BASE; - s2 %= BASE; - } - return (s2 << 16) | s1; -} -#endif - - -/* infblock.h -- header to use infblock.c - * Copyright (C) 1995-1998 Mark Adler - * For conditions of distribution and use, see copyright notice in zlib.h - */ - -/* WARNING: this file should *not* be used by applications. It is - part of the implementation of the compression library and is - subject to change. Applications should only use zlib.h. - */ - -extern inflate_blocks_statef * inflate_blocks_new OF(( - z_streamp z, - check_func c, /* check function */ - uInt w)); /* window size */ - -extern int inflate_blocks OF(( - inflate_blocks_statef *, - z_streamp , - int)); /* initial return code */ - -extern void inflate_blocks_reset OF(( - inflate_blocks_statef *, - z_streamp , - uLong *)); /* check value on output */ - -extern int inflate_blocks_free OF(( - inflate_blocks_statef *, - z_streamp)); - -extern void inflate_set_dictionary OF(( - inflate_blocks_statef *s, - const Byte *d, /* dictionary */ - uInt n)); /* dictionary length */ - -extern int inflate_blocks_sync_point OF(( - inflate_blocks_statef *s)); - -typedef enum { - imMETHOD, /* waiting for method byte */ - imFLAG, /* waiting for flag byte */ - imDICT4, /* four dictionary check bytes to go */ - imDICT3, /* three dictionary check bytes to go */ - imDICT2, /* two dictionary check bytes to go */ - imDICT1, /* one dictionary check byte to go */ - imDICT0, /* waiting for inflateSetDictionary */ - imBLOCKS, /* decompressing blocks */ - imCHECK4, /* four check bytes to go */ - imCHECK3, /* three check bytes to go */ - imCHECK2, /* two check bytes to go */ - imCHECK1, /* one check byte to go */ - imDONE, /* finished check, done */ - imBAD} /* got an error--stay here */ -inflate_mode; - -/* inflate private state */ -struct internal_state { - - /* mode */ - inflate_mode mode; /* current inflate mode */ - - /* mode dependent information */ - union { - uInt method; /* if FLAGS, method byte */ - struct { - uLong was; /* computed check value */ - uLong need; /* stream check value */ - } check; /* if CHECK, check values to compare */ - uInt marker; /* if BAD, inflateSync's marker bytes count */ - } sub; /* submode */ - - /* mode independent information */ - int nowrap; /* flag for no wrapper */ - uInt wbits; /* log2(window size) (8..15, defaults to 15) */ - inflate_blocks_statef - *blocks; /* current inflate_blocks state */ - -}; - - -#ifndef __APPLE__ -int inflateReset(z_streamp z) -{ - if (z == Z_NULL || z->state == Z_NULL) - return Z_STREAM_ERROR; - z->total_in = z->total_out = 0; - z->msg = Z_NULL; - z->state->mode = z->state->nowrap ? imBLOCKS : imMETHOD; - inflate_blocks_reset(z->state->blocks, z, Z_NULL); - Tracev(("inflate: reset\n")); - return Z_OK; -} -#endif - -#ifndef __APPLE__ -int inflateEnd(z_streamp z) -{ - if (z == Z_NULL || z->state == Z_NULL || z->zfree == Z_NULL) - return Z_STREAM_ERROR; - if (z->state->blocks != Z_NULL) - inflate_blocks_free(z->state->blocks, z); - ZFREE(z, z->state); - z->state = Z_NULL; - Tracev(("inflate: end\n")); - return Z_OK; -} -#endif - -#ifndef __APPLE__ -int inflateInit2_(z_streamp z, int w, const char *version, int stream_size) -{ - if (version == Z_NULL || version[0] != ZLIB_VERSION[0] || - stream_size != sizeof(z_stream)) - return Z_VERSION_ERROR; - - /* initialize state */ - if (z == Z_NULL) - return Z_STREAM_ERROR; - z->msg = Z_NULL; - if (z->zalloc == Z_NULL) - { - z->zalloc = (void *(*)(void *, unsigned, unsigned))zcalloc; - z->opaque = (voidp)0; - } - if (z->zfree == Z_NULL) z->zfree = (void (*)(void *, void *))zcfree; - if ((z->state = (struct internal_state *) - ZALLOC(z,1,sizeof(struct internal_state))) == Z_NULL) - return Z_MEM_ERROR; - z->state->blocks = Z_NULL; - - /* handle undocumented nowrap option (no zlib header or check) */ - z->state->nowrap = 0; - if (w < 0) - { - w = - w; - z->state->nowrap = 1; - } - - /* set window size */ - if (w < 8 || w > 15) - { - inflateEnd(z); - return Z_STREAM_ERROR; - } - z->state->wbits = (uInt)w; - - /* create inflate_blocks state */ - if ((z->state->blocks = - inflate_blocks_new(z, z->state->nowrap ? Z_NULL : adler32, (uInt)1 << w)) - == Z_NULL) - { - inflateEnd(z); - return Z_MEM_ERROR; - } - Tracev(("inflate: allocated\n")); - - /* reset state */ - inflateReset(z); - return Z_OK; -} -#endif - -#ifndef __APPLE__ -int inflateInit_(z_streamp z, const char *version, int stream_size) -{ - return inflateInit2_(z, DEF_WBITS, version, stream_size); -} -#endif - -#define iNEEDBYTE {if(z->avail_in==0)return r;r=f;} -#define iNEXTBYTE (z->avail_in--,z->total_in++,*z->next_in++) - -#ifndef __APPLE__ -int inflate(z_streamp z, int f) -{ - int r; - uInt b; - - if (z == Z_NULL || z->state == Z_NULL || z->next_in == Z_NULL) - return Z_STREAM_ERROR; - f = f == Z_FINISH ? Z_BUF_ERROR : Z_OK; - r = Z_BUF_ERROR; - while (1) switch (z->state->mode) - { - case imMETHOD: - iNEEDBYTE - if (((z->state->sub.method = iNEXTBYTE) & 0xf) != Z_DEFLATED) - { - z->state->mode = imBAD; - z->msg = (char*)"unknown compression method"; - z->state->sub.marker = 5; /* can't try inflateSync */ - break; - } - if ((z->state->sub.method >> 4) + 8 > z->state->wbits) - { - z->state->mode = imBAD; - z->msg = (char*)"invalid window size"; - z->state->sub.marker = 5; /* can't try inflateSync */ - break; - } - z->state->mode = imFLAG; - case imFLAG: - iNEEDBYTE - b = iNEXTBYTE; - if (((z->state->sub.method << 8) + b) % 31) - { - z->state->mode = imBAD; - z->msg = (char*)"incorrect header check"; - z->state->sub.marker = 5; /* can't try inflateSync */ - break; - } - Tracev(("inflate: zlib header ok\n")); - if (!(b & PRESET_DICT)) - { - z->state->mode = imBLOCKS; - break; - } - z->state->mode = imDICT4; - case imDICT4: - iNEEDBYTE - z->state->sub.check.need = (uLong)iNEXTBYTE << 24; - z->state->mode = imDICT3; - case imDICT3: - iNEEDBYTE - z->state->sub.check.need += (uLong)iNEXTBYTE << 16; - z->state->mode = imDICT2; - case imDICT2: - iNEEDBYTE - z->state->sub.check.need += (uLong)iNEXTBYTE << 8; - z->state->mode = imDICT1; - case imDICT1: - iNEEDBYTE - z->state->sub.check.need += (uLong)iNEXTBYTE; - z->adler = z->state->sub.check.need; - z->state->mode = imDICT0; - return Z_NEED_DICT; - case imDICT0: - z->state->mode = imBAD; - z->msg = (char*)"need dictionary"; - z->state->sub.marker = 0; /* can try inflateSync */ - return Z_STREAM_ERROR; - case imBLOCKS: - r = inflate_blocks(z->state->blocks, z, r); - if (r == Z_DATA_ERROR) - { - z->state->mode = imBAD; - z->state->sub.marker = 0; /* can try inflateSync */ - break; - } - if (r == Z_OK) - r = f; - if (r != Z_STREAM_END) - return r; - r = f; - inflate_blocks_reset(z->state->blocks, z, &z->state->sub.check.was); - if (z->state->nowrap) - { - z->state->mode = imDONE; - break; - } - z->state->mode = imCHECK4; - case imCHECK4: - iNEEDBYTE - z->state->sub.check.need = (uLong)iNEXTBYTE << 24; - z->state->mode = imCHECK3; - case imCHECK3: - iNEEDBYTE - z->state->sub.check.need += (uLong)iNEXTBYTE << 16; - z->state->mode = imCHECK2; - case imCHECK2: - iNEEDBYTE - z->state->sub.check.need += (uLong)iNEXTBYTE << 8; - z->state->mode = imCHECK1; - case imCHECK1: - iNEEDBYTE - z->state->sub.check.need += (uLong)iNEXTBYTE; - - if (z->state->sub.check.was != z->state->sub.check.need) - { - z->state->mode = imBAD; - z->msg = (char*)"incorrect data check"; - z->state->sub.marker = 5; /* can't try inflateSync */ - break; - } - Tracev(("inflate: zlib check ok\n")); - z->state->mode = imDONE; - case imDONE: - return Z_STREAM_END; - case imBAD: - return Z_DATA_ERROR; - default: - return Z_STREAM_ERROR; - } -#ifdef NEED_DUMMY_RETURN - return Z_STREAM_ERROR; /* Some dumb compilers complain without this */ -#endif -} -#endif - -#ifndef __APPLE__ -int inflateSetDictionary(z_streamp z, const Byte *dictionary, uInt dictLength) -{ - uInt length = dictLength; - - if (z == Z_NULL || z->state == Z_NULL || z->state->mode != imDICT0) - return Z_STREAM_ERROR; - - if (adler32(1L, dictionary, dictLength) != z->adler) return Z_DATA_ERROR; - z->adler = 1L; - - if (length >= ((uInt)1<state->wbits)) - { - length = (1<state->wbits)-1; - dictionary += dictLength - length; - } - inflate_set_dictionary(z->state->blocks, dictionary, length); - z->state->mode = imBLOCKS; - return Z_OK; -} -#endif - -#ifndef __APPLE__ -int inflateSync(z_streamp z) -{ - uInt n; /* number of bytes to look at */ - Byte *p; /* pointer to bytes */ - uInt m; /* number of marker bytes found in a row */ - uLong r, w; /* temporaries to save total_in and total_out */ - - /* set up */ - if (z == Z_NULL || z->state == Z_NULL) - return Z_STREAM_ERROR; - if (z->state->mode != imBAD) - { - z->state->mode = imBAD; - z->state->sub.marker = 0; - } - if ((n = z->avail_in) == 0) - return Z_BUF_ERROR; - p = z->next_in; - m = z->state->sub.marker; - - /* search */ - while (n && m < 4) - { - static const Byte mark[4] = {0, 0, 0xff, 0xff}; - if (*p == mark[m]) - m++; - else if (*p) - m = 0; - else - m = 4 - m; - p++, n--; - } - - /* restore */ - z->total_in += p - z->next_in; - z->next_in = p; - z->avail_in = n; - z->state->sub.marker = m; - - /* return no joy or set up to restart on a new block */ - if (m != 4) - return Z_DATA_ERROR; - r = z->total_in; w = z->total_out; - inflateReset(z); - z->total_in = r; z->total_out = w; - z->state->mode = imBLOCKS; - return Z_OK; -} -#endif - -/* Returns true if inflate is currently at the end of a block generated - * by Z_SYNC_FLUSH or Z_FULL_FLUSH. This function is used by one PPP - * implementation to provide an additional safety check. PPP uses Z_SYNC_FLUSH - * but removes the length bytes of the resulting empty stored block. When - * decompressing, PPP checks that at the end of input packet, inflate is - * waiting for these length bytes. - */ -#ifndef __APPLE__ -int inflateSyncPoint(z_streamp z) -{ - if (z == Z_NULL || z->state == Z_NULL || z->state->blocks == Z_NULL) - return Z_STREAM_ERROR; - return inflate_blocks_sync_point(z->state->blocks); -} -#endif - -#ifndef __APPLE__ -voidp zcalloc (voidp opaque, unsigned items, unsigned size) -{ - if (opaque) items += size - size; /* make compiler happy */ - return (voidp)safe_malloc(items*size); -} - -void zcfree (voidp opaque, voidp ptr) -{ - free(ptr); - if (opaque) return; /* make compiler happy */ -} -#endif diff --git a/tools/urt/tools/quake3/common/unzip.h b/tools/urt/tools/quake3/common/unzip.h deleted file mode 100644 index 73044e7..0000000 --- a/tools/urt/tools/quake3/common/unzip.h +++ /dev/null @@ -1,321 +0,0 @@ -/* - Copyright (C) 1999-2007 id Software, Inc. and contributors. - For a list of contributors, see the accompanying CONTRIBUTORS file. - - This file is part of GtkRadiant. - - GtkRadiant is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - GtkRadiant is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with GtkRadiant; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - - -#if defined(STRICTUNZIP) || defined(STRICTZIPUNZIP) -/* like the STRICT of WIN32, we define a pointer that cannot be converted - from (void*) without cast */ -typedef struct TagunzFile__ { int unused; } unzFile__; -typedef unzFile__ *unzFile; -#else -typedef void* unzFile; -#endif - - -/* tm_unz contain date/time info */ -typedef struct tm_unz_s -{ - unsigned int tm_sec; /* seconds after the minute - [0,59] */ - unsigned int tm_min; /* minutes after the hour - [0,59] */ - unsigned int tm_hour; /* hours since midnight - [0,23] */ - unsigned int tm_mday; /* day of the month - [1,31] */ - unsigned int tm_mon; /* months since January - [0,11] */ - unsigned int tm_year; /* years - [1980..2044] */ -} tm_unz; - -/* unz_global_info structure contain global data about the ZIPfile - These data comes from the end of central dir */ -typedef struct unz_global_info_s -{ - unsigned long number_entry; /* total number of entries in the central dir on this disk */ - unsigned long size_comment; /* size of the global comment of the zipfile */ -} unz_global_info; - - -/* unz_file_info contain information about a file in the zipfile */ -typedef struct unz_file_info_s -{ - unsigned long version; /* version made by 2 unsigned chars */ - unsigned long version_needed; /* version needed to extract 2 unsigned chars */ - unsigned long flag; /* general purpose bit flag 2 unsigned chars */ - unsigned long compression_method; /* compression method 2 unsigned chars */ - unsigned long dosDate; /* last mod file date in Dos fmt 4 unsigned chars */ - unsigned long crc; /* crc-32 4 unsigned chars */ - unsigned long compressed_size; /* compressed size 4 unsigned chars */ - unsigned long uncompressed_size; /* uncompressed size 4 unsigned chars */ - unsigned long size_filename; /* filename length 2 unsigned chars */ - unsigned long size_file_extra; /* extra field length 2 unsigned chars */ - unsigned long size_file_comment; /* file comment length 2 unsigned chars */ - - unsigned long disk_num_start; /* disk number start 2 unsigned chars */ - unsigned long internal_fa; /* internal file attributes 2 unsigned chars */ - unsigned long external_fa; /* external file attributes 4 unsigned chars */ - - tm_unz tmu_date; -} unz_file_info; - -/* unz_file_info_interntal contain internal info about a file in zipfile*/ -typedef struct unz_file_info_internal_s -{ - unsigned long offset_curfile;/* relative offset of static header 4 unsigned chars */ -} unz_file_info_internal; - -typedef void* (*alloc_func) (void* opaque, unsigned int items, unsigned int size); -typedef void (*free_func) (void* opaque, void* address); - -struct internal_state; - -typedef struct z_stream_s { - unsigned char *next_in; /* next input unsigned char */ - unsigned int avail_in; /* number of unsigned chars available at next_in */ - unsigned long total_in; /* total nb of input unsigned chars read so */ - - unsigned char *next_out; /* next output unsigned char should be put there */ - unsigned int avail_out; /* remaining free space at next_out */ - unsigned long total_out; /* total nb of unsigned chars output so */ - - char *msg; /* last error message, NULL if no error */ - struct internal_state *state; /* not visible by applications */ - - alloc_func zalloc; /* used to allocate the internal state */ - free_func zfree; /* used to free the internal state */ - unsigned char* opaque; /* private data object passed to zalloc and zfree */ - - int data_type; /* best guess about the data type: ascii or binary */ - unsigned long adler; /* adler32 value of the uncompressed data */ - unsigned long reserved; /* reserved for future use */ -} z_stream; - -typedef z_stream *z_streamp; - - -/* file_in_zip_read_info_s contain internal information about a file in zipfile, - when reading and decompress it */ -typedef struct -{ - char *read_buffer; /* internal buffer for compressed data */ - z_stream stream; /* zLib stream structure for inflate */ - - unsigned long pos_in_zipfile; /* position in unsigned char on the zipfile, for fseek*/ - unsigned long stream_initialised; /* flag set if stream structure is initialised*/ - - unsigned long offset_local_extrafield;/* offset of the static extra field */ - unsigned int size_local_extrafield;/* size of the static extra field */ - unsigned long pos_local_extrafield; /* position in the static extra field in read*/ - - unsigned long crc32; /* crc32 of all data uncompressed */ - unsigned long crc32_wait; /* crc32 we must obtain after decompress all */ - unsigned long rest_read_compressed; /* number of unsigned char to be decompressed */ - unsigned long rest_read_uncompressed;/*number of unsigned char to be obtained after decomp*/ - FILE* file; /* io structore of the zipfile */ - unsigned long compression_method; /* compression method (0==store) */ - unsigned long byte_before_the_zipfile;/* unsigned char before the zipfile, (>0 for sfx)*/ -} file_in_zip_read_info_s; - - -/* unz_s contain internal information about the zipfile -*/ -typedef struct -{ - FILE* file; /* io structore of the zipfile */ - unz_global_info gi; /* public global information */ - unsigned long byte_before_the_zipfile;/* unsigned char before the zipfile, (>0 for sfx)*/ - unsigned long num_file; /* number of the current file in the zipfile*/ - unsigned long pos_in_central_dir; /* pos of the current file in the central dir*/ - unsigned long current_file_ok; /* flag about the usability of the current file*/ - unsigned long central_pos; /* position of the beginning of the central dir*/ - - unsigned long size_central_dir; /* size of the central directory */ - unsigned long offset_central_dir; /* offset of start of central directory with - respect to the starting disk number */ - - unz_file_info cur_file_info; /* public info about the current file in zip*/ - unz_file_info_internal cur_file_info_internal; /* private info about it*/ - file_in_zip_read_info_s* pfile_in_zip_read; /* structure about the current - file if we are decompressing it */ -} unz_s; - -#define UNZ_OK (0) -#define UNZ_END_OF_LIST_OF_FILE (-100) -#define UNZ_ERRNO (Z_ERRNO) -#define UNZ_EOF (0) -#define UNZ_PARAMERROR (-102) -#define UNZ_BADZIPFILE (-103) -#define UNZ_INTERNALERROR (-104) -#define UNZ_CRCERROR (-105) - -#define UNZ_CASESENSITIVE 1 -#define UNZ_NOTCASESENSITIVE 2 -#define UNZ_OSDEFAULTCASE 0 - -extern int unzStringFileNameCompare (const char* fileName1, const char* fileName2, int iCaseSensitivity); - -/* - Compare two filename (fileName1,fileName2). - If iCaseSenisivity = 1, comparision is case sensitivity (like strcmp) - If iCaseSenisivity = 2, comparision is not case sensitivity (like strcmpi - or strcasecmp) - If iCaseSenisivity = 0, case sensitivity is defaut of your operating system - (like 1 on Unix, 2 on Windows) -*/ - -extern unzFile unzOpen (const char *path); -extern unzFile unzReOpen (const char* path, unzFile file); - -/* - Open a Zip file. path contain the full pathname (by example, - on a Windows NT computer "c:\\zlib\\zlib111.zip" or on an Unix computer - "zlib/zlib111.zip". - If the zipfile cannot be opened (file don't exist or in not valid), the - return value is NULL. - Else, the return value is a unzFile Handle, usable with other function - of this unzip package. -*/ - -extern int unzClose (unzFile file); - -/* - Close a ZipFile opened with unzipOpen. - If there is files inside the .Zip opened with unzOpenCurrentFile (see later), - these files MUST be closed with unzipCloseCurrentFile before call unzipClose. - return UNZ_OK if there is no problem. */ - -extern int unzGetGlobalInfo (unzFile file, unz_global_info *pglobal_info); - -/* - Write info about the ZipFile in the *pglobal_info structure. - No preparation of the structure is needed - return UNZ_OK if there is no problem. */ - - -extern int unzGetGlobalComment (unzFile file, char *szComment, unsigned long uSizeBuf); - -/* - Get the global comment string of the ZipFile, in the szComment buffer. - uSizeBuf is the size of the szComment buffer. - return the number of unsigned char copied or an error code <0 -*/ - - -/***************************************************************************/ -/* Unzip package allow you browse the directory of the zipfile */ - -extern int unzGoToFirstFile (unzFile file); - -/* - Set the current file of the zipfile to the first file. - return UNZ_OK if there is no problem -*/ - -extern int unzGoToNextFile (unzFile file); - -/* - Set the current file of the zipfile to the next file. - return UNZ_OK if there is no problem - return UNZ_END_OF_LIST_OF_FILE if the actual file was the latest. -*/ - -extern int unzLocateFile (unzFile file, const char *szFileName, int iCaseSensitivity); - -/* - Try locate the file szFileName in the zipfile. - For the iCaseSensitivity signification, see unzStringFileNameCompare - - return value : - UNZ_OK if the file is found. It becomes the current file. - UNZ_END_OF_LIST_OF_FILE if the file is not found -*/ - - -extern int unzGetCurrentFileInfo (unzFile file, unz_file_info *pfile_info, char *szFileName, unsigned long fileNameBufferSize, void *extraField, unsigned long extraFieldBufferSize, char *szComment, unsigned long commentBufferSize); - -/* - Get Info about the current file - if pfile_info!=NULL, the *pfile_info structure will contain somes info about - the current file - if szFileName!=NULL, the filemane string will be copied in szFileName - (fileNameBufferSize is the size of the buffer) - if extraField!=NULL, the extra field information will be copied in extraField - (extraFieldBufferSize is the size of the buffer). - This is the Central-header version of the extra field - if szComment!=NULL, the comment string of the file will be copied in szComment - (commentBufferSize is the size of the buffer) -*/ - -/***************************************************************************/ -/* for reading the content of the current zipfile, you can open it, read data - from it, and close it (you can close it before reading all the file) - */ - -extern int unzOpenCurrentFile (unzFile file); - -/* - Open for reading data the current file in the zipfile. - If there is no error, the return value is UNZ_OK. -*/ - -extern int unzCloseCurrentFile (unzFile file); - -/* - Close the file in zip opened with unzOpenCurrentFile - Return UNZ_CRCERROR if all the file was read but the CRC is not good -*/ - - -extern int unzReadCurrentFile (unzFile file, void* buf, unsigned len); - -/* - Read unsigned chars from the current file (opened by unzOpenCurrentFile) - buf contain buffer where data must be copied - len the size of buf. - - return the number of unsigned char copied if somes unsigned chars are copied - return 0 if the end of file was reached - return <0 with error code if there is an error - (UNZ_ERRNO for IO error, or zLib error for uncompress error) -*/ - -extern long unztell(unzFile file); - -/* - Give the current position in uncompressed data -*/ - -extern int unzeof (unzFile file); - -/* - return 1 if the end of file was reached, 0 elsewhere -*/ - -extern int unzGetLocalExtrafield (unzFile file, void* buf, unsigned len); - -/* - Read extra field from the current file (opened by unzOpenCurrentFile) - This is the local-header version of the extra field (sometimes, there is - more info in the local-header version than in the central-header) - - if buf==NULL, it return the size of the local extra field - - if buf!=NULL, len is the size of the buffer, the extra header is copied in - buf. - the return value is the number of unsigned chars copied in buf, or (if <0) - the error code -*/ diff --git a/tools/urt/tools/quake3/common/vfs.c b/tools/urt/tools/quake3/common/vfs.c deleted file mode 100644 index 04af830..0000000 --- a/tools/urt/tools/quake3/common/vfs.c +++ /dev/null @@ -1,370 +0,0 @@ -/* - Copyright (c) 2001, Loki software, inc. - All rights reserved. - - Redistribution and use in source and binary forms, with or without modification, - are permitted provided that the following conditions are met: - - Redistributions of source code must retain the above copyright notice, this list - of conditions and the following disclaimer. - - Redistributions in binary form must reproduce the above copyright notice, this - list of conditions and the following disclaimer in the documentation and/or - other materials provided with the distribution. - - Neither the name of Loki software nor the names of its contributors may be used - to endorse or promote products derived from this software without specific prior - written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' - AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY - DIRECT,INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -// -// Rules: -// -// - Directories should be searched in the following order: ~/.q3a/baseq3, -// install dir (/usr/local/games/quake3/baseq3) and cd_path (/mnt/cdrom/baseq3). -// -// - Pak files are searched first inside the directories. -// - Case insensitive. -// - Unix-style slashes (/) (windows is backwards .. everyone knows that) -// -// Leonardo Zide (leo@lokigames.com) -// - -#include - -#if defined ( __linux__ ) || defined ( __APPLE__ ) -#include -#include -#else -#include -#include -#define R_OK 04 -#define S_ISDIR( mode ) ( mode & _S_IFDIR ) -#define PATH_MAX 260 -#endif - -#include -#include -#include - -#include "cmdlib.h" -#include "mathlib.h" -#include -#include "inout.h" -#include "vfs.h" -#include "unzip.h" - -typedef struct -{ - char* name; - unz_s zipinfo; - unzFile zipfile; - guint32 size; -} VFS_PAKFILE; - -// ============================================================================= -// Global variables - -static GSList* g_unzFiles; -static GSList* g_pakFiles; -static char g_strDirs[VFS_MAXDIRS][PATH_MAX]; -static int g_numDirs; -static gboolean g_bUsePak = TRUE; - -// ============================================================================= -// Static functions - -static void vfsAddSlash( char *str ){ - int n = strlen( str ); - if ( n > 0 ) { - if ( str[n - 1] != '\\' && str[n - 1] != '/' ) { - strcat( str, "/" ); - } - } -} - -static void vfsFixDOSName( char *src ){ - if ( src == NULL ) { - return; - } - - while ( *src ) - { - if ( *src == '\\' ) { - *src = '/'; - } - src++; - } -} - -//!\todo Define globally or use heap-allocated string. -#define NAME_MAX 255 - -static void vfsInitPakFile( const char *filename ){ - unz_global_info gi; - unzFile uf; - guint32 i; - int err; - - uf = unzOpen( filename ); - if ( uf == NULL ) { - return; - } - - g_unzFiles = g_slist_append( g_unzFiles, uf ); - - err = unzGetGlobalInfo( uf,&gi ); - if ( err != UNZ_OK ) { - return; - } - unzGoToFirstFile( uf ); - - for ( i = 0; i < gi.number_entry; i++ ) - { - char filename_inzip[NAME_MAX]; - unz_file_info file_info; - VFS_PAKFILE* file; - - err = unzGetCurrentFileInfo( uf, &file_info, filename_inzip, sizeof( filename_inzip ), NULL, 0, NULL, 0 ); - if ( err != UNZ_OK ) { - break; - } - - file = (VFS_PAKFILE*)safe_malloc( sizeof( VFS_PAKFILE ) ); - g_pakFiles = g_slist_append( g_pakFiles, file ); - - vfsFixDOSName( filename_inzip ); - g_strdown( filename_inzip ); - - file->name = strdup( filename_inzip ); - file->size = file_info.uncompressed_size; - file->zipfile = uf; - memcpy( &file->zipinfo, uf, sizeof( unz_s ) ); - - if ( ( i + 1 ) < gi.number_entry ) { - err = unzGoToNextFile( uf ); - if ( err != UNZ_OK ) { - break; - } - } - } -} - -// ============================================================================= -// Global functions - -// reads all pak files from a dir -void vfsInitDirectory( const char *path ){ - char filename[PATH_MAX]; - char *dirlist; - GDir *dir; - - if ( g_numDirs == ( VFS_MAXDIRS - 1 ) ) { - return; - } - - Sys_Printf( "VFS Init: %s\n", path ); - - strcpy( g_strDirs[g_numDirs], path ); - vfsFixDOSName( g_strDirs[g_numDirs] ); - vfsAddSlash( g_strDirs[g_numDirs] ); - g_numDirs++; - - if ( g_bUsePak ) { - dir = g_dir_open( path, 0, NULL ); - - if ( dir != NULL ) { - while ( 1 ) - { - const char* name = g_dir_read_name( dir ); - if ( name == NULL ) { - break; - } - - dirlist = g_strdup( name ); - - { - char *ext = strrchr( dirlist, '.' ); - if ( ( ext == NULL ) || ( Q_stricmp( ext, ".pk3" ) != 0 ) ) { - continue; - } - } - - sprintf( filename, "%s/%s", path, dirlist ); - vfsInitPakFile( filename ); - - g_free( dirlist ); - } - g_dir_close( dir ); - } - } -} - -// frees all memory that we allocated -void vfsShutdown(){ - while ( g_unzFiles ) - { - unzClose( (unzFile)g_unzFiles->data ); - g_unzFiles = g_slist_remove( g_unzFiles, g_unzFiles->data ); - } - - while ( g_pakFiles ) - { - VFS_PAKFILE* file = (VFS_PAKFILE*)g_pakFiles->data; - free( file->name ); - free( file ); - g_pakFiles = g_slist_remove( g_pakFiles, file ); - } -} - -// return the number of files that match -int vfsGetFileCount( const char *filename ){ - int i, count = 0; - char fixed[NAME_MAX], tmp[NAME_MAX]; - GSList *lst; - - strcpy( fixed, filename ); - vfsFixDOSName( fixed ); - g_strdown( fixed ); - - for ( lst = g_pakFiles; lst != NULL; lst = g_slist_next( lst ) ) - { - VFS_PAKFILE* file = (VFS_PAKFILE*)lst->data; - - if ( strcmp( file->name, fixed ) == 0 ) { - count++; - } - } - - for ( i = 0; i < g_numDirs; i++ ) - { - strcpy( tmp, g_strDirs[i] ); - strcat( tmp, fixed ); - if ( access( tmp, R_OK ) == 0 ) { - count++; - } - } - - return count; -} - -// NOTE: when loading a file, you have to allocate one extra byte and set it to \0 -int vfsLoadFile( const char *filename, void **bufferptr, int index ){ - int i, count = 0; - char tmp[NAME_MAX], fixed[NAME_MAX]; - GSList *lst; - - // filename is a full path - if ( index == -1 ) { - long len; - FILE *f; - - f = fopen( filename, "rb" ); - if ( f == NULL ) { - return -1; - } - - fseek( f, 0, SEEK_END ); - len = ftell( f ); - rewind( f ); - - *bufferptr = safe_malloc( len + 1 ); - if ( *bufferptr == NULL ) { - return -1; - } - - fread( *bufferptr, 1, len, f ); - fclose( f ); - - // we need to end the buffer with a 0 - ( (char*) ( *bufferptr ) )[len] = 0; - - return len; - } - - *bufferptr = NULL; - strcpy( fixed, filename ); - vfsFixDOSName( fixed ); - g_strdown( fixed ); - - for ( i = 0; i < g_numDirs; i++ ) - { - strcpy( tmp, g_strDirs[i] ); - strcat( tmp, filename ); - if ( access( tmp, R_OK ) == 0 ) { - if ( count == index ) { - long len; - FILE *f; - - f = fopen( tmp, "rb" ); - if ( f == NULL ) { - return -1; - } - - fseek( f, 0, SEEK_END ); - len = ftell( f ); - rewind( f ); - - *bufferptr = safe_malloc( len + 1 ); - if ( *bufferptr == NULL ) { - return -1; - } - - fread( *bufferptr, 1, len, f ); - fclose( f ); - - // we need to end the buffer with a 0 - ( (char*) ( *bufferptr ) )[len] = 0; - - return len; - } - - count++; - } - } - - for ( lst = g_pakFiles; lst != NULL; lst = g_slist_next( lst ) ) - { - VFS_PAKFILE* file = (VFS_PAKFILE*)lst->data; - - if ( strcmp( file->name, fixed ) != 0 ) { - continue; - } - - if ( count == index ) { - memcpy( file->zipfile, &file->zipinfo, sizeof( unz_s ) ); - - if ( unzOpenCurrentFile( file->zipfile ) != UNZ_OK ) { - return -1; - } - - *bufferptr = safe_malloc( file->size + 1 ); - // we need to end the buffer with a 0 - ( (char*) ( *bufferptr ) )[file->size] = 0; - - i = unzReadCurrentFile( file->zipfile, *bufferptr, file->size ); - unzCloseCurrentFile( file->zipfile ); - if ( i < 0 ) { - return -1; - } - else{ - return file->size; - } - } - - count++; - } - - return -1; -} diff --git a/tools/urt/tools/quake3/common/vfs.h b/tools/urt/tools/quake3/common/vfs.h deleted file mode 100644 index ca41a29..0000000 --- a/tools/urt/tools/quake3/common/vfs.h +++ /dev/null @@ -1,41 +0,0 @@ -/* - Copyright (c) 2001, Loki software, inc. - All rights reserved. - - Redistribution and use in source and binary forms, with or without modification, - are permitted provided that the following conditions are met: - - Redistributions of source code must retain the above copyright notice, this list - of conditions and the following disclaimer. - - Redistributions in binary form must reproduce the above copyright notice, this - list of conditions and the following disclaimer in the documentation and/or - other materials provided with the distribution. - - Neither the name of Loki software nor the names of its contributors may be used - to endorse or promote products derived from this software without specific prior - written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' - AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY - DIRECT,INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef _VFS_H_ -#define _VFS_H_ - -#define VFS_MAXDIRS 8 - -void vfsInitDirectory( const char *path ); -void vfsShutdown(); -int vfsGetFileCount( const char *filename ); -int vfsLoadFile( const char *filename, void **buffer, int index ); - -#endif // _VFS_H_ diff --git a/tools/urt/tools/quake3/q3data/3dslib.c b/tools/urt/tools/quake3/q3data/3dslib.c deleted file mode 100644 index d034122..0000000 --- a/tools/urt/tools/quake3/q3data/3dslib.c +++ /dev/null @@ -1,640 +0,0 @@ -#include -#include "q3data.h" - -static void Load3DS( const char *filename, _3DS_t *p3DS, qboolean verbose ); - -static qboolean s_verbose; - -#define MAX_MATERIALS 100 -#define MAX_NAMED_OBJECTS 100 -#define MAX_MESH_MATERIAL_GROUPS 100 -#define MAX_TRI_OBJECTS 512 - -static char s_buffer[1000000]; - -static int ReadString( FILE *fp, char *buffer ){ - int i = 0; - int bytesRead = 0; - - do - { - fread( &buffer[i], 1, sizeof( char ), fp ); - bytesRead++; - } while ( buffer[i++] != 0 ); - buffer[i] = 0; - - return bytesRead; -} - -static int ReadChunkAndLength( FILE *fp, short *chunk, long *len ){ - if ( fread( chunk, sizeof( short ), 1, fp ) != 1 ) { - return 0; - } - if ( fread( len, sizeof( long ), 1, fp ) != 1 ) { - Error( "Unexpected EOF found" ); - } - return 1; -} - -static void LoadMapName( FILE *fp, char *buffer, int thisChunkLen ){ - unsigned short chunkID; - long chunkLen; - long bytesRead = 0; - - while ( ReadChunkAndLength( fp, &chunkID, &chunkLen ) ) - { - switch ( chunkID ) - { - case _3DS_CHUNK_MAT_MAPNAME: - fread( buffer, chunkLen - 6, 1, fp ); - break; - default: - fread( s_buffer, chunkLen - 6, 1, fp ); - break; - } - bytesRead += chunkLen; - if ( bytesRead >= thisChunkLen ) { - return; - } - } -} - -static void LoadMaterialList( FILE *fp, long thisChunkLen, _3DSMaterial_t *pMat ){ - long chunkLen; - unsigned short chunkID; - long bytesRead = 0; - _3DSMaterial_t mat; - char curdir[1024]; - char buffer[2048]; - - memset( &mat, 0, sizeof( mat ) ); - - if ( s_verbose ) { - printf( " >>> MATERIAL LIST\n" ); - } - - while ( ReadChunkAndLength( fp, &chunkID, &chunkLen ) ) - { - switch ( chunkID ) - { - case _3DS_CHUNK_MAT_NAME: - fread( mat.name, chunkLen - 6, 1, fp ); - if ( s_verbose ) { - printf( " found mat name '%s'\n", mat.name ); - } - break; - case _3DS_CHUNK_TEXMAP: - LoadMapName( fp, mat.texture, chunkLen - 6 ); - if ( s_verbose ) { - printf( " found texture '%s'\n", mat.texture ); - } - break; - case _3DS_CHUNK_SPECMAP: - LoadMapName( fp, mat.specular, chunkLen - 6 ); - if ( s_verbose ) { - printf( " found specular map '%s'\n", mat.specular ); - } - break; - case _3DS_CHUNK_OPACMAP: - LoadMapName( fp, mat.opacity, chunkLen - 6 ); - if ( s_verbose ) { - printf( " found opacity map '%s'\n", mat.opacity ); - } - break; - case _3DS_CHUNK_REFLMAP: - LoadMapName( fp, mat.reflection, chunkLen - 6 ); - if ( s_verbose ) { - printf( " found reflection map '%s'\n", mat.reflection ); - } - break; - case _3DS_CHUNK_BUMPMAP: - LoadMapName( fp, mat.bump, chunkLen - 6 ); - if ( s_verbose ) { - printf( " found bump map '%s'\n", mat.bump ); - } - break; - default: - fread( s_buffer, chunkLen - 6, 1, fp ); - break; - } - - bytesRead += chunkLen; - - if ( bytesRead >= thisChunkLen ) { - break; - } - } - - Q_getwd( curdir ); - - if ( mat.texture[0] ) { - sprintf( buffer, "%s%s", curdir, mat.texture ); - if ( strstr( buffer, gamedir + 1 ) ) { - strcpy( mat.texture, strstr( buffer, gamedir + 1 ) + strlen( gamedir ) - 1 ); - } - else{ - strcpy( mat.texture, buffer ); - } - } - - if ( mat.specular[0] ) { - sprintf( buffer, "%s%s", curdir, mat.specular ); - if ( strstr( buffer, gamedir + 1 ) ) { - strcpy( mat.specular, strstr( buffer, gamedir + 1 ) + strlen( gamedir ) - 1 ); - } - else{ - strcpy( mat.specular, buffer ); - } - } - - if ( mat.bump[0] ) { - sprintf( buffer, "%s%s", curdir, mat.bump ); - if ( strstr( buffer, gamedir + 1 ) ) { - strcpy( mat.bump, strstr( buffer, gamedir + 1 ) + strlen( gamedir ) - 1 ); - } - else{ - strcpy( mat.bump, buffer ); - } - } - - if ( mat.reflection[0] ) { - sprintf( buffer, "%s%s", curdir, mat.reflection ); - if ( strstr( buffer, gamedir + 1 ) ) { - strcpy( mat.reflection, strstr( buffer, gamedir + 1 ) + strlen( gamedir ) - 1 ); - } - else{ - strcpy( mat.reflection, buffer ); - } - } - - if ( mat.opacity[0] ) { - sprintf( buffer, "%s%s", curdir, mat.opacity ); - if ( strstr( buffer, gamedir + 1 ) ) { - strcpy( mat.opacity, strstr( buffer, gamedir + 1 ) + strlen( gamedir ) - 1 ); - } - else{ - strcpy( mat.opacity, buffer ); - } - } - - *pMat = mat; -} - -static void LoadMeshMaterialGroup( FILE *fp, long thisChunkLen, _3DSMeshMaterialGroup_t *pMMG ){ - _3DSMeshMaterialGroup_t mmg; - - memset( &mmg, 0, sizeof( mmg ) ); - - ReadString( fp, mmg.name ); - - fread( &mmg.numFaces, sizeof( mmg.numFaces ), 1, fp ); - mmg.pFaces = malloc( sizeof( mmg.pFaces[0] ) * mmg.numFaces ); - fread( mmg.pFaces, sizeof( mmg.pFaces[0] ), mmg.numFaces, fp ); - - if ( s_verbose ) { - printf( " >>> MESH MATERIAL GROUP '%s' (%d faces)\n", mmg.name, mmg.numFaces ); - - { - int i; - - for ( i = 0; i < mmg.numFaces; i++ ) - { - printf( " %d\n", mmg.pFaces[i] ); - } - } - } - - *pMMG = mmg; -} - -static void LoadNamedTriObject( FILE *fp, long thisChunkLen, _3DSTriObject_t *pTO ){ - long chunkLen; - unsigned short chunkID; - int i = 0; - long bytesRead = 0; - _3DSTriObject_t triObj; - _3DSMeshMaterialGroup_t meshMaterialGroups[MAX_MESH_MATERIAL_GROUPS]; - int numMeshMaterialGroups = 0; - - memset( &triObj, 0, sizeof( triObj ) ); - - if ( s_verbose ) { - printf( " >>> NAMED TRI OBJECT\n" ); - } - - while ( ReadChunkAndLength( fp, &chunkID, &chunkLen ) ) - { - switch ( chunkID ) - { - case _3DS_CHUNK_MSH_MAT_GROUP: - LoadMeshMaterialGroup( fp, chunkLen - 6, &meshMaterialGroups[numMeshMaterialGroups] ); - bytesRead += chunkLen; - numMeshMaterialGroups++; - break; - case _3DS_CHUNK_FACE_ARRAY: - fread( &triObj.numFaces, sizeof( triObj.numFaces ), 1, fp ); - assert( triObj.pFaces == 0 ); - - triObj.pFaces = malloc( sizeof( triObj.pFaces[0] ) * triObj.numFaces ); - fread( triObj.pFaces, sizeof( triObj.pFaces[0] ), triObj.numFaces, fp ); - bytesRead += sizeof( triObj.numFaces ) + triObj.numFaces * sizeof( triObj.pFaces[0] ) + 6; - - if ( s_verbose ) { - printf( " found face array with %d faces\n", triObj.numFaces ); - for ( i = 0; i < triObj.numFaces; i++ ) - { - printf( " %d: %d,%d,%d\n", i, triObj.pFaces[i].a, triObj.pFaces[i].b, triObj.pFaces[i].c ); - } - } - - break; - case _3DS_CHUNK_POINT_ARRAY: - fread( &triObj.numPoints, sizeof( triObj.numPoints ), 1, fp ); - triObj.pPoints = malloc( sizeof( triObj.pPoints[0] ) * triObj.numPoints ); - fread( triObj.pPoints, sizeof( triObj.pPoints[0] ), triObj.numPoints, fp ); - bytesRead += sizeof( triObj.numPoints ) + triObj.numPoints * sizeof( triObj.pPoints[0] ) + 6; - - // flip points around into our coordinate system - for ( i = 0; i < triObj.numPoints; i++ ) - { - float x, y, z; - - x = triObj.pPoints[i].x; - y = triObj.pPoints[i].y; - z = triObj.pPoints[i].z; - - triObj.pPoints[i].x = -y; - triObj.pPoints[i].y = x; - triObj.pPoints[i].z = z; - } - - if ( s_verbose ) { - printf( " found point array with %d points\n", triObj.numPoints ); - for ( i = 0; i < triObj.numPoints; i++ ) - { - printf( " %d: %f,%f,%f\n", i, triObj.pPoints[i].x, triObj.pPoints[i].y, triObj.pPoints[i].z ); - } - } - break; - case _3DS_CHUNK_TEX_VERTS: - fread( &triObj.numTexVerts, sizeof( triObj.numTexVerts ), 1, fp ); - triObj.pTexVerts = malloc( sizeof( triObj.pTexVerts[0] ) * triObj.numTexVerts ); - fread( triObj.pTexVerts, sizeof( triObj.pTexVerts[0] ), triObj.numTexVerts, fp ); - bytesRead += sizeof( triObj.numTexVerts ) + sizeof( triObj.pTexVerts[0] ) * triObj.numTexVerts + 6; - - if ( s_verbose ) { - printf( " found tex vert array with %d tex verts\n", triObj.numTexVerts ); - for ( i = 0; i < triObj.numTexVerts; i++ ) - { - printf( " %d: %f,%f\n", i, triObj.pTexVerts[i].s, triObj.pTexVerts[i].t ); - } - } - break; - default: - fread( s_buffer, chunkLen - 6, 1, fp ); - bytesRead += chunkLen; - break; - } - - if ( bytesRead >= thisChunkLen ) { - break; - } - } - *pTO = triObj; - - if ( numMeshMaterialGroups == 0 ) { - numMeshMaterialGroups = 1; - strcpy( meshMaterialGroups[0].name, "(null)" ); - if ( pTO->numTexVerts ) { - printf( "Warning: assigning (null) skin to tri object\n" ); - } - } - else - { - assert( pTO->numFaces == meshMaterialGroups[0].numFaces ); - } - - pTO->pMeshMaterialGroups = malloc( sizeof( _3DSMeshMaterialGroup_t ) * numMeshMaterialGroups ); - memcpy( pTO->pMeshMaterialGroups, meshMaterialGroups, numMeshMaterialGroups * sizeof( meshMaterialGroups[0] ) ); - pTO->numMeshMaterialGroups = numMeshMaterialGroups; - - // - // sanity checks - // - assert( numMeshMaterialGroups <= 1 ); -} - -static void LoadNamedObject( FILE *fp, long thisChunkLen, _3DSNamedObject_t *pNO ){ - long chunkLen; - unsigned short chunkID; - int i = 0; - long bytesRead = 0; - char name[100]; - _3DSTriObject_t triObj[MAX_TRI_OBJECTS]; - int numTriObjects = 0; - - memset( triObj, 0, sizeof( triObj ) ); - - bytesRead += ReadString( fp, name ); - - if ( s_verbose ) { - printf( " >>> NAMED OBJECT '%s'\n", name ); - } - - while ( ReadChunkAndLength( fp, &chunkID, &chunkLen ) ) - { - switch ( chunkID ) - { - case _3DS_CHUNK_NAMED_TRI_OBJECT: - LoadNamedTriObject( fp, chunkLen - 6, &triObj[numTriObjects] ); - numTriObjects++; - break; - default: - fread( s_buffer, chunkLen - 6, 1, fp ); - break; - } - - bytesRead += chunkLen; - - if ( bytesRead >= thisChunkLen ) { - break; - } - } - - strcpy( pNO->name, name ); - pNO->pTriObjects = malloc( sizeof( _3DSTriObject_t ) * numTriObjects ); - memcpy( pNO->pTriObjects, triObj, sizeof( triObj[0] ) * numTriObjects ); - pNO->numTriObjects = numTriObjects; - - assert( numTriObjects <= 1 ); -} - -static void LoadEditChunk( FILE *fp, long thisChunkLen, _3DSEditChunk_t *pEC ){ - unsigned short chunkID; - long chunkLen; - long bytesRead = 0; - _3DSEditChunk_t editChunk; - - _3DSMaterial_t mat[MAX_MATERIALS]; - _3DSNamedObject_t namedObjects[MAX_NAMED_OBJECTS]; - - int numMaterials = 0, numNamedObjects = 0; - - memset( &editChunk, 0, sizeof( editChunk ) ); - - if ( s_verbose ) { - printf( ">>> EDIT CHUNK\n" ); - } - - while ( ReadChunkAndLength( fp, &chunkID, &chunkLen ) ) - { - switch ( chunkID ) - { - case _3DS_CHUNK_MAT_LIST: - LoadMaterialList( fp, chunkLen - 6, &mat[numMaterials] ); - numMaterials++; - break; - case _3DS_CHUNK_NAMED_OBJECT: - LoadNamedObject( fp, chunkLen - 6, &namedObjects[numNamedObjects] ); - if ( namedObjects[numNamedObjects].numTriObjects != 0 ) { - ++numNamedObjects; - } - break; - case _3DS_CHUNK_MESH_VERSION: - default: - fread( s_buffer, chunkLen - 6, 1, fp ); - break; - } - - bytesRead += chunkLen; - - if ( bytesRead >= thisChunkLen ) { - break; - } - } - - if ( numMaterials == 0 ) { - numMaterials = 1; - strcpy( mat[0].name, "(null)" ); - printf( "Warning: no material definitions found\n" ); - } - - pEC->numNamedObjects = numNamedObjects; - - pEC->pMaterials = malloc( sizeof( _3DSMaterial_t ) * numMaterials ); - pEC->pNamedObjects = malloc( sizeof( _3DSNamedObject_t ) * numNamedObjects ); - - memcpy( pEC->pMaterials, mat, numMaterials * sizeof( mat[0] ) ); - memcpy( pEC->pNamedObjects, namedObjects, numNamedObjects * sizeof( namedObjects[0] ) ); -} - -static void Load3DS( const char *filename, _3DS_t *p3DS, qboolean verbose ){ - FILE *fp; - unsigned short chunkID; - long chunkLen; - _3DSEditChunk_t editChunk; - - s_verbose = verbose; - - if ( ( fp = fopen( filename, "rb" ) ) == 0 ) { - Error( "Unable to open '%s'", filename ); - } - - // read magic number - if ( ( fread( &chunkID, sizeof( short ), 1, fp ) != 1 ) || - ( LittleShort( chunkID ) != _3DS_CHUNK_MAGIC ) ) { - Error( "Missing or incorrect magic number in '%s'", filename ); - } - if ( fread( &chunkLen, sizeof( chunkLen ), 1, fp ) != 1 ) { - Error( "Unexpected EOF encountered in '%s'", filename ); - } - // version number - if ( !ReadChunkAndLength( fp, &chunkID, &chunkLen ) ) { - Error( "Missing version number in '%s'", filename ); - } - if ( fread( s_buffer, chunkLen - 6, 1, fp ) != 1 ) { - Error( "Unexpected EOF encountered in '%s'", filename ); - } - - while ( ReadChunkAndLength( fp, &chunkID, &chunkLen ) ) - { - switch ( chunkID ) - { - case _3DS_CHUNK_EDIT: - LoadEditChunk( fp, chunkLen - 6, &editChunk ); - break; - case _3DS_CHUNK_KEYFRAME_DATA: - fread( s_buffer, chunkLen - 6, 1, fp ); - break; - default: - fread( s_buffer, chunkLen - 6, 1, fp ); - break; - } - } - - fclose( fp ); - - p3DS->editChunk = editChunk; -} - -static void ComputeNormals( _3DSTriObject_t *pTO, triangle_t *pTris ){ - vec3_t faceNormals[POLYSET_MAXTRIANGLES]; - vec3_t vertexNormals[POLYSET_MAXTRIANGLES * 3]; - vec3_t side0, side1, facenormal; - int f, v; - - memset( faceNormals, 0, sizeof( faceNormals ) ); - memset( vertexNormals, 0, sizeof( vertexNormals ) ); - - // - // compute face normals - // - for ( f = 0; f < pTO->numFaces; f++ ) - { - VectorSubtract( pTris[f].verts[0], pTris[f].verts[1], side0 ); - VectorSubtract( pTris[f].verts[2], pTris[f].verts[1], side1 ); - - CrossProduct( side0, side1, facenormal ); - VectorNormalize( facenormal, faceNormals[f] ); - } - - // - // sum vertex normals - // - for ( v = 0; v < pTO->numPoints; v++ ) - { - for ( f = 0; f < pTO->numFaces; f++ ) - { - if ( ( pTO->pFaces[f].a == v ) || - ( pTO->pFaces[f].b == v ) || - ( pTO->pFaces[f].c == v ) ) { - vertexNormals[v][0] += faceNormals[f][0]; - vertexNormals[v][1] += faceNormals[f][1]; - vertexNormals[v][2] += faceNormals[f][2]; - } - } - - VectorNormalize( vertexNormals[v], vertexNormals[v] ); - } - - // - // copy vertex normals into triangles - // - for ( f = 0; f < pTO->numFaces; f++ ) - { - int i0 = pTO->pFaces[f].c; - int i1 = pTO->pFaces[f].b; - int i2 = pTO->pFaces[f].a; - - VectorCopy( vertexNormals[i0], pTris[f].normals[0] ); - VectorCopy( vertexNormals[i1], pTris[f].normals[1] ); - VectorCopy( vertexNormals[i2], pTris[f].normals[2] ); - } -} - -/* -** void _3DS_LoadPolysets -*/ -void _3DS_LoadPolysets( const char *filename, polyset_t **ppPSET, int *numpsets, qboolean verbose ){ - _3DS_t _3ds; - int numPolysets; - polyset_t *pPSET; - triangle_t *ptri, *triangles; - int i; - - // load the 3DS - memset( &_3ds, 0, sizeof( _3ds ) ); - Load3DS( filename, &_3ds, verbose ); - - // compute information - numPolysets = _3ds.editChunk.numNamedObjects; - - // allocate memory - pPSET = calloc( 1, numPolysets * sizeof( polyset_t ) ); - triangles = ptri = calloc( 1, POLYSET_MAXTRIANGLES * sizeof( triangle_t ) ); - - // copy the data over - for ( i = 0; i < numPolysets; i++ ) - { - char matnamebuf[1024]; - int j; - triangle_t *tri; - _3DSTriObject_t *pTO = &_3ds.editChunk.pNamedObjects[i].pTriObjects[0]; - - pPSET[i].triangles = ptri; - pPSET[i].numtriangles = pTO->numFaces; - strcpy( pPSET[i].name, _3ds.editChunk.pNamedObjects[i].name ); - - strcpy( matnamebuf, filename ); - if ( strrchr( matnamebuf, '/' ) ) { - *( strrchr( matnamebuf, '/' ) + 1 ) = 0; - } - strcat( matnamebuf, pTO->pMeshMaterialGroups[0].name ); - - if ( strstr( matnamebuf, gamedir ) ) { - strcpy( pPSET[i].materialname, strstr( matnamebuf, gamedir ) + strlen( gamedir ) ); - } - else{ - strcpy( pPSET[i].materialname, pTO->pMeshMaterialGroups[0].name ); - } - - assert( pPSET[i].numtriangles < POLYSET_MAXTRIANGLES ); - - for ( tri = ptri, j = 0; j < pPSET[i].numtriangles; j++ ) - { - int i0 = pTO->pFaces[j].c; - int i1 = pTO->pFaces[j].b; - int i2 = pTO->pFaces[j].a; - - tri->verts[0][0] = pTO->pPoints[i0].x; - tri->verts[0][1] = pTO->pPoints[i0].y; - tri->verts[0][2] = pTO->pPoints[i0].z; - - tri->verts[1][0] = pTO->pPoints[i1].x; - tri->verts[1][1] = pTO->pPoints[i1].y; - tri->verts[1][2] = pTO->pPoints[i1].z; - - tri->verts[2][0] = pTO->pPoints[i2].x; - tri->verts[2][1] = pTO->pPoints[i2].y; - tri->verts[2][2] = pTO->pPoints[i2].z; -/* - for ( k = 0; k < 3; k++ ) - { - tri->colors[0][k] = 1; - tri->colors[1][k] = 1; - tri->colors[2][k] = 1; - } - */ - - if ( pTO->pTexVerts ) { - tri->texcoords[0][0] = pTO->pTexVerts[i0].s; - tri->texcoords[0][1] = 1.0f - pTO->pTexVerts[i0].t; - tri->texcoords[1][0] = pTO->pTexVerts[i1].s; - tri->texcoords[1][1] = 1.0f - pTO->pTexVerts[i1].t; - tri->texcoords[2][0] = pTO->pTexVerts[i2].s; - tri->texcoords[2][1] = 1.0f - pTO->pTexVerts[i2].t; - } - - tri++; - } - - ptri += pPSET[i].numtriangles; - assert( ptri - triangles < POLYSET_MAXTRIANGLES ); - } - - // compute normal data -#if 0 - for ( i = 0; i < numPolysets; i++ ) - { - // unique vertices based solely on vertex position - ComputeNormals( &_3ds.editChunk.pNamedObjects[i].pTriObjects[0], - pPSET[i].triangles ); - } -#endif - - free( _3ds.editChunk.pMaterials ); - free( _3ds.editChunk.pNamedObjects ); - - *ppPSET = pPSET; - *numpsets = numPolysets; -} diff --git a/tools/urt/tools/quake3/q3data/3dslib.h b/tools/urt/tools/quake3/q3data/3dslib.h deleted file mode 100644 index a5b2a10..0000000 --- a/tools/urt/tools/quake3/q3data/3dslib.h +++ /dev/null @@ -1,118 +0,0 @@ -typedef struct -{ - float x, y, z; -} _3DSPoint_t; - -typedef struct -{ - short a, b, c; - short flags; -} _3DSFace_t; - -typedef struct -{ - float s, t; -} _3DSTexVert_t; - -typedef struct -{ - char name[100]; - short numFaces; - short *pFaces; -} _3DSMeshMaterialGroup_t; - -typedef struct -{ - char name[80]; - - char texture[100]; - char specular[100]; - char reflection[100]; - char bump[100]; - char opacity[100]; -} _3DSMaterial_t; - -typedef struct -{ - short numFaces, numPoints, numTexVerts; - int numMeshMaterialGroups; - - _3DSPoint_t *pPoints; - _3DSFace_t *pFaces; - _3DSTexVert_t *pTexVerts; - - _3DSMeshMaterialGroup_t *pMeshMaterialGroups; -} _3DSTriObject_t; - -typedef struct -{ - char name[100]; - - int numTriObjects; - _3DSTriObject_t *pTriObjects; -} _3DSNamedObject_t; - -typedef struct -{ - int numNamedObjects; - int numMaterials; - - _3DSNamedObject_t *pNamedObjects; - _3DSMaterial_t *pMaterials; - -} _3DSEditChunk_t; - -typedef struct -{ - _3DSEditChunk_t editChunk; -} _3DS_t; - -#define _3DS_CHUNK_NULL 0x0000 -#define _3DS_CHUNK_UNKNOWN0 0x0001 -#define _3DS_CHUNK_M3D_VERSION 0x0002 -#define _3DS_CHUNK_M3D_KFVERSION 0x0005 -#define _3DS_CHUNK_COLOR_F 0x0010 -#define _3DS_CHUNK_COLOR_24 0x0011 -#define _3DS_CHUNK_LIN_COLOR_24 0x0012 -#define _3DS_CHUNK_LIN_COLOR_F 0x0013 -#define _3DS_CHUNK_INT_PERCENTAGE 0x0030 -#define _3DS_CHUNK_FLOAT_PERCENT 0x0031 -#define _3DS_CHUNK_MASTER_SCALE 0x0100 -#define _3DS_CHUNK_CHUNK_TYPE 0x0995 -#define _3DS_CHUNK_CHUNK_UNIQUE 0x0996 -#define _3DS_CHUNK_NOT_CHUNK 0x0997 -#define _3DS_CHUNK_CONTAINER 0x0998 -#define _3DS_CHUNK_IS_CHUNK 0x0999 -#define _3DS_CHUNK_C_SXP_SELFI_MASKDATA 0x0c3c - -#define _3DS_CHUNK_BITMAP 0x1100 -#define _3DS_CHUNK_USE_BITMAP 0x1101 -#define _3DS_CHUNK_SOLID_BGND 0x1200 -#define _3DS_CHUNK_USE_SOLID_BGND 0x1201 - -#define _3DS_CHUNK_EDIT 0x3d3d -#define _3DS_CHUNK_MESH_VERSION 0x3d3e - -#define _3DS_CHUNK_NAMED_OBJECT 0x4000 -#define _3DS_CHUNK_NAMED_TRI_OBJECT 0x4100 -#define _3DS_CHUNK_POINT_ARRAY 0x4110 -#define _3DS_CHUNK_POINT_FLAG_ARRAY 0x4111 -#define _3DS_CHUNK_FACE_ARRAY 0x4120 -#define _3DS_CHUNK_MSH_MAT_GROUP 0x4130 -#define _3DS_CHUNK_TEX_VERTS 0x4140 -#define _3DS_CHUNK_SMOOTH_GROUP 0x4150 -#define _3DS_CHUNK_MESH_MATRIX 0x4160 -#define _3DS_CHUNK_MAGIC 0x4d4d - -#define _3DS_CHUNK_MAT_NAME 0xa000 -#define _3DS_CHUNK_TEXMAP 0xa200 -#define _3DS_CHUNK_SPECMAP 0xa204 -#define _3DS_CHUNK_OPACMAP 0xa210 -#define _3DS_CHUNK_REFLMAP 0xa220 -#define _3DS_CHUNK_BUMPMAP 0xa230 -#define _3DS_CHUNK_MAT_MAPNAME 0xa300 -#define _3DS_CHUNK_MAT_LIST 0xafff - -#define _3DS_CHUNK_KEYFRAME_DATA 0xb000 - -void _3DS_LoadPolysets( const char *filename, polyset_t **ppPSET, int *numpsets, qboolean verbose ); diff --git a/tools/urt/tools/quake3/q3data/compress.c b/tools/urt/tools/quake3/q3data/compress.c deleted file mode 100644 index a584ef2..0000000 --- a/tools/urt/tools/quake3/q3data/compress.c +++ /dev/null @@ -1,766 +0,0 @@ -#include "q3data.h" - -#if 0 -/* - ================== - MTF - ================== - */ -cblock_t MTF( cblock_t in ){ - int i, j, b, code; - byte *out_p; - int index[256]; - cblock_t out; - - out_p = out.data = malloc( in.count + 4 ); - - // write count - *out_p++ = in.count & 255; - *out_p++ = ( in.count >> 8 ) & 255; - *out_p++ = ( in.count >> 16 ) & 255; - *out_p++ = ( in.count >> 24 ) & 255; - - for ( i = 0 ; i < 256 ; i++ ) - index[i] = i; - - for ( i = 0 ; i < in.count ; i++ ) - { - b = in.data[i]; - code = index[b]; - *out_p++ = code; - - // shuffle b indexes to 0 - for ( j = 0 ; j < 256 ; j++ ) - if ( index[j] < code ) { - index[j]++; - } - index[b] = 0; - } - - out.count = out_p - out.data; - - return out; -} - - -//========================================================================== - -int bwt_size; -byte *bwt_data; - -int bwtCompare( const void *elem1, const void *elem2 ){ - int i; - int i1, i2; - int b1, b2; - - i1 = *(int *)elem1; - i2 = *(int *)elem2; - - for ( i = 0 ; i < bwt_size ; i++ ) - { - b1 = bwt_data[i1]; - b2 = bwt_data[i2]; - if ( b1 < b2 ) { - return -1; - } - if ( b1 > b2 ) { - return 1; - } - if ( ++i1 == bwt_size ) { - i1 = 0; - } - if ( ++i2 == bwt_size ) { - i2 = 0; - } - } - - return 0; -} - -/* - ================== - BWT - ================== - */ -cblock_t BWT( cblock_t in ){ - int *sorted; - int i; - byte *out_p; - cblock_t out; - - bwt_size = in.count; - bwt_data = in.data; - - sorted = malloc( in.count * sizeof( *sorted ) ); - for ( i = 0 ; i < in.count ; i++ ) - sorted[i] = i; - qsort( sorted, in.count, sizeof( *sorted ), bwtCompare ); - - out_p = out.data = malloc( in.count + 8 ); - - // write count - *out_p++ = in.count & 255; - *out_p++ = ( in.count >> 8 ) & 255; - *out_p++ = ( in.count >> 16 ) & 255; - *out_p++ = ( in.count >> 24 ) & 255; - - // write head index - for ( i = 0 ; i < in.count ; i++ ) - if ( sorted[i] == 0 ) { - break; - } - *out_p++ = i & 255; - *out_p++ = ( i >> 8 ) & 255; - *out_p++ = ( i >> 16 ) & 255; - *out_p++ = ( i >> 24 ) & 255; - - // write the L column - for ( i = 0 ; i < in.count ; i++ ) - *out_p++ = in.data[( sorted[i] + in.count - 1 ) % in.count]; - - free( sorted ); - - out.count = out_p - out.data; - - return out; -} - -//========================================================================== - -typedef struct hnode_s -{ - int count; - qboolean used; - int children[2]; -} hnode_t; - -int numhnodes; -hnode_t hnodes[512]; -unsigned charbits[256]; -int charbitscount[256]; - -int SmallestNode( void ){ - int i; - int best, bestnode; - - best = 99999999; - bestnode = -1; - for ( i = 0 ; i < numhnodes ; i++ ) - { - if ( hnodes[i].used ) { - continue; - } - if ( !hnodes[i].count ) { - continue; - } - if ( hnodes[i].count < best ) { - best = hnodes[i].count; - bestnode = i; - } - } - - if ( bestnode == -1 ) { - return -1; - } - - hnodes[bestnode].used = true; - return bestnode; -} - -void BuildChars( int nodenum, unsigned bits, int bitcount ){ - hnode_t *node; - - if ( nodenum < 256 ) { - if ( bitcount > 32 ) { - Error( "bitcount > 32" ); - } - charbits[nodenum] = bits; - charbitscount[nodenum] = bitcount; - return; - } - - node = &hnodes[nodenum]; - bits <<= 1; - BuildChars( node->children[0], bits, bitcount + 1 ); - bits |= 1; - BuildChars( node->children[1], bits, bitcount + 1 ); -} - -/* - ================== - Huffman - ================== - */ -cblock_t Huffman( cblock_t in ){ - int i; - hnode_t *node; - int outbits, c; - unsigned bits; - byte *out_p; - cblock_t out; - int max, maxchar; - - // count - memset( hnodes, 0, sizeof( hnodes ) ); - for ( i = 0 ; i < in.count ; i++ ) - hnodes[in.data[i]].count++; - - // normalize counts - max = 0; - maxchar = 0; - for ( i = 0 ; i < 256 ; i++ ) - { - if ( hnodes[i].count > max ) { - max = hnodes[i].count; - maxchar = i; - } - } - if ( max == 0 ) { - Error( "Huffman: max == 0" ); - } - - for ( i = 0 ; i < 256 ; i++ ) - { - hnodes[i].count = ( hnodes[i].count * 255 + max - 1 ) / max; - } - - // build the nodes - numhnodes = 256; - while ( numhnodes != 511 ) - { - node = &hnodes[numhnodes]; - - // pick two lowest counts - node->children[0] = SmallestNode(); - if ( node->children[0] == -1 ) { - break; // no more - - } - node->children[1] = SmallestNode(); - if ( node->children[1] == -1 ) { - if ( node->children[0] != numhnodes - 1 ) { - Error( "Bad smallestnode" ); - } - break; - } - node->count = hnodes[node->children[0]].count + - hnodes[node->children[1]].count; - numhnodes++; - } - - BuildChars( numhnodes - 1, 0, 0 ); - - out_p = out.data = malloc( in.count * 2 + 1024 ); - memset( out_p, 0, in.count * 2 + 1024 ); - - // write count - *out_p++ = in.count & 255; - *out_p++ = ( in.count >> 8 ) & 255; - *out_p++ = ( in.count >> 16 ) & 255; - *out_p++ = ( in.count >> 24 ) & 255; - - // save out the 256 normalized counts so the tree can be recreated - for ( i = 0 ; i < 256 ; i++ ) - *out_p++ = hnodes[i].count; - - // write bits - outbits = 0; - for ( i = 0 ; i < in.count ; i++ ) - { - c = charbitscount[in.data[i]]; - bits = charbits[in.data[i]]; - while ( c ) - { - c--; - if ( bits & ( 1 << c ) ) { - out_p[outbits >> 3] |= 1 << ( outbits & 7 ); - } - outbits++; - } - } - - out_p += ( outbits + 7 ) >> 3; - - out.count = out_p - out.data; - - return out; -} - -//========================================================================== - -/* - ================== - RLE - ================== - */ -#define RLE_CODE 0xe8 -#define RLE_TRIPPLE 0xe9 - -int rle_counts[256]; -int rle_bytes[256]; - -cblock_t RLE( cblock_t in ){ - int i; - byte *out_p; - int val; - int repeat; - cblock_t out; - - out_p = out.data = malloc( in.count * 2 ); - - // write count - *out_p++ = in.count & 255; - *out_p++ = ( in.count >> 8 ) & 255; - *out_p++ = ( in.count >> 16 ) & 255; - *out_p++ = ( in.count >> 24 ) & 255; - - for ( i = 0 ; i < in.count ; ) - { - val = in.data[i]; - rle_bytes[val]++; - repeat = 1; - i++; - while ( i < in.count && repeat < 255 && in.data[i] == val ) - { - repeat++; - i++; - } - if ( repeat < 256 ) { - rle_counts[repeat]++; - } - if ( repeat > 3 || val == RLE_CODE ) { - *out_p++ = RLE_CODE; - *out_p++ = val; - *out_p++ = repeat; - } - else - { - while ( repeat-- ) - *out_p++ = val; - } - } - - out.count = out_p - out.data; - return out; -} - -//========================================================================== - -unsigned lzss_head[256]; -unsigned lzss_next[0x20000]; - -/* - ================== - LZSS - ================== - */ -#define BACK_WINDOW 0x10000 -#define BACK_BITS 16 -#define FRONT_WINDOW 16 -#define FRONT_BITS 4 -cblock_t LZSS( cblock_t in ){ - int i; - byte *out_p; - cblock_t out; - int val; - int j, start, max; - int bestlength, beststart; - int outbits; - - if ( in.count >= sizeof( lzss_next ) / 4 ) { - Error( "LZSS: too big" ); - } - - memset( lzss_head, -1, sizeof( lzss_head ) ); - - out_p = out.data = malloc( in.count * 2 ); - memset( out.data, 0, in.count * 2 ); - - // write count - *out_p++ = in.count & 255; - *out_p++ = ( in.count >> 8 ) & 255; - *out_p++ = ( in.count >> 16 ) & 255; - *out_p++ = ( in.count >> 24 ) & 255; - - outbits = 0; - for ( i = 0 ; i < in.count ; ) - { - val = in.data[i]; -#if 1 -// chained search - bestlength = 0; - beststart = 0; - - max = FRONT_WINDOW; - if ( i + max > in.count ) { - max = in.count - i; - } - - start = lzss_head[val]; - while ( start != -1 && start >= i - BACK_WINDOW ) - { - // count match length - for ( j = 0 ; j < max ; j++ ) - if ( in.data[start + j] != in.data[i + j] ) { - break; - } - if ( j > bestlength ) { - bestlength = j; - beststart = start; - } - start = lzss_next[start]; - } - -#else -// slow simple search - // search for a match - max = FRONT_WINDOW; - if ( i + max > in.count ) { - max = in.count - i; - } - - start = i - BACK_WINDOW; - if ( start < 0 ) { - start = 0; - } - bestlength = 0; - beststart = 0; - for ( ; start < i ; start++ ) - { - if ( in.data[start] != val ) { - continue; - } - // count match length - for ( j = 0 ; j < max ; j++ ) - if ( in.data[start + j] != in.data[i + j] ) { - break; - } - if ( j > bestlength ) { - bestlength = j; - beststart = start; - } - } -#endif - beststart = BACK_WINDOW - ( i - beststart ); - - if ( bestlength < 3 ) { // output a single char - bestlength = 1; - - out_p[outbits >> 3] |= 1 << ( outbits & 7 ); // set bit to mark char - outbits++; - for ( j = 0 ; j < 8 ; j++, outbits++ ) - if ( val & ( 1 << j ) ) { - out_p[outbits >> 3] |= 1 << ( outbits & 7 ); - } - } - else - { // output a phrase - outbits++; // leave a 0 bit to mark phrase - for ( j = 0 ; j < BACK_BITS ; j++, outbits++ ) - if ( beststart & ( 1 << j ) ) { - out_p[outbits >> 3] |= 1 << ( outbits & 7 ); - } - for ( j = 0 ; j < FRONT_BITS ; j++, outbits++ ) - if ( bestlength & ( 1 << j ) ) { - out_p[outbits >> 3] |= 1 << ( outbits & 7 ); - } - } - - while ( bestlength-- ) - { - val = in.data[i]; - lzss_next[i] = lzss_head[val]; - lzss_head[val] = i; - i++; - } - } - - out_p += ( outbits + 7 ) >> 3; - out.count = out_p - out.data; - return out; -} - -//========================================================================== - -#define MIN_REPT 15 -#define MAX_REPT 0 -#define HUF_TOKENS ( 256 + MAX_REPT ) - -unsigned charbits1[256][HUF_TOKENS]; -int charbitscount1[256][HUF_TOKENS]; - -hnode_t hnodes1[256][HUF_TOKENS * 2]; -int numhnodes1[256]; - -int order0counts[256]; - -/* - ================== - SmallestNode1 - ================== - */ -int SmallestNode1( hnode_t *hnodes, int numhnodes ){ - int i; - int best, bestnode; - - best = 99999999; - bestnode = -1; - for ( i = 0 ; i < numhnodes ; i++ ) - { - if ( hnodes[i].used ) { - continue; - } - if ( !hnodes[i].count ) { - continue; - } - if ( hnodes[i].count < best ) { - best = hnodes[i].count; - bestnode = i; - } - } - - if ( bestnode == -1 ) { - return -1; - } - - hnodes[bestnode].used = true; - return bestnode; -} - - -/* - ================== - BuildChars1 - ================== - */ -void BuildChars1( int prev, int nodenum, unsigned bits, int bitcount ){ - hnode_t *node; - - if ( nodenum < HUF_TOKENS ) { - if ( bitcount > 32 ) { - Error( "bitcount > 32" ); - } - charbits1[prev][nodenum] = bits; - charbitscount1[prev][nodenum] = bitcount; - return; - } - - node = &hnodes1[prev][nodenum]; - bits <<= 1; - BuildChars1( prev, node->children[0], bits, bitcount + 1 ); - bits |= 1; - BuildChars1( prev, node->children[1], bits, bitcount + 1 ); -} - - -/* - ================== - BuildTree1 - ================== - */ -void BuildTree1( int prev ){ - hnode_t *node, *nodebase; - int numhnodes; - - // build the nodes - numhnodes = HUF_TOKENS; - nodebase = hnodes1[prev]; - while ( 1 ) - { - node = &nodebase[numhnodes]; - - // pick two lowest counts - node->children[0] = SmallestNode1( nodebase, numhnodes ); - if ( node->children[0] == -1 ) { - break; // no more - - } - node->children[1] = SmallestNode1( nodebase, numhnodes ); - if ( node->children[1] == -1 ) { - break; - } - - node->count = nodebase[node->children[0]].count + - nodebase[node->children[1]].count; - numhnodes++; - } - numhnodes1[prev] = numhnodes - 1; - BuildChars1( prev, numhnodes - 1, 0, 0 ); -} - - -/* - ================== - Huffman1_Count - ================== - */ -void Huffman1_Count( cblock_t in ){ - int i; - int prev; - int v; - int rept; - - prev = 0; - for ( i = 0 ; i < in.count ; i++ ) - { - v = in.data[i]; - order0counts[v]++; - hnodes1[prev][v].count++; - prev = v; -#if 1 - for ( rept = 1 ; i + rept < in.count && rept < MAX_REPT ; rept++ ) - if ( in.data[i + rept] != v ) { - break; - } - if ( rept > MIN_REPT ) { - hnodes1[prev][255 + rept].count++; - i += rept - 1; - } -#endif - } -} - - -/* - ================== - Huffman1_Build - ================== - */ -byte scaled[256][HUF_TOKENS]; -void Huffman1_Build( FILE *f ){ - int i, j, v; - int max; - int total; - - for ( i = 0 ; i < 256 ; i++ ) - { - // normalize and save the counts - max = 0; - for ( j = 0 ; j < HUF_TOKENS ; j++ ) - { - if ( hnodes1[i][j].count > max ) { - max = hnodes1[i][j].count; - } - } - if ( max == 0 ) { - max = 1; - } - total = 0; - for ( j = 0 ; j < HUF_TOKENS ; j++ ) - { // easy to overflow 32 bits here! - v = ( hnodes1[i][j].count * (double)255 + max - 1 ) / max; - if ( v > 255 ) { - Error( "v > 255" ); - } - scaled[i][j] = hnodes1[i][j].count = v; - if ( v ) { - total++; - } - } - if ( total == 1 ) { // must have two tokens - if ( !scaled[i][0] ) { - scaled[i][0] = hnodes1[i][0].count = 1; - } - else{ - scaled[i][1] = hnodes1[i][1].count = 1; - } - } - - BuildTree1( i ); - } - -#if 0 - // count up the total bits - total = 0; - for ( i = 0 ; i < 256 ; i++ ) - for ( j = 0 ; j < 256 ; j++ ) - total += charbitscount1[i][j] * hnodes1[i][j].count; - - total = ( total + 7 ) / 8; - printf( "%i bytes huffman1 compressed\n", total ); -#endif - - fwrite( scaled, 1, sizeof( scaled ), f ); -} - -/* - ================== - Huffman1 - - Order 1 compression with pre-built table - ================== - */ -cblock_t Huffman1( cblock_t in ){ - int i; - int outbits, c; - unsigned bits; - byte *out_p; - cblock_t out; - int prev; - int v; - int rept; - - out_p = out.data = malloc( in.count * 2 + 1024 ); - memset( out_p, 0, in.count * 2 + 1024 ); - - // write count - *out_p++ = in.count & 255; - *out_p++ = ( in.count >> 8 ) & 255; - *out_p++ = ( in.count >> 16 ) & 255; - *out_p++ = ( in.count >> 24 ) & 255; - - // write bits - outbits = 0; - prev = 0; - for ( i = 0 ; i < in.count ; i++ ) - { - v = in.data[i]; - - c = charbitscount1[prev][v]; - bits = charbits1[prev][v]; - if ( !c ) { - Error( "!bits" ); - } - while ( c ) - { - c--; - if ( bits & ( 1 << c ) ) { - out_p[outbits >> 3] |= 1 << ( outbits & 7 ); - } - outbits++; - } - - prev = v; -#if 1 - // check for repeat encodes - for ( rept = 1 ; i + rept < in.count && rept < MAX_REPT ; rept++ ) - if ( in.data[i + rept] != v ) { - break; - } - if ( rept > MIN_REPT ) { - c = charbitscount1[prev][255 + rept]; - bits = charbits1[prev][255 + rept]; - if ( !c ) { - Error( "!bits" ); - } - while ( c ) - { - c--; - if ( bits & ( 1 << c ) ) { - out_p[outbits >> 3] |= 1 << ( outbits & 7 ); - } - outbits++; - } - i += rept - 1; - } -#endif - } - - out_p += ( outbits + 7 ) >> 3; - - out.count = out_p - out.data; - - return out; -} - -#endif diff --git a/tools/urt/tools/quake3/q3data/images.c b/tools/urt/tools/quake3/q3data/images.c deleted file mode 100644 index e9ad92d..0000000 --- a/tools/urt/tools/quake3/q3data/images.c +++ /dev/null @@ -1,468 +0,0 @@ -#include "q3data.h" - -byte *byteimage, *lbmpalette; -int byteimagewidth, byteimageheight; - - -char mip_prefix[1024]; // directory to dump the textures in - -qboolean colormap_issued; -byte colormap_palette[768]; - -/* - ============== - Cmd_Grab - - $grab filename x y width height - ============== - */ -void Cmd_Grab( void ){ - int xl,yl,w,h,y; - byte *cropped; - char savename[1024]; - char dest[1024]; - - GetToken( qfalse ); - - if ( token[0] == '/' || token[0] == '\\' ) { - sprintf( savename, "%s%s.pcx", writedir, token + 1 ); - } - else{ - sprintf( savename, "%spics/%s.pcx", writedir, token ); - } - - if ( g_release ) { - if ( token[0] == '/' || token[0] == '\\' ) { - sprintf( dest, "%s.pcx", token + 1 ); - } - else{ - sprintf( dest, "pics/%s.pcx", token ); - } - - ReleaseFile( dest ); - return; - } - - GetToken( qfalse ); - xl = atoi( token ); - GetToken( qfalse ); - yl = atoi( token ); - GetToken( qfalse ); - w = atoi( token ); - GetToken( qfalse ); - h = atoi( token ); - - if ( xl < 0 || yl < 0 || w < 0 || h < 0 || xl + w > byteimagewidth || yl + h > byteimageheight ) { - Error( "GrabPic: Bad size: %i, %i, %i, %i",xl,yl,w,h ); - } - - // crop it to the proper size - cropped = malloc( w * h ); - for ( y = 0 ; y < h ; y++ ) - { - memcpy( cropped + y * w, byteimage + ( y + yl ) * byteimagewidth + xl, w ); - } - - // save off the new image - printf( "saving %s\n", savename ); - CreatePath( savename ); - WritePCXfile( savename, cropped, w, h, lbmpalette ); - - free( cropped ); -} - -/* - ============== - Cmd_Raw - - $grab filename x y width height - ============== - */ -void Cmd_Raw( void ){ - int xl,yl,w,h,y; - byte *cropped; - char savename[1024]; - char dest[1024]; - - GetToken( qfalse ); - - sprintf( savename, "%s%s.lmp", writedir, token ); - - if ( g_release ) { - sprintf( dest, "%s.lmp", token ); - ReleaseFile( dest ); - return; - } - - GetToken( qfalse ); - xl = atoi( token ); - GetToken( qfalse ); - yl = atoi( token ); - GetToken( qfalse ); - w = atoi( token ); - GetToken( qfalse ); - h = atoi( token ); - - if ( xl < 0 || yl < 0 || w < 0 || h < 0 || xl + w > byteimagewidth || yl + h > byteimageheight ) { - Error( "GrabPic: Bad size: %i, %i, %i, %i",xl,yl,w,h ); - } - - // crop it to the proper size - cropped = malloc( w * h ); - for ( y = 0 ; y < h ; y++ ) - { - memcpy( cropped + y * w, byteimage + ( y + yl ) * byteimagewidth + xl, w ); - } - - // save off the new image - printf( "saving %s\n", savename ); - CreatePath( savename ); - - SaveFile( savename, cropped, w * h ); - - free( cropped ); -} - -/* - ============================================================================= - - COLORMAP GRABBING - - ============================================================================= - */ - -/* - =============== - BestColor - =============== - */ -byte BestColor( int r, int g, int b, int start, int stop ){ - int i; - int dr, dg, db; - int bestdistortion, distortion; - int bestcolor; - byte *pal; - -// -// let any color go to 0 as a last resort -// - bestdistortion = 256 * 256 * 4; - bestcolor = 0; - - pal = colormap_palette + start * 3; - for ( i = start ; i <= stop ; i++ ) - { - dr = r - (int)pal[0]; - dg = g - (int)pal[1]; - db = b - (int)pal[2]; - pal += 3; - distortion = dr * dr + dg * dg + db * db; - if ( distortion < bestdistortion ) { - if ( !distortion ) { - return i; // perfect match - - } - bestdistortion = distortion; - bestcolor = i; - } - } - - return bestcolor; -} - - -/* - ============== - Cmd_Colormap - - $colormap filename - - the brightes colormap is first in the table (FIXME: reverse this now?) - - 64 rows of 256 : lightmaps - 256 rows of 256 : translucency table - ============== - */ -void Cmd_Colormap( void ){ - int levels, brights; - int l, c; - float frac, red, green, blue; - float range; - byte *cropped, *lump_p; - char savename[1024]; - char dest[1024]; - - colormap_issued = qtrue; - if ( !g_release ) { - memcpy( colormap_palette, lbmpalette, 768 ); - } - - if ( !TokenAvailable() ) { // just setting colormap_issued - return; - } - - GetToken( qfalse ); - sprintf( savename, "%spics/%s.pcx", writedir, token ); - - if ( g_release ) { - sprintf( dest, "pics/%s.pcx", token ); - ReleaseFile( dest ); - return; - } - - range = 2; - levels = 64; - brights = 1; // ignore 255 (transparent) - - cropped = malloc( ( levels + 256 ) * 256 ); - lump_p = cropped; - -// shaded levels - for ( l = 0; l < levels; l++ ) - { - frac = range - range * (float)l / ( levels - 1 ); - for ( c = 0 ; c < 256 - brights ; c++ ) - { - red = lbmpalette[c * 3]; - green = lbmpalette[c * 3 + 1]; - blue = lbmpalette[c * 3 + 2]; - - red = (int)( red * frac + 0.5 ); - green = (int)( green * frac + 0.5 ); - blue = (int)( blue * frac + 0.5 ); - -// -// note: 254 instead of 255 because 255 is the transparent color, and we -// don't want anything remapping to that -// don't use color 0, because NT can't remap that (or 255) -// - *lump_p++ = BestColor( red,green,blue, 1, 254 ); - } - - // fullbrights allways stay the same - for ( ; c < 256 ; c++ ) - *lump_p++ = c; - } - -// 66% transparancy table - for ( l = 0; l < 255; l++ ) - { - for ( c = 0 ; c < 255 ; c++ ) - { - red = lbmpalette[c * 3] * 0.33 + lbmpalette[l * 3] * 0.66; - green = lbmpalette[c * 3 + 1] * 0.33 + lbmpalette[l * 3 + 1] * 0.66; - blue = lbmpalette[c * 3 + 2] * 0.33 + lbmpalette[l * 3 + 2] * 0.66; - - *lump_p++ = BestColor( red,green,blue, 1, 254 ); - } - *lump_p++ = 255; - } - for ( c = 0 ; c < 256 ; c++ ) - *lump_p++ = 255; - - // save off the new image - printf( "saving %s\n", savename ); - CreatePath( savename ); - WritePCXfile( savename, cropped, 256, levels + 256, lbmpalette ); - - free( cropped ); -} - -/* - ============================================================================= - - MIPTEX GRABBING - - ============================================================================= - */ - -byte pixdata[256]; - -int d_red, d_green, d_blue; - -byte palmap[32][32][32]; -qboolean palmap_built; - -/* - ============= - FindColor - ============= - */ -int FindColor( int r, int g, int b ){ - int bestcolor; - - if ( r > 255 ) { - r = 255; - } - if ( r < 0 ) { - r = 0; - } - if ( g > 255 ) { - g = 255; - } - if ( g < 0 ) { - g = 0; - } - if ( b > 255 ) { - b = 255; - } - if ( b < 0 ) { - b = 0; - } -#ifndef TABLECOLORS - bestcolor = BestColor( r, g, b, 0, 254 ); -#else - bestcolor = palmap[r >> 3][g >> 3][b >> 3]; -#endif - - return bestcolor; -} - - -void BuildPalmap( void ){ -#ifdef TABLECOLORS - int r, g, b; - int bestcolor; - - if ( palmap_built ) { - return; - } - palmap_built = qtrue; - - for ( r = 4 ; r < 256 ; r += 8 ) - { - for ( g = 4 ; g < 256 ; g += 8 ) - { - for ( b = 4 ; b < 256 ; b += 8 ) - { - bestcolor = BestColor( r, g, b, 1, 254 ); - palmap[r >> 3][g >> 3][b >> 3] = bestcolor; - } - } - } -#endif - - if ( !colormap_issued ) { - Error( "You must issue a $colormap command first" ); - } - -} - -/* - ============= - AveragePixels - ============= - */ -byte AveragePixels( int count ){ - int r,g,b; - int i; - int vis; - int pix; - int bestcolor; - byte *pal; - int fullbright; - - vis = 0; - r = g = b = 0; - fullbright = 0; - for ( i = 0 ; i < count ; i++ ) - { - pix = pixdata[i]; - - r += lbmpalette[pix * 3]; - g += lbmpalette[pix * 3 + 1]; - b += lbmpalette[pix * 3 + 2]; - vis++; - } - - r /= vis; - g /= vis; - b /= vis; - - // error diffusion - r += d_red; - g += d_green; - b += d_blue; - -// -// find the best color -// - bestcolor = FindColor( r, g, b ); - - // error diffusion - pal = colormap_palette + bestcolor * 3; - d_red = r - (int)pal[0]; - d_green = g - (int)pal[1]; - d_blue = b - (int)pal[2]; - - return bestcolor; -} - - - -/* - ============================================================================= - - ENVIRONMENT MAP GRABBING - - Creates six pcx files from tga files without any palette edge seams - also copies the tga files for GL rendering. - ============================================================================= - */ - -// 3dstudio environment map suffixes -char *suf[6] = {"rt", "ft", "lf", "bk", "up", "dn"}; - -/* - ================= - Cmd_Environment - ================= - */ -void Cmd_Environment( void ){ - char name[1024]; - int i, x, y; - byte image[256 * 256]; - byte *tga; - - GetToken( qfalse ); - - if ( g_release ) { - for ( i = 0 ; i < 6 ; i++ ) - { - sprintf( name, "env/%s%s.pcx", token, suf[i] ); - ReleaseFile( name ); - sprintf( name, "env/%s%s.tga", token, suf[i] ); - ReleaseFile( name ); - } - return; - } - // get the palette - BuildPalmap(); - - sprintf( name, "%senv/", gamedir ); - CreatePath( name ); - - // convert the images - for ( i = 0 ; i < 6 ; i++ ) - { - sprintf( name, "%senv/%s%s.tga", gamedir, token, suf[i] ); - printf( "loading %s...\n", name ); - LoadTGA( name, &tga, NULL, NULL ); - - for ( y = 0 ; y < 256 ; y++ ) - { - for ( x = 0 ; x < 256 ; x++ ) - { - image[y * 256 + x] = FindColor( tga[( y * 256 + x ) * 4 + 0],tga[( y * 256 + x ) * 4 + 1],tga[( y * 256 + x ) * 4 + 2] ); - } - } - free( tga ); - sprintf( name, "%senv/%s%s.pcx", writedir, token, suf[i] ); - if ( FileTime( name ) != -1 ) { - printf( "%s already exists, not overwriting.\n", name ); - } - else{ - WritePCXfile( name, image, 256, 256, colormap_palette ); - } - } -} diff --git a/tools/urt/tools/quake3/q3data/md3lib.c b/tools/urt/tools/quake3/q3data/md3lib.c deleted file mode 100644 index 007e760..0000000 --- a/tools/urt/tools/quake3/q3data/md3lib.c +++ /dev/null @@ -1,190 +0,0 @@ -#include -#ifdef WIN32 -#include -#endif -#include "md3lib.h" - -#if defined ( __linux__ ) || defined ( __APPLE__ ) -#define filelength Q_filelength -#endif - -/* -** MD3_ComputeTagFromTri -*/ -void MD3_ComputeTagFromTri( md3Tag_t *pTag, const float pTri[3][3] ){ - float len[3]; - vec3_t axes[3], sides[3]; - int longestSide, shortestSide, hypotSide; - int origin; - int j; - float d; - - memset( axes, 0, sizeof( axes ) ); - memset( sides, 0, sizeof( sides ) ); - - // - // compute sides - // - for ( j = 0; j < 3; j++ ) - { - sides[j][0] = pTri[( j + 1 ) % 3][0] - pTri[j][0]; - sides[j][1] = pTri[( j + 1 ) % 3][1] - pTri[j][1]; - sides[j][2] = pTri[( j + 1 ) % 3][2] - pTri[j][2]; - - len[j] = ( float ) sqrt( DotProduct( sides[j], sides[j] ) ); - } - -#if 0 - if ( len[0] > len[1] && len[0] > len[2] ) { - longestSide = 0; shortestSide = 1; origin = 2; - } - else if ( len[1] > len[0] && len[1] > len[2] ) { - longestSide = 1; shortestSide = 2; origin = 0; - } - else if ( len[2] > len[0] && len[2] > len[1] ) { - longestSide = 2; shortestSide = 0; origin = 1; - } - else - { - Error( "invalid tag triangle, must be a right triangle with unequal length sides" ); - } -#endif - if ( len[0] > len[1] && len[0] > len[2] ) { - hypotSide = 0; - origin = 2; - } - else if ( len[1] > len[0] && len[1] > len[2] ) { - hypotSide = 1; - origin = 0; - } - else if ( len[2] > len[0] && len[2] > len[1] ) { - hypotSide = 2; - origin = 1; - } - len[hypotSide] = -1; - - if ( len[0] > len[1] && len[0] > len[2] ) { - longestSide = 0; - } - else if ( len[1] > len[0] && len[1] > len[2] ) { - longestSide = 1; - } - else if ( len[2] > len[0] && len[2] > len[1] ) { - longestSide = 2; - } - len[longestSide] = -1; - - if ( len[0] > len[1] && len[0] > len[2] ) { - shortestSide = 0; - } - else if ( len[1] > len[0] && len[1] > len[2] ) { - shortestSide = 1; - } - else if ( len[2] > len[0] && len[2] > len[1] ) { - shortestSide = 2; - } - len[shortestSide] = -1; - - - -// VectorNormalize( sides[shortestSide], axes[0] ); -// VectorNormalize( sides[longestSide], axes[1] ); - VectorNormalize( sides[longestSide], axes[0] ); - VectorNormalize( sides[shortestSide], axes[1] ); - - // project shortest side so that it is exactly 90 degrees to the longer side - d = DotProduct( axes[0], axes[1] ); - VectorMA( axes[0], -d, axes[1], axes[0] ); - VectorNormalize( axes[0], axes[0] ); - - CrossProduct( sides[longestSide], sides[shortestSide], axes[2] ); - VectorNormalize( axes[2], axes[2] ); - - pTag->origin[0] = pTri[origin][0]; - pTag->origin[1] = pTri[origin][1]; - pTag->origin[2] = pTri[origin][2]; - - VectorCopy( axes[0], pTag->axis[0] ); - VectorCopy( axes[1], pTag->axis[1] ); - VectorCopy( axes[2], pTag->axis[2] ); -} - -/* - ============== - MD3_Dump - ============== - */ -void MD3_Dump( const char *filename ){ - md3Header_t header; - md3Tag_t *pTag; - md3Surface_t *pSurface; - FILE *fp; - void *_buffer; - void *buffer; - long fileSize; - int i; - - if ( ( fp = fopen( filename, "rb" ) ) == 0 ) { - Error( "Unable to open '%s'\n", filename ); - } - - fileSize = filelength( fileno( fp ) ); - _buffer = malloc( filelength( fileno( fp ) ) ); - fread( _buffer, fileSize, 1, fp ); - fclose( fp ); - - buffer = ( char * ) _buffer; - header = *( md3Header_t * ) _buffer; - - if ( header.ident != MD3_IDENT ) { - Error( "Incorrect ident for '%s'\n", filename ); - } - - printf( "Contents of '%s'\n", filename ); - printf( " version: %d\n", header.version ); - printf( " name: %s\n", header.name ); - printf( " num frames: %d\n", header.numFrames ); - printf( " num tags: %d\n", header.numTags ); - printf( " num surfaces: %d\n", header.numSurfaces ); - printf( " num skins: %d\n", header.numSkins ); - printf( " file size: %d\n", fileSize ); - - printf( "--- TAGS ---\n" ); - pTag = ( md3Tag_t * ) ( ( ( char * ) buffer ) + header.ofsTags ); - for ( i = 0; i < header.numTags; i++, pTag++ ) - { - printf( " tag %d ('%s')\n", i, pTag->name ); - printf( " origin: %f,%f,%f\n", pTag->origin[0], pTag->origin[1], pTag->origin[2] ); - printf( " vf: %f,%f,%f\n", pTag->axis[0][0], pTag->axis[0][1], pTag->axis[0][2] ); - printf( " vr: %f,%f,%f\n", pTag->axis[1][0], pTag->axis[1][1], pTag->axis[1][2] ); - printf( " vu: %f,%f,%f\n", pTag->axis[2][0], pTag->axis[2][1], pTag->axis[2][2] ); - } - - printf( "--- SURFACES ---\n" ); - pSurface = ( md3Surface_t * ) ( ( ( char * ) buffer ) + header.ofsSurfaces ); - - for ( i = 0; i < header.numSurfaces; i++ ) - { - int j; - - md3Shader_t *pShader = ( md3Shader_t * ) ( ( ( char * ) pSurface ) + pSurface->ofsShaders ); - - printf( "\n surface %d ('%s')\n", i, pSurface->name ); - printf( " num frames: %d\n", pSurface->numFrames ); - printf( " num shaders: %d\n", pSurface->numShaders ); - printf( " num tris: %d\n", pSurface->numTriangles ); - printf( " num verts: %d\n", pSurface->numVerts ); - - if ( pSurface->numShaders > 0 ) { - printf( " --- SHADERS ---\n" ); - - for ( j = 0; j < pSurface->numShaders; j++, pShader++ ) - { - printf( " shader %d ('%s')\n", j, pShader->name ); - } - } - pSurface = ( md3Surface_t * ) ( ( ( char * ) pSurface ) + pSurface->ofsEnd ); - } - - free( _buffer ); -} diff --git a/tools/urt/tools/quake3/q3data/md3lib.h b/tools/urt/tools/quake3/q3data/md3lib.h deleted file mode 100644 index bdee0bd..0000000 --- a/tools/urt/tools/quake3/q3data/md3lib.h +++ /dev/null @@ -1,7 +0,0 @@ -#include -#include "../common/cmdlib.h" -#include "mathlib.h" -#include "../common/qfiles.h" - -void MD3_Dump( const char *filename ); -void MD3_ComputeTagFromTri( md3Tag_t *pTag, const float tri[3][3] ); diff --git a/tools/urt/tools/quake3/q3data/models.c b/tools/urt/tools/quake3/q3data/models.c deleted file mode 100644 index 97de189..0000000 --- a/tools/urt/tools/quake3/q3data/models.c +++ /dev/null @@ -1,2086 +0,0 @@ -#include -#include "q3data.h" - -//================================================================= - -static void OrderSurfaces( void ); -static void LoadBase( const char *filename ); -static int LoadModelFile( const char *filename, polyset_t **ppsets, int *pnumpolysets ); - -#define MAX_SURFACE_TRIS ( SHADER_MAX_INDEXES / 3 ) -#define MAX_SURFACE_VERTS SHADER_MAX_VERTEXES - -#define MD3_TYPE_UNKNOWN 0 -#define MD3_TYPE_BASE3DS 1 -#define MD3_TYPE_SPRITE 2 -#define MD3_TYPE_ASE 3 - -#define MAX_ANIM_FRAMES 512 -#define MAX_ANIM_SURFACES 32 - -typedef struct -{ - polyset_t *frames; - int numFrames; -} SurfaceAnimation_t; - -typedef struct -{ - polyset_t *surfaces[MAX_ANIM_SURFACES]; - int numSurfaces; -} ObjectAnimationFrame_t; - -typedef struct { - vec3_t xyz; - vec3_t normal; - vec3_t color; - float st[2]; - int index; -} baseVertex_t; - -typedef struct { - baseVertex_t v[3]; -} baseTriangle_t; - -//================================================================ - -typedef struct -{ - md3Surface_t header; - md3Shader_t shaders[MD3_MAX_SHADERS]; - // all verts (xyz_normal) - float *verts[MD3_MAX_FRAMES]; - - baseTriangle_t baseTriangles[MD3_MAX_TRIANGLES]; - - // the triangles will be sorted so that they form long generalized tristrips - int orderedTriangles[MD3_MAX_TRIANGLES][3]; - int lodTriangles[MD3_MAX_TRIANGLES][3]; - baseVertex_t baseVertexes[MD3_MAX_VERTS]; - -} md3SurfaceData_t; - -typedef struct -{ - int skinwidth, skinheight; - - md3SurfaceData_t surfData[MD3_MAX_SURFACES]; - - md3Tag_t tags[MD3_MAX_FRAMES][MD3_MAX_TAGS]; - md3Frame_t frames[MD3_MAX_FRAMES]; - - md3Header_t model; - float scale_up; // set by $scale - vec3_t adjust; // set by $origin - vec3_t aseAdjust; - int fixedwidth, fixedheight; // set by $skinsize - - int maxSurfaceTris; - - int lowerSkipFrameStart, lowerSkipFrameEnd; - int maxUpperFrames; - int maxHeadFrames; - int currentLod; - float lodBias; - - int type; // MD3_TYPE_BASE, MD3_TYPE_OLDBASE, MD3_TYPE_ASE, or MD3_TYPE_SPRITE - -} q3data; - -q3data g_data; - -// the command list holds counts, the count * 3 xyz, st, normal indexes -// that are valid for every frame -char g_cddir[1024]; -char g_modelname[1024]; - -//============================================================== - -/* - =============== - ClearModel - =============== - */ -void ClearModel( void ){ - int i; - - g_data.type = MD3_TYPE_UNKNOWN; - - for ( i = 0; i < MD3_MAX_SURFACES; i++ ) - { - memset( &g_data.surfData[i].header, 0, sizeof( g_data.surfData[i].header ) ); - memset( &g_data.surfData[i].shaders, 0, sizeof( g_data.surfData[i].shaders ) ); - memset( &g_data.surfData[i].verts, 0, sizeof( g_data.surfData[i].verts ) ); - } - - memset( g_data.tags, 0, sizeof( g_data.tags ) ); - - for ( i = 0; i < g_data.model.numSurfaces; i++ ) - { - int j; - - for ( j = 0; j < g_data.surfData[i].header.numShaders; j++ ) - { - memset( &g_data.surfData[i].shaders[j], 0, sizeof( g_data.surfData[i].shaders[j] ) ); - } - } - memset( &g_data.model, 0, sizeof( g_data.model ) ); - memset( g_cddir, 0, sizeof( g_cddir ) ); - - g_modelname[0] = 0; - g_data.scale_up = 1.0; - memset( &g_data.model, 0, sizeof( g_data.model ) ); - VectorCopy( vec3_origin, g_data.adjust ); - g_data.fixedwidth = g_data.fixedheight = 0; - g_skipmodel = qfalse; -} - -/* -** void WriteModelSurface( FILE *modelouthandle, md3SurfaceData_t *pSurfData ) -** -** This routine assumes that the file position has been adjusted -** properly prior to entry to point at the beginning of the surface. -** -** Since surface header information is completely relative, we can't -** just randomly seek to an arbitrary surface location right now. Is -** this something we should add? -*/ -void WriteModelSurface( FILE *modelouthandle, md3SurfaceData_t *pSurfData ){ - md3Surface_t *pSurf = &pSurfData->header; - md3Shader_t *pShader = pSurfData->shaders; - baseVertex_t *pBaseVertex = pSurfData->baseVertexes; - float **verts = pSurfData->verts; - - short xyznormals[MD3_MAX_VERTS][4]; - - float base_st[MD3_MAX_VERTS][2]; - md3Surface_t surftemp; - - int f, i, j, k; - - if ( strstr( pSurf->name, "tag_" ) == pSurf->name ) { - return; - } - - // - // write out the header - // - surftemp = *pSurf; - surftemp.ident = LittleLong( MD3_IDENT ); - surftemp.flags = LittleLong( pSurf->flags ); - surftemp.numFrames = LittleLong( pSurf->numFrames ); - surftemp.numShaders = LittleLong( pSurf->numShaders ); - - surftemp.ofsShaders = LittleLong( pSurf->ofsShaders ); - - surftemp.ofsTriangles = LittleLong( pSurf->ofsTriangles ); - surftemp.numTriangles = LittleLong( pSurf->numTriangles ); - - surftemp.ofsSt = LittleLong( pSurf->ofsSt ); - surftemp.ofsXyzNormals = LittleLong( pSurf->ofsXyzNormals ); - surftemp.ofsEnd = LittleLong( pSurf->ofsEnd ); - - SafeWrite( modelouthandle, &surftemp, sizeof( surftemp ) ); - - if ( g_verbose ) { - printf( "surface '%s'\n", pSurf->name ); - printf( "...num shaders: %d\n", pSurf->numShaders ); - } - - // - // write out shaders - // - for ( i = 0; i < pSurf->numShaders; i++ ) - { - md3Shader_t shadertemp; - - if ( g_verbose ) { - printf( "......'%s'\n", pShader[i].name ); - } - - shadertemp = pShader[i]; - shadertemp.shaderIndex = LittleLong( shadertemp.shaderIndex ); - SafeWrite( modelouthandle, &shadertemp, sizeof( shadertemp ) ); - } - - // - // write out the triangles - // - for ( i = 0 ; i < pSurf->numTriangles ; i++ ) - { - for ( j = 0 ; j < 3 ; j++ ) - { - int ivalue = LittleLong( pSurfData->orderedTriangles[i][j] ); - pSurfData->orderedTriangles[i][j] = ivalue; - } - } - - SafeWrite( modelouthandle, pSurfData->orderedTriangles, pSurf->numTriangles * sizeof( g_data.surfData[0].orderedTriangles[0] ) ); - - if ( g_verbose ) { - printf( "\n...num verts: %d\n", pSurf->numVerts ); - printf( "...TEX COORDINATES\n" ); - } - - // - // write out the texture coordinates - // - for ( i = 0; i < pSurf->numVerts ; i++ ) { - base_st[i][0] = LittleFloat( pBaseVertex[i].st[0] ); - base_st[i][1] = LittleFloat( pBaseVertex[i].st[1] ); - if ( g_verbose ) { - printf( "......%d: %f,%f\n", i, base_st[i][0], base_st[i][1] ); - } - } - SafeWrite( modelouthandle, base_st, pSurf->numVerts * sizeof( base_st[0] ) ); - - // - // write the xyz_normal - // - if ( g_verbose ) { - printf( "...XYZNORMALS\n" ); - } - for ( f = 0; f < g_data.model.numFrames; f++ ) - { - for ( j = 0 ; j < pSurf->numVerts; j++ ) - { - short value; - - for ( k = 0 ; k < 3 ; k++ ) - { - value = ( short ) ( verts[f][j * 6 + k] / MD3_XYZ_SCALE ); - xyznormals[j][k] = LittleShort( value ); - } - NormalToLatLong( &verts[f][j * 6 + 3], (byte *)&xyznormals[j][3] ); - } - SafeWrite( modelouthandle, xyznormals, pSurf->numVerts * sizeof( short ) * 4 ); - } -} - -/* -** void WriteModelFile( FILE *modelouthandle ) -** -** CHUNK SIZE -** header sizeof( md3Header_t ) -** frames sizeof( md3Frame_t ) * numFrames -** tags sizeof( md3Tag_t ) * numFrames * numTags -** surfaces surfaceSum -*/ -void WriteModelFile( FILE *modelouthandle ){ - int f; - int i, j; - md3Header_t modeltemp; - long surfaceSum = 0; - int numRealSurfaces = 0; - int numFrames = g_data.model.numFrames; - - // compute offsets for all surfaces, sum their total size - for ( i = 0; i < g_data.model.numSurfaces; i++ ) - { - if ( strstr( g_data.surfData[i].header.name, "tag_" ) != g_data.surfData[i].header.name ) { - md3Surface_t *psurf = &g_data.surfData[i].header; - - if ( psurf->numTriangles == 0 || psurf->numVerts == 0 ) { - continue; - } - - // - // the triangle and vertex split threshold is controlled by a parameter - // to $base, a la $base blah.3ds 1900, where "1900" determines the number - // of triangles to split on - // - else if ( psurf->numVerts > MAX_SURFACE_VERTS ) { - Error( "too many vertices\n" ); - } - - psurf->numFrames = numFrames; - - psurf->ofsShaders = sizeof( md3Surface_t ); - - if ( psurf->numTriangles > MAX_SURFACE_TRIS ) { - Error( "too many faces\n" ); - } - - psurf->ofsTriangles = psurf->ofsShaders + psurf->numShaders * sizeof( md3Shader_t ); - - psurf->ofsSt = psurf->ofsTriangles + psurf->numTriangles * sizeof( md3Triangle_t ); - psurf->ofsXyzNormals = psurf->ofsSt + psurf->numVerts * sizeof( md3St_t ); - psurf->ofsEnd = psurf->ofsXyzNormals + psurf->numFrames * psurf->numVerts * ( sizeof( short ) * 4 ); - - surfaceSum += psurf->ofsEnd; - - numRealSurfaces++; - } - } - - g_data.model.ident = MD3_IDENT; - g_data.model.version = MD3_VERSION; - - g_data.model.ofsFrames = sizeof( md3Header_t ); - g_data.model.ofsTags = g_data.model.ofsFrames + numFrames * sizeof( md3Frame_t ); - g_data.model.ofsSurfaces = g_data.model.ofsTags + numFrames * g_data.model.numTags * sizeof( md3Tag_t ); - g_data.model.ofsEnd = g_data.model.ofsSurfaces + surfaceSum; - - // - // write out the model header - // - modeltemp = g_data.model; - modeltemp.ident = LittleLong( modeltemp.ident ); - modeltemp.version = LittleLong( modeltemp.version ); - modeltemp.numFrames = LittleLong( modeltemp.numFrames ); - modeltemp.numTags = LittleLong( modeltemp.numTags ); - modeltemp.numSurfaces = LittleLong( numRealSurfaces ); - modeltemp.ofsFrames = LittleLong( modeltemp.ofsFrames ); - modeltemp.ofsTags = LittleLong( modeltemp.ofsTags ); - modeltemp.ofsSurfaces = LittleLong( modeltemp.ofsSurfaces ); - modeltemp.ofsEnd = LittleLong( modeltemp.ofsEnd ); - - SafeWrite( modelouthandle, &modeltemp, sizeof( modeltemp ) ); - - // - // write out the frames - // - for ( i = 0 ; i < numFrames ; i++ ) - { - vec3_t tmpVec; - float maxRadius = 0; - - // - // compute localOrigin and radius - // - g_data.frames[i].localOrigin[0] = - g_data.frames[i].localOrigin[1] = - g_data.frames[i].localOrigin[2] = 0; - - for ( j = 0; j < 8; j++ ) - { - tmpVec[0] = g_data.frames[i].bounds[( j & 1 ) != 0][0]; - tmpVec[1] = g_data.frames[i].bounds[( j & 2 ) != 0][1]; - tmpVec[2] = g_data.frames[i].bounds[( j & 4 ) != 0][2]; - - if ( VectorLength( tmpVec ) > maxRadius ) { - maxRadius = VectorLength( tmpVec ); - } - } - - g_data.frames[i].radius = LittleFloat( maxRadius ); - - // swap - for ( j = 0 ; j < 3 ; j++ ) { - g_data.frames[i].bounds[0][j] = LittleFloat( g_data.frames[i].bounds[0][j] ); - g_data.frames[i].bounds[1][j] = LittleFloat( g_data.frames[i].bounds[1][j] ); - g_data.frames[i].localOrigin[j] = LittleFloat( g_data.frames[i].localOrigin[j] ); - } - } - fseek( modelouthandle, g_data.model.ofsFrames, SEEK_SET ); - SafeWrite( modelouthandle, g_data.frames, numFrames * sizeof( g_data.frames[0] ) ); - - // - // write out the tags - // - fseek( modelouthandle, g_data.model.ofsTags, SEEK_SET ); - for ( f = 0 ; f < g_data.model.numFrames; f++ ) - { - int t; - - for ( t = 0; t < g_data.model.numTags; t++ ) - { - g_data.tags[f][t].origin[0] = LittleFloat( g_data.tags[f][t].origin[0] ); - g_data.tags[f][t].origin[1] = LittleFloat( g_data.tags[f][t].origin[1] ); - g_data.tags[f][t].origin[2] = LittleFloat( g_data.tags[f][t].origin[2] ); - - for ( j = 0 ; j < 3 ; j++ ) - { - g_data.tags[f][t].axis[0][j] = LittleFloat( g_data.tags[f][t].axis[0][j] ); - g_data.tags[f][t].axis[1][j] = LittleFloat( g_data.tags[f][t].axis[1][j] ); - g_data.tags[f][t].axis[2][j] = LittleFloat( g_data.tags[f][t].axis[2][j] ); - } - } - SafeWrite( modelouthandle, g_data.tags[f], g_data.model.numTags * sizeof( md3Tag_t ) ); - } - - // - // write out the surfaces - // - fseek( modelouthandle, g_data.model.ofsSurfaces, SEEK_SET ); - for ( i = 0; i < g_data.model.numSurfaces; i++ ) - { - WriteModelSurface( modelouthandle, &g_data.surfData[i] ); - } -} - - -/* - =============== - FinishModel - =============== - */ -void FinishModel( int type ){ - FILE *modelouthandle; - FILE *defaultSkinHandle; - char name[1024]; - int i; - - if ( !g_data.model.numFrames ) { - return; - } - - // - // build generalized triangle strips - // - OrderSurfaces(); - - if ( type == TYPE_PLAYER ) { - sprintf( name, "%s%s", writedir, g_modelname ); - *strrchr( name, '.' ) = 0; - strcat( name, "_default.skin" ); - - defaultSkinHandle = fopen( name, "wt" ); - for ( i = 0; i < g_data.model.numSurfaces; i++ ) - { - fprintf( defaultSkinHandle, "%s,%s\n", g_data.surfData[i].header.name, g_data.surfData[i].shaders[0].name ); - } - fclose( defaultSkinHandle ); - } - - sprintf( name, "%s%s", writedir, g_modelname ); - - // - // copy the model and its shaders to release directory tree - // if doing a release build - // - if ( g_release ) { - int i, j; - md3SurfaceData_t *pSurf; - - ReleaseFile( g_modelname ); - - for ( i = 0; i < g_data.model.numSurfaces; i++ ) { - pSurf = &g_data.surfData[i]; - for ( j = 0; j < g_data.model.numSkins; j++ ) { - ReleaseShader( pSurf->shaders[j].name ); - } - } - return; - } - - // - // write the model output file - // - printf( "saving to %s\n", name ); - CreatePath( name ); - modelouthandle = SafeOpenWrite( name ); - - WriteModelFile( modelouthandle ); - - printf( "%4d surfaces\n", g_data.model.numSurfaces ); - printf( "%4d frames\n", g_data.model.numFrames ); - printf( "%4d tags\n", g_data.model.numTags ); - printf( "file size: %d\n", (int)ftell( modelouthandle ) ); - printf( "---------------------\n" ); - - fclose( modelouthandle ); -} - -/* -** OrderSurfaces -** -** Reorders triangles in all the surfaces. -*/ -static void OrderSurfaces( void ){ - int s; - extern qboolean g_stripify; - - // go through each surface and find best strip/fans possible - for ( s = 0; s < g_data.model.numSurfaces; s++ ) - { - int mesh[MD3_MAX_TRIANGLES][3]; - int i; - - printf( "stripifying surface %d/%d with %d tris\n", s, g_data.model.numSurfaces, g_data.surfData[s].header.numTriangles ); - - for ( i = 0; i < g_data.surfData[s].header.numTriangles; i++ ) - { - mesh[i][0] = g_data.surfData[s].lodTriangles[i][0]; - mesh[i][1] = g_data.surfData[s].lodTriangles[i][1]; - mesh[i][2] = g_data.surfData[s].lodTriangles[i][2]; - } - - if ( g_stripify ) { - OrderMesh( mesh, // input - g_data.surfData[s].orderedTriangles, // output - g_data.surfData[s].header.numTriangles ); - } - else - { - memcpy( g_data.surfData[s].orderedTriangles, mesh, sizeof( int ) * 3 * g_data.surfData[s].header.numTriangles ); - } - } -} - - -/* - =============================================================== - - BASE FRAME SETUP - - =============================================================== - */ -/* - ============ - CopyTrianglesToBaseTriangles - - ============ - */ -static void CopyTrianglesToBaseTriangles( triangle_t *ptri, int numtri, baseTriangle_t *bTri ){ - int i; -// int width, height, iwidth, iheight, swidth; -// float s_scale, t_scale; -// float scale; -// vec3_t mins, maxs; - float *pbasevert; - -/* - // - // find bounds of all the verts on the base frame - // - ClearBounds (mins, maxs); - - for (i=0 ; i= 150) - scale = 150.0 / width; - if (height*scale >= 190) - scale = 190.0 / height; - - s_scale = t_scale = scale; - - iwidth = ceil(width*s_scale); - iheight = ceil(height*t_scale); - - iwidth += 4; - iheight += 4; - } - else - { // new style - iwidth = g_data.fixedwidth / 2; - iheight = g_data.fixedheight; - - s_scale = (float)(iwidth-4) / width; - t_scale = (float)(iheight-4) / height; - } - - // make the width a multiple of 4; some hardware requires this, and it ensures - // dword alignment for each scan - swidth = iwidth*2; - g_data.skinwidth = (swidth + 3) & ~3; - g_data.skinheight = iheight; - */ - - for ( i = 0; i < numtri ; i++, ptri++, bTri++ ) - { - int j; - - for ( j = 0 ; j < 3 ; j++ ) - { - pbasevert = ptri->verts[j]; - - VectorCopy( ptri->verts[j], bTri->v[j].xyz ); - VectorCopy( ptri->normals[j], bTri->v[j].normal ); - - bTri->v[j].st[0] = ptri->texcoords[j][0]; - bTri->v[j].st[1] = ptri->texcoords[j][1]; - } - } -} - -static void BuildBaseFrame( const char *filename, ObjectAnimationFrame_t *pOAF ){ - baseTriangle_t *bTri; - baseVertex_t *bVert; - int i, j; - - // calculate the base triangles - for ( i = 0; i < g_data.model.numSurfaces; i++ ) - { - CopyTrianglesToBaseTriangles( pOAF->surfaces[i]->triangles, - pOAF->surfaces[i]->numtriangles, - g_data.surfData[i].baseTriangles ); - - strcpy( g_data.surfData[i].header.name, pOAF->surfaces[i]->name ); - - g_data.surfData[i].header.numTriangles = pOAF->surfaces[i]->numtriangles; - g_data.surfData[i].header.numVerts = 0; - -/* - if ( strstr( filename, gamedir + 1 ) ) - { - strcpy( shaderName, strstr( filename, gamedir + 1 ) + strlen( gamedir ) - 1 ); - } - else - { - strcpy( shaderName, filename ); - } - - if ( strrchr( shaderName, '/' ) ) - *( strrchr( shaderName, '/' ) + 1 ) = 0; - - - strcpy( shaderName, pOAF->surfaces[i]->materialname ); - */ - strcpy( g_data.surfData[i].shaders[g_data.surfData[i].header.numShaders].name, pOAF->surfaces[i]->materialname ); - - g_data.surfData[i].header.numShaders++; - } - - // - // compute unique vertices for each polyset - // - for ( i = 0; i < g_data.model.numSurfaces; i++ ) - { - int t; - - for ( t = 0; t < pOAF->surfaces[i]->numtriangles; t++ ) - { - bTri = &g_data.surfData[i].baseTriangles[t]; - - for ( j = 0 ; j < 3 ; j++ ) - { - int k; - - bVert = &bTri->v[j]; - - // get the xyz index - for ( k = 0; k < g_data.surfData[i].header.numVerts; k++ ) - { - if ( ( g_data.surfData[i].baseVertexes[k].st[0] == bVert->st[0] ) && - ( g_data.surfData[i].baseVertexes[k].st[1] == bVert->st[1] ) && - ( VectorCompare( bVert->xyz, g_data.surfData[i].baseVertexes[k].xyz ) ) && - ( VectorCompare( bVert->normal, g_data.surfData[i].baseVertexes[k].normal ) ) ) { - break; // this vertex is already in the base vertex list - } - } - - if ( k == g_data.surfData[i].header.numVerts ) { // new index - g_data.surfData[i].baseVertexes[g_data.surfData[i].header.numVerts] = *bVert; - g_data.surfData[i].header.numVerts++; - } - - bVert->index = k; - - g_data.surfData[i].lodTriangles[t][j] = k; - } - } - } - - // - // find tags - // - for ( i = 0; i < g_data.model.numSurfaces; i++ ) - { - if ( strstr( pOAF->surfaces[i]->name, "tag_" ) == pOAF->surfaces[i]->name ) { - if ( pOAF->surfaces[i]->numtriangles != 1 ) { - Error( "tag polysets must consist of only one triangle" ); - } - if ( strstr( filename, "_flash.md3" ) && !strcmp( pOAF->surfaces[i]->name, "tag_parent" ) ) { - continue; - } - printf( "found tag '%s'\n", pOAF->surfaces[i]->name ); - g_data.model.numTags++; - } - } - -} - -static int LoadModelFile( const char *filename, polyset_t **psets, int *numpolysets ){ - int time1; - char file1[1024]; - const char *frameFile; - - printf( "---------------------\n" ); - if ( filename[1] != ':' ) { - frameFile = filename; - sprintf( file1, "%s/%s", g_cddir, frameFile ); - } - else - { - strcpy( file1, filename ); - } - - time1 = FileTime( file1 ); - if ( time1 == -1 ) { - Error( "%s doesn't exist", file1 ); - } - - // - // load the base triangles - // - *psets = Polyset_LoadSets( file1, numpolysets, g_data.maxSurfaceTris ); - - // - // snap polysets - // - Polyset_SnapSets( *psets, *numpolysets ); - - if ( strstr( file1, ".3ds" ) || strstr( file1, ".3DS" ) ) { - return MD3_TYPE_BASE3DS; - } - - Error( "Unknown model file type" ); - - return MD3_TYPE_UNKNOWN; -} - -/* - ================= - Cmd_Base - ================= - */ -void Cmd_Base( void ){ - char filename[1024]; - - GetToken( qfalse ); - sprintf( filename, "%s/%s", g_cddir, token ); - LoadBase( filename ); -} - -static void LoadBase( const char *filename ){ - int numpolysets; - polyset_t *psets; - int i; - ObjectAnimationFrame_t oaf; - - // determine polyset splitting threshold - if ( TokenAvailable() ) { - GetToken( qfalse ); - g_data.maxSurfaceTris = atoi( token ); - } - else - { - g_data.maxSurfaceTris = MAX_SURFACE_TRIS - 1; - } - - g_data.type = LoadModelFile( filename, &psets, &numpolysets ); - - Polyset_ComputeNormals( psets, numpolysets ); - - g_data.model.numSurfaces = numpolysets; - - memset( &oaf, 0, sizeof( oaf ) ); - - for ( i = 0; i < numpolysets; i++ ) - { - oaf.surfaces[i] = &psets[i]; - oaf.numSurfaces = numpolysets; - } - - BuildBaseFrame( filename, &oaf ); - - free( psets[0].triangles ); - free( psets ); -} - -/* - ================= - Cmd_SpriteBase - - $spritebase xorg yorg width height - - Generate a single square for the model - ================= - */ -void Cmd_SpriteBase( void ){ - float xl, yl, width, height; - - g_data.type = MD3_TYPE_SPRITE; - - GetToken( qfalse ); - xl = atof( token ); - GetToken( qfalse ); - yl = atof( token ); - GetToken( qfalse ); - width = atof( token ); - GetToken( qfalse ); - height = atof( token ); - -// if (g_skipmodel || g_release || g_archive) -// return; - - printf( "---------------------\n" ); - - g_data.surfData[0].verts[0] = ( float * ) calloc( 1, sizeof( float ) * 6 * 4 ); - - g_data.surfData[0].header.numVerts = 4; - - g_data.surfData[0].verts[0][0 + 0] = 0; - g_data.surfData[0].verts[0][0 + 1] = -xl; - g_data.surfData[0].verts[0][0 + 2] = yl + height; - - g_data.surfData[0].verts[0][0 + 3] = -1; - g_data.surfData[0].verts[0][0 + 4] = 0; - g_data.surfData[0].verts[0][0 + 5] = 0; - g_data.surfData[0].baseVertexes[0].st[0] = 0; - g_data.surfData[0].baseVertexes[0].st[1] = 0; - - - g_data.surfData[0].verts[0][6 + 0] = 0; - g_data.surfData[0].verts[0][6 + 1] = -xl - width; - g_data.surfData[0].verts[0][6 + 2] = yl + height; - - g_data.surfData[0].verts[0][6 + 3] = -1; - g_data.surfData[0].verts[0][6 + 4] = 0; - g_data.surfData[0].verts[0][6 + 5] = 0; - g_data.surfData[0].baseVertexes[1].st[0] = 1; - g_data.surfData[0].baseVertexes[1].st[1] = 0; - - - g_data.surfData[0].verts[0][12 + 0] = 0; - g_data.surfData[0].verts[0][12 + 1] = -xl - width; - g_data.surfData[0].verts[0][12 + 2] = yl; - - g_data.surfData[0].verts[0][12 + 3] = -1; - g_data.surfData[0].verts[0][12 + 4] = 0; - g_data.surfData[0].verts[0][12 + 5] = 0; - g_data.surfData[0].baseVertexes[2].st[0] = 1; - g_data.surfData[0].baseVertexes[2].st[1] = 1; - - - g_data.surfData[0].verts[0][18 + 0] = 0; - g_data.surfData[0].verts[0][18 + 1] = -xl; - g_data.surfData[0].verts[0][18 + 2] = yl; - - g_data.surfData[0].verts[0][18 + 3] = -1; - g_data.surfData[0].verts[0][18 + 4] = 0; - g_data.surfData[0].verts[0][18 + 5] = 0; - g_data.surfData[0].baseVertexes[3].st[0] = 0; - g_data.surfData[0].baseVertexes[3].st[1] = 1; - - g_data.surfData[0].lodTriangles[0][0] = 0; - g_data.surfData[0].lodTriangles[0][1] = 1; - g_data.surfData[0].lodTriangles[0][2] = 2; - - g_data.surfData[0].lodTriangles[1][0] = 2; - g_data.surfData[0].lodTriangles[1][1] = 3; - g_data.surfData[0].lodTriangles[1][2] = 0; - - g_data.model.numSurfaces = 1; - - g_data.surfData[0].header.numTriangles = 2; - g_data.surfData[0].header.numVerts = 4; - - g_data.model.numFrames = 1; -} - -/* - =========================================================================== - - FRAME GRABBING - - =========================================================================== - */ - -/* - =============== - GrabFrame - =============== - */ -void GrabFrame( const char *frame ){ - int i, j, k; - char file1[1024]; - md3Frame_t *fr; - md3Tag_t tagParent; - float *frameXyz; - float *frameNormals; - const char *framefile; - polyset_t *psets; - qboolean parentTagExists = qfalse; - int numpolysets; - int numtags = 0; - int tagcount; - - // the frame 'run1' will be looked for as either - // run.1 or run1.tri, so the new alias sequence save - // feature an be used - if ( frame[1] != ':' ) { -// framefile = FindFrameFile (frame); - framefile = frame; - sprintf( file1, "%s/%s",g_cddir, framefile ); - } - else - { - strcpy( file1, frame ); - } - printf( "grabbing %s\n", file1 ); - - if ( g_data.model.numFrames >= MD3_MAX_FRAMES ) { - Error( "model.numFrames >= MD3_MAX_FRAMES" ); - } - fr = &g_data.frames[g_data.model.numFrames]; - - strcpy( fr->name, frame ); - - psets = Polyset_LoadSets( file1, &numpolysets, g_data.maxSurfaceTris ); - - // - // snap polysets - // - Polyset_SnapSets( psets, numpolysets ); - - // - // compute vertex normals - // - Polyset_ComputeNormals( psets, numpolysets ); - - // - // flip everything to compensate for the alias coordinate system - // and perform global scale and adjust - // - for ( i = 0; i < g_data.model.numSurfaces; i++ ) - { - triangle_t *ptri = psets[i].triangles; - int t; - - for ( t = 0; t < psets[i].numtriangles; t++ ) - { - - for ( j = 0; j < 3; j++ ) - { - - // scale and adjust - for ( k = 0 ; k < 3 ; k++ ) { - ptri[t].verts[j][k] = ptri[t].verts[j][k] * g_data.scale_up + - g_data.adjust[k]; - - if ( ptri[t].verts[j][k] > 1023 || - ptri[t].verts[j][k] < -1023 ) { - Error( "Model extents too large" ); - } - } - } - } - } - - // - // find and count tags, locate parent tag - // - for ( i = 0; i < numpolysets; i++ ) - { - if ( strstr( psets[i].name, "tag_" ) == psets[i].name ) { - if ( strstr( psets[i].name, "tag_parent" ) == psets[i].name ) { - if ( strstr( psets[i].name, "tag_parent" ) ) { - float tri[3][3]; - - if ( parentTagExists ) { - Error( "Multiple parent tags not allowed" ); - } - - memcpy( tri[0], psets[i].triangles[0].verts[0], sizeof( float ) * 3 ); - memcpy( tri[1], psets[i].triangles[0].verts[1], sizeof( float ) * 3 ); - memcpy( tri[2], psets[i].triangles[0].verts[2], sizeof( float ) * 3 ); - - MD3_ComputeTagFromTri( &tagParent, tri ); - strcpy( tagParent.name, psets[i].name ); - g_data.tags[g_data.model.numFrames][numtags] = tagParent; - parentTagExists = qtrue; - - } - } - numtags++; - } - - if ( strcmp( psets[i].name, g_data.surfData[i].header.name ) ) { - Error( "Mismatched surfaces from base('%s') to frame('%s') in model '%s'\n", g_data.surfData[i].header.name, psets[i].name, g_modelname ); - } - } - - if ( numtags != g_data.model.numTags ) { - Error( "mismatched number of tags in frame(%d) vs. base(%d)", numtags, g_data.model.numTags ); - } - - if ( numpolysets != g_data.model.numSurfaces ) { - Error( "mismatched number of surfaces in frame(%d) vs. base(%d)", numpolysets - numtags, g_data.model.numSurfaces ); - } - - // - // prepare to accumulate bounds and normals - // - ClearBounds( fr->bounds[0], fr->bounds[1] ); - - // - // store the frame's vertices in the same order as the base. This assumes the - // triangles and vertices in this frame are in exactly the same order as in the - // base - // - for ( i = 0, tagcount = 0; i < numpolysets; i++ ) - { - int t; - triangle_t *pTris = psets[i].triangles; - - strcpy( g_data.surfData[i].header.name, psets[i].name ); - - // - // parent tag adjust - // - if ( parentTagExists ) { - for ( t = 0; t < psets[i].numtriangles; t++ ) - { - for ( j = 0; j < 3 ; j++ ) - { - vec3_t tmp; - - VectorSubtract( pTris[t].verts[j], tagParent.origin, tmp ); - - pTris[t].verts[j][0] = DotProduct( tmp, tagParent.axis[0] ); - pTris[t].verts[j][1] = DotProduct( tmp, tagParent.axis[1] ); - pTris[t].verts[j][2] = DotProduct( tmp, tagParent.axis[2] ); - - VectorCopy( pTris[t].normals[j], tmp ); - pTris[t].normals[j][0] = DotProduct( tmp, tagParent.axis[0] ); - pTris[t].normals[j][1] = DotProduct( tmp, tagParent.axis[1] ); - pTris[t].normals[j][2] = DotProduct( tmp, tagParent.axis[2] ); - } - } - } - - // - // compute tag data - // - if ( strstr( psets[i].name, "tag_" ) == psets[i].name ) { - md3Tag_t *pTag = &g_data.tags[g_data.model.numFrames][tagcount]; - float tri[3][3]; - - strcpy( pTag->name, psets[i].name ); - - memcpy( tri[0], pTris[0].verts[0], sizeof( float ) * 3 ); - memcpy( tri[1], pTris[0].verts[1], sizeof( float ) * 3 ); - memcpy( tri[2], pTris[0].verts[2], sizeof( float ) * 3 ); - - MD3_ComputeTagFromTri( pTag, tri ); - tagcount++; - } - else - { - if ( g_data.surfData[i].verts[g_data.model.numFrames] ) { - free( g_data.surfData[i].verts[g_data.model.numFrames] ); - } - frameXyz = g_data.surfData[i].verts[g_data.model.numFrames] = calloc( 1, sizeof( float ) * 6 * g_data.surfData[i].header.numVerts ); - frameNormals = frameXyz + 3; - - for ( t = 0; t < psets[i].numtriangles; t++ ) - { - for ( j = 0; j < 3 ; j++ ) - { - int index; - - index = g_data.surfData[i].baseTriangles[t].v[j].index; - frameXyz[index * 6 + 0] = pTris[t].verts[j][0]; - frameXyz[index * 6 + 1] = pTris[t].verts[j][1]; - frameXyz[index * 6 + 2] = pTris[t].verts[j][2]; - frameNormals[index * 6 + 0] = pTris[t].normals[j][0]; - frameNormals[index * 6 + 1] = pTris[t].normals[j][1]; - frameNormals[index * 6 + 2] = pTris[t].normals[j][2]; - AddPointToBounds( &frameXyz[index * 6], fr->bounds[0], fr->bounds[1] ); - } - } - } - } - - g_data.model.numFrames++; - - // only free the first triangle array, all of the psets in this array share the - // same triangle pool!!! -// free( psets[0].triangles ); -// free( psets ); -} - -//=========================================================================== - - - -/* - =============== - Cmd_Frame - =============== - */ -void Cmd_Frame( void ){ - while ( TokenAvailable() ) - { - GetToken( qfalse ); - if ( g_skipmodel ) { - continue; - } - if ( g_release || g_archive ) { - g_data.model.numFrames = 1; // don't skip the writeout - continue; - } - - GrabFrame( token ); - } -} - - -/* - =============== - Cmd_Skin - - =============== - */ -void SkinFrom3DS( const char *filename ){ - polyset_t *psets; - char name[1024]; - int numPolysets; - int i; - - _3DS_LoadPolysets( filename, &psets, &numPolysets, g_verbose ); - - for ( i = 0; i < numPolysets; i++ ) - { -/* - if ( strstr( filename, gamedir + 1 ) ) - { - strcpy( name, strstr( filename, gamedir + 1 ) + strlen( gamedir ) - 1 ); - } - else - { - strcpy( name, filename ); - } - - if ( strrchr( name, '/' ) ) - *( strrchr( name, '/' ) + 1 ) = 0; - */ - strcpy( name, psets[i].materialname ); - strcpy( g_data.surfData[i].shaders[g_data.surfData[i].header.numShaders].name, name ); - - g_data.surfData[i].header.numShaders++; - } - - free( psets[0].triangles ); - free( psets ); -} - -void Cmd_Skin( void ){ - char skinfile[1024]; - - if ( g_data.type == MD3_TYPE_BASE3DS ) { - GetToken( qfalse ); - - sprintf( skinfile, "%s/%s", g_cddir, token ); - - if ( strstr( token, ".3ds" ) || strstr( token, ".3DS" ) ) { - SkinFrom3DS( skinfile ); - } - else - { - Error( "Unknown file format for $skin '%s'\n", skinfile ); - } - } - else - { - Error( "invalid model type while processing $skin" ); - } - - g_data.model.numSkins++; -} - -/* - ================= - Cmd_SpriteShader - ================= - - This routine is also called for $oldskin - - */ -void Cmd_SpriteShader(){ - GetToken( qfalse ); - strcpy( g_data.surfData[0].shaders[g_data.surfData[0].header.numShaders].name, token ); - g_data.surfData[0].header.numShaders++; - g_data.model.numSkins++; -} - -/* - ================= - Cmd_Origin - ================= - */ -void Cmd_Origin( void ){ - // rotate points into frame of reference so model points down the - // positive x axis - // FIXME: use alias native coordinate system - GetToken( qfalse ); - g_data.adjust[1] = -atof( token ); - - GetToken( qfalse ); - g_data.adjust[0] = atof( token ); - - GetToken( qfalse ); - g_data.adjust[2] = -atof( token ); -} - - -/* - ================= - Cmd_ScaleUp - ================= - */ -void Cmd_ScaleUp( void ){ - GetToken( qfalse ); - g_data.scale_up = atof( token ); - if ( g_skipmodel || g_release || g_archive ) { - return; - } - - printf( "Scale up: %f\n", g_data.scale_up ); -} - - -/* - ================= - Cmd_Skinsize - - Set a skin size other than the default - QUAKE3: not needed - ================= - */ -void Cmd_Skinsize( void ){ - GetToken( qfalse ); - g_data.fixedwidth = atoi( token ); - GetToken( qfalse ); - g_data.fixedheight = atoi( token ); -} - -/* - ================= - Cmd_Modelname - - Begin creating a model of the given name - ================= - */ -void Cmd_Modelname( void ){ - FinishModel( TYPE_UNKNOWN ); - ClearModel(); - - GetToken( qfalse ); - strcpy( g_modelname, token ); - StripExtension( g_modelname ); - strcat( g_modelname, ".md3" ); - strcpy( g_data.model.name, g_modelname ); -} - -/* - =============== - fCmd_Cd - =============== - */ -void Cmd_Cd( void ){ - if ( g_cddir[0] ) { - Error( "$cd command without a $modelname" ); - } - - GetToken( qfalse ); - - sprintf( g_cddir, "%s%s", gamedir, token ); - - // if -only was specified and this cd doesn't match, - // skip the model (you only need to match leading chars, - // so you could regrab all monsters with -only models/monsters) - if ( !g_only[0] ) { - return; - } - if ( strncmp( token, g_only, strlen( g_only ) ) ) { - g_skipmodel = qtrue; - printf( "skipping %s\n", token ); - } -} - -void Convert3DStoMD3( const char *file ){ - LoadBase( file ); - GrabFrame( file ); - SkinFrom3DS( file ); - - strcpy( g_data.model.name, g_modelname ); - - FinishModel( TYPE_UNKNOWN ); - ClearModel(); -} - -/* -** Cmd_3DSConvert -*/ -void Cmd_3DSConvert(){ - char file[1024]; - - FinishModel( TYPE_UNKNOWN ); - ClearModel(); - - GetToken( qfalse ); - - sprintf( file, "%s%s", gamedir, token ); - strcpy( g_modelname, token ); - if ( strrchr( g_modelname, '.' ) ) { - *strrchr( g_modelname, '.' ) = 0; - } - strcat( g_modelname, ".md3" ); - - if ( FileTime( file ) == -1 ) { - Error( "%s doesn't exist", file ); - } - - if ( TokenAvailable() ) { - GetToken( qfalse ); - g_data.scale_up = atof( token ); - } - - Convert3DStoMD3( file ); -} - -static void ConvertASE( const char *filename, int type, qboolean grabAnims ); - -/* -** Cmd_ASEConvert -*/ -void Cmd_ASEConvert( qboolean grabAnims ){ - char filename[1024]; - int type = TYPE_ITEM; - - FinishModel( TYPE_UNKNOWN ); - ClearModel(); - - GetToken( qfalse ); - sprintf( filename, "%s%s", gamedir, token ); - - strcpy( g_modelname, token ); - StripExtension( g_modelname ); - strcat( g_modelname, ".md3" ); - strcpy( g_data.model.name, g_modelname ); - - if ( !strstr( filename, ".ase" ) && !strstr( filename, ".ASE" ) ) { - strcat( filename, ".ASE" ); - } - - g_data.maxSurfaceTris = MAX_SURFACE_TRIS - 1; - - while ( TokenAvailable() ) - { - GetToken( qfalse ); - if ( !strcmp( token, "-origin" ) ) { - if ( !TokenAvailable() ) { - Error( "missing parameter for -origin" ); - } - GetToken( qfalse ); - g_data.aseAdjust[1] = -atof( token ); - - if ( !TokenAvailable() ) { - Error( "missing parameter for -origin" ); - } - GetToken( qfalse ); - g_data.aseAdjust[0] = atof( token ); - - if ( !TokenAvailable() ) { - Error( "missing parameter for -origin" ); - } - GetToken( qfalse ); - g_data.aseAdjust[2] = -atof( token ); - } - else if ( !strcmp( token, "-lod" ) ) { - if ( !TokenAvailable() ) { - Error( "No parameter for -lod" ); - } - GetToken( qfalse ); - g_data.currentLod = atoi( token ); - if ( g_data.currentLod > MD3_MAX_LODS - 1 ) { - Error( "-lod parameter too large! (%d)\n", g_data.currentLod ); - } - - if ( !TokenAvailable() ) { - Error( "No second parameter for -lod" ); - } - GetToken( qfalse ); - g_data.lodBias = atof( token ); - } - else if ( !strcmp( token, "-maxtris" ) ) { - if ( !TokenAvailable() ) { - Error( "No parameter for -maxtris" ); - } - GetToken( qfalse ); - g_data.maxSurfaceTris = atoi( token ); - } - else if ( !strcmp( token, "-playerparms" ) ) { - if ( !TokenAvailable() ) { - Error( "missing skip start parameter for -playerparms" ); - } - GetToken( qfalse ); - g_data.lowerSkipFrameStart = atoi( token ); - -#if 0 - if ( !TokenAvailable() ) { - Error( "missing skip end parameter for -playerparms" ); - } - GetToken( qfalse ); - g_data.lowerSkipFrameEnd = atoi( token ); -#endif - - if ( !TokenAvailable() ) { - Error( "missing upper parameter for -playerparms" ); - } - GetToken( qfalse ); - g_data.maxUpperFrames = atoi( token ); - - g_data.lowerSkipFrameEnd = g_data.maxUpperFrames - 1; - -#if 0 - if ( !TokenAvailable() ) { - Error( "missing head parameter for -playerparms" ); - } - GetToken( qfalse ); - g_data.maxHeadFrames = atoi( token ); -#endif - g_data.maxHeadFrames = 1; - - if ( type != TYPE_ITEM ) { - Error( "invalid argument" ); - } - - type = TYPE_PLAYER; - } - else if ( !strcmp( token, "-weapon" ) ) { - if ( type != TYPE_ITEM ) { - Error( "invalid argument" ); - } - - type = TYPE_WEAPON; - } - } - - g_data.type = MD3_TYPE_ASE; - - if ( type == TYPE_WEAPON && grabAnims ) { - Error( "can't grab anims with weapon models" ); - } - if ( type == TYPE_PLAYER && !grabAnims ) { - Error( "player models must be converted with $aseanimconvert" ); - } - - if ( type == TYPE_WEAPON ) { - ConvertASE( filename, type, qfalse ); - ConvertASE( filename, TYPE_HAND, qtrue ); - } - else - { - ConvertASE( filename, type, grabAnims ); - } -} - -static int GetSurfaceAnimations( SurfaceAnimation_t sanims[MAX_ANIM_SURFACES], - const char *part, - int skipFrameStart, - int skipFrameEnd, - int maxFrames ){ - int numSurfaces; - int numValidSurfaces; - int i; - int numFrames = -1; - - if ( ( numSurfaces = ASE_GetNumSurfaces() ) > MAX_ANIM_SURFACES ) { - Error( "Too many surfaces in ASE" ); - } - - for ( numValidSurfaces = 0, i = 0; i < numSurfaces; i++ ) - { - polyset_t *splitSets; - int numNewFrames; - const char *surfaceName = ASE_GetSurfaceName( i ); - - if ( !surfaceName ) { - continue; -// Error( "Missing animation frames in model" ); - } - - if ( strstr( surfaceName, "tag_" ) || - !strcmp( part, "any" ) || - ( strstr( surfaceName, part ) == surfaceName ) ) { - - // skip this if it's an inappropriate tag - if ( strcmp( part, "any" ) ) { - // ignore non-"tag_head" tags if this is the head - if ( !strcmp( part, "h_" ) && strstr( surfaceName, "tag_" ) && strcmp( surfaceName, "tag_head" ) ) { - continue; - } - // ignore "tag_head" if this is the legs - if ( !strcmp( part, "l_" ) && !strcmp( surfaceName, "tag_head" ) ) { - continue; - } - // ignore "tag_weapon" if this is the legs - if ( !strcmp( part, "l_" ) && !strcmp( surfaceName, "tag_weapon" ) ) { - continue; - } - } - - if ( ( sanims[numValidSurfaces].frames = ASE_GetSurfaceAnimation( i, &sanims[numValidSurfaces].numFrames, skipFrameStart, skipFrameEnd, maxFrames ) ) != 0 ) { - splitSets = Polyset_SplitSets( sanims[numValidSurfaces].frames, sanims[numValidSurfaces].numFrames, &numNewFrames, g_data.maxSurfaceTris ); - - if ( numFrames == -1 ) { - numFrames = sanims[numValidSurfaces].numFrames; - } - else if ( numFrames != sanims[numValidSurfaces].numFrames ) { - Error( "Different number of animation frames on surfaces" ); - } - - if ( sanims[numValidSurfaces].frames != splitSets ) { - int j; - - // free old data if we split the surfaces - for ( j = 0; j < sanims[numValidSurfaces].numFrames; j++ ) - { - free( sanims[numValidSurfaces].frames[j].triangles ); - free( sanims[numValidSurfaces].frames ); - } - - sanims[numValidSurfaces].frames = splitSets; - sanims[numValidSurfaces].numFrames = numNewFrames; - } - Polyset_SnapSets( sanims[numValidSurfaces].frames, sanims[numValidSurfaces].numFrames ); - Polyset_ComputeNormals( sanims[numValidSurfaces].frames, sanims[numValidSurfaces].numFrames ); - - numValidSurfaces++; - } - } - } - - return numValidSurfaces; -} - -static int SurfaceOrderToFrameOrder( SurfaceAnimation_t sanims[], ObjectAnimationFrame_t oanims[], int numSurfaces ){ - int i, s; - int numFrames = -1; - - /* - ** we have the data here arranged in surface order, now we need to convert it to - ** frame order - */ - for ( i = 0, s = 0; i < numSurfaces; i++ ) - { - int j; - - if ( sanims[i].frames ) { - if ( numFrames == -1 ) { - numFrames = sanims[i].numFrames; - } - else if ( numFrames != sanims[i].numFrames ) { - Error( "numFrames != sanims[i].numFrames (%d != %d)\n", numFrames, sanims[i].numFrames ); - } - - for ( j = 0; j < sanims[i].numFrames; j++ ) - { - oanims[j].surfaces[s] = &sanims[i].frames[j]; - oanims[j].numSurfaces = numSurfaces; - } - s++; - } - } - - return numFrames; -} - -static void WriteMD3( const char *_filename, ObjectAnimationFrame_t oanims[], int numFrames ){ - char filename[1024]; - - strcpy( filename, _filename ); - if ( strchr( filename, '.' ) ) { - *strchr( filename, '.' ) = 0; - } - strcat( filename, ".md3" ); -} - -static void BuildAnimationFromOAFs( const char *filename, ObjectAnimationFrame_t oanims[], int numFrames, int type ){ - int f, i, j, tagcount; - float *frameXyz; - float *frameNormals; - - g_data.model.numSurfaces = oanims[0].numSurfaces; - g_data.model.numFrames = numFrames; - if ( g_data.model.numFrames < 0 ) { - Error( "model.numFrames < 0" ); - } - if ( g_data.model.numFrames >= MD3_MAX_FRAMES ) { - Error( "model.numFrames >= MD3_MAX_FRAMES" ); - } - - // build base frame - BuildBaseFrame( filename, &oanims[0] ); - - // build animation frames - for ( f = 0; f < numFrames; f++ ) - { - ObjectAnimationFrame_t *pOAF = &oanims[f]; - qboolean parentTagExists = qfalse; - md3Tag_t tagParent; - int numtags = 0; - md3Frame_t *fr; - - fr = &g_data.frames[f]; - - strcpy( fr->name, "(from ASE)" ); - - // scale and adjust frame - for ( i = 0; i < pOAF->numSurfaces; i++ ) - { - triangle_t *pTris = pOAF->surfaces[i]->triangles; - int t; - - for ( t = 0; t < pOAF->surfaces[i]->numtriangles; t++ ) - { - for ( j = 0; j < 3; j++ ) - { - int k; - - // scale and adjust - for ( k = 0 ; k < 3 ; k++ ) { - pTris[t].verts[j][k] = pTris[t].verts[j][k] * g_data.scale_up + - g_data.aseAdjust[k]; - - if ( pTris[t].verts[j][k] > 1023 || - pTris[t].verts[j][k] < -1023 ) { - Error( "Model extents too large" ); - } - } - } - } - } - - // - // find and count tags, locate parent tag - // - for ( i = 0; i < pOAF->numSurfaces; i++ ) - { - if ( strstr( pOAF->surfaces[i]->name, "tag_" ) == pOAF->surfaces[i]->name ) { - // ignore parent tags when grabbing a weapon model and this is the flash portion - if ( !strcmp( pOAF->surfaces[i]->name, "tag_parent" ) && strstr( filename, "_flash.md3" ) ) { - continue; - } - else if ( !strstr( filename, "_hand.md3" ) && ( - ( !strcmp( pOAF->surfaces[i]->name, "tag_parent" ) && !strstr( filename, "_flash.md3" ) ) || - ( !strcmp( pOAF->surfaces[i]->name, "tag_torso" ) && ( strstr( filename, "upper_" ) || strstr( filename, "upper.md3" ) ) ) || - ( !strcmp( pOAF->surfaces[i]->name, "tag_head" ) && ( strstr( filename, "head.md3" ) || strstr( filename, "head_" ) ) ) || - ( !strcmp( pOAF->surfaces[i]->name, "tag_flash" ) && strstr( filename, "_flash.md3" ) ) || - ( !strcmp( pOAF->surfaces[i]->name, "tag_weapon" ) && type == TYPE_WEAPON ) ) ) { - float tri[3][3]; - - if ( parentTagExists ) { - Error( "Multiple parent tags not allowed" ); - } - - memcpy( tri[0], pOAF->surfaces[i]->triangles[0].verts[0], sizeof( float ) * 3 ); - memcpy( tri[1], pOAF->surfaces[i]->triangles[0].verts[1], sizeof( float ) * 3 ); - memcpy( tri[2], pOAF->surfaces[i]->triangles[0].verts[2], sizeof( float ) * 3 ); - - MD3_ComputeTagFromTri( &tagParent, tri ); - strcpy( tagParent.name, "tag_parent" ); - g_data.tags[f][numtags] = tagParent; - parentTagExists = qtrue; - } - else - { - float tri[3][3]; - - memcpy( tri[0], pOAF->surfaces[i]->triangles[0].verts[0], sizeof( float ) * 3 ); - memcpy( tri[1], pOAF->surfaces[i]->triangles[0].verts[1], sizeof( float ) * 3 ); - memcpy( tri[2], pOAF->surfaces[i]->triangles[0].verts[2], sizeof( float ) * 3 ); - - MD3_ComputeTagFromTri( &g_data.tags[f][numtags], tri ); - strcpy( g_data.tags[f][numtags].name, pOAF->surfaces[i]->name ); - if ( strstr( g_data.tags[f][numtags].name, "tag_flash" ) ) { - *( strstr( g_data.tags[f][numtags].name, "tag_flash" ) + strlen( "tag_flash" ) ) = 0; - } - } - - numtags++; - } - - if ( strcmp( pOAF->surfaces[i]->name, g_data.surfData[i].header.name ) ) { - Error( "Mismatched surfaces from base('%s') to frame('%s') in model '%s'\n", g_data.surfData[i].header.name, pOAF->surfaces[i]->name, filename ); - } - } - - if ( numtags != g_data.model.numTags ) { - Error( "mismatched number of tags in frame(%d) vs. base(%d)", numtags, g_data.model.numTags ); - } - - // - // prepare to accumulate bounds and normals - // - ClearBounds( fr->bounds[0], fr->bounds[1] ); - - // - // store the frame's vertices in the same order as the base. This assumes the - // triangles and vertices in this frame are in exactly the same order as in the - // base - // - for ( i = 0, tagcount = 0; i < pOAF->numSurfaces; i++ ) - { - int t; - triangle_t *pTris = pOAF->surfaces[i]->triangles; - - // - // parent tag adjust - // - if ( parentTagExists ) { - for ( t = 0; t < pOAF->surfaces[i]->numtriangles; t++ ) - { - for ( j = 0; j < 3 ; j++ ) - { - vec3_t tmp; - - VectorSubtract( pTris[t].verts[j], tagParent.origin, tmp ); - - pTris[t].verts[j][0] = DotProduct( tmp, tagParent.axis[0] ); - pTris[t].verts[j][1] = DotProduct( tmp, tagParent.axis[1] ); - pTris[t].verts[j][2] = DotProduct( tmp, tagParent.axis[2] ); - - VectorCopy( pTris[t].normals[j], tmp ); - pTris[t].normals[j][0] = DotProduct( tmp, tagParent.axis[0] ); - pTris[t].normals[j][1] = DotProduct( tmp, tagParent.axis[1] ); - pTris[t].normals[j][2] = DotProduct( tmp, tagParent.axis[2] ); - } - } - } - - // - // compute tag data - // - if ( strstr( pOAF->surfaces[i]->name, "tag_" ) == pOAF->surfaces[i]->name ) { - md3Tag_t *pTag = &g_data.tags[f][tagcount]; - float tri[3][3]; - - strcpy( pTag->name, pOAF->surfaces[i]->name ); - - memcpy( tri[0], pTris[0].verts[0], sizeof( float ) * 3 ); - memcpy( tri[1], pTris[0].verts[1], sizeof( float ) * 3 ); - memcpy( tri[2], pTris[0].verts[2], sizeof( float ) * 3 ); - - MD3_ComputeTagFromTri( pTag, tri ); - tagcount++; - } - else - { - if ( g_data.surfData[i].verts[f] ) { - free( g_data.surfData[i].verts[f] ); - } - frameXyz = g_data.surfData[i].verts[f] = calloc( 1, sizeof( float ) * 6 * g_data.surfData[i].header.numVerts ); - frameNormals = frameXyz + 3; - - for ( t = 0; t < pOAF->surfaces[i]->numtriangles; t++ ) - { - for ( j = 0; j < 3 ; j++ ) - { - int index; - - index = g_data.surfData[i].baseTriangles[t].v[j].index; - frameXyz[index * 6 + 0] = pTris[t].verts[j][0]; - frameXyz[index * 6 + 1] = pTris[t].verts[j][1]; - frameXyz[index * 6 + 2] = pTris[t].verts[j][2]; - frameNormals[index * 6 + 0] = pTris[t].normals[j][0]; - frameNormals[index * 6 + 1] = pTris[t].normals[j][1]; - frameNormals[index * 6 + 2] = pTris[t].normals[j][2]; - AddPointToBounds( &frameXyz[index * 6], fr->bounds[0], fr->bounds[1] ); - } - } - } - } - } - - if ( strstr( filename, gamedir + 1 ) ) { - strcpy( g_modelname, strstr( filename, gamedir + 1 ) + strlen( gamedir ) - 1 ); - } - else - { - strcpy( g_modelname, filename ); - } - - FinishModel( type ); - ClearModel(); -} - -static void ConvertASE( const char *filename, int type, qboolean grabAnims ){ - int i, j; - int numSurfaces; - int numFrames = -1; - SurfaceAnimation_t surfaceAnimations[MAX_ANIM_SURFACES]; - ObjectAnimationFrame_t objectAnimationFrames[MAX_ANIM_FRAMES]; - char outfilename[1024]; - - /* - ** load ASE into memory - */ - ASE_Load( filename, g_verbose, grabAnims ); - - /* - ** process parts - */ - if ( type == TYPE_ITEM ) { - numSurfaces = GetSurfaceAnimations( surfaceAnimations, "any", -1, -1, -1 ); - - if ( numSurfaces <= 0 ) { - Error( "numSurfaces <= 0" ); - } - - numFrames = SurfaceOrderToFrameOrder( surfaceAnimations, objectAnimationFrames, numSurfaces ); - - if ( numFrames <= 0 ) { - Error( "numFrames <= 0" ); - } - - strcpy( outfilename, filename ); - if ( strrchr( outfilename, '.' ) ) { - *( strrchr( outfilename, '.' ) + 1 ) = 0; - } - strcat( outfilename, "md3" ); - BuildAnimationFromOAFs( outfilename, objectAnimationFrames, numFrames, type ); - - // free memory - for ( i = 0; i < numSurfaces; i++ ) - { - if ( surfaceAnimations[i].frames ) { - for ( j = 0; j < surfaceAnimations[i].numFrames; j++ ) - { - free( surfaceAnimations[i].frames[j].triangles ); - } - free( surfaceAnimations[i].frames ); - surfaceAnimations[i].frames = 0; - } - } - } - else if ( type == TYPE_PLAYER ) { - qboolean tagTorso = qfalse; - qboolean tagHead = qfalse; - qboolean tagWeapon = qfalse; - - // - // verify that all necessary tags exist - // - numSurfaces = ASE_GetNumSurfaces(); - for ( i = 0; i < numSurfaces; i++ ) - { - if ( !strcmp( ASE_GetSurfaceName( i ), "tag_head" ) ) { - tagHead = qtrue; - } - if ( !strcmp( ASE_GetSurfaceName( i ), "tag_torso" ) ) { - tagTorso = qtrue; - } - if ( !strcmp( ASE_GetSurfaceName( i ), "tag_weapon" ) ) { - tagWeapon = qtrue; - } - } - - if ( !tagWeapon ) { - Error( "Missing tag_weapon!" ); - } - if ( !tagTorso ) { - Error( "Missing tag_torso!" ); - } - if ( !tagWeapon ) { - Error( "Missing tag_weapon!" ); - } - - // get all upper body surfaces - numSurfaces = GetSurfaceAnimations( surfaceAnimations, "u_", -1, -1, g_data.maxUpperFrames ); - numFrames = SurfaceOrderToFrameOrder( surfaceAnimations, objectAnimationFrames, numSurfaces ); - strcpy( outfilename, filename ); - if ( strrchr( outfilename, '/' ) ) { - *( strrchr( outfilename, '/' ) + 1 ) = 0; - } - - if ( g_data.currentLod == 0 ) { - strcat( outfilename, "upper.md3" ); - } - else - { - char temp[128]; - - sprintf( temp, "upper_%d.md3", g_data.currentLod ); - strcat( outfilename, temp ); - } - - BuildAnimationFromOAFs( outfilename, objectAnimationFrames, numFrames, type ); - - // free memory - for ( i = 0; i < numSurfaces; i++ ) - { - if ( surfaceAnimations[i].frames ) { - for ( j = 0; j < surfaceAnimations[i].numFrames; j++ ) - { - free( surfaceAnimations[i].frames[j].triangles ); - } - free( surfaceAnimations[i].frames ); - surfaceAnimations[i].frames = 0; - } - } - - // get lower body surfaces - numSurfaces = GetSurfaceAnimations( surfaceAnimations, "l_", g_data.lowerSkipFrameStart, g_data.lowerSkipFrameEnd, -1 ); - numFrames = SurfaceOrderToFrameOrder( surfaceAnimations, objectAnimationFrames, numSurfaces ); - strcpy( outfilename, filename ); - if ( strrchr( outfilename, '/' ) ) { - *( strrchr( outfilename, '/' ) + 1 ) = 0; - } - - if ( g_data.currentLod == 0 ) { - strcat( outfilename, "lower.md3" ); - } - else - { - char temp[128]; - - sprintf( temp, "lower_%d.md3", g_data.currentLod ); - strcat( outfilename, temp ); - } - BuildAnimationFromOAFs( outfilename, objectAnimationFrames, numFrames, type ); - - // free memory - for ( i = 0; i < numSurfaces; i++ ) - { - if ( surfaceAnimations[i].frames ) { - for ( j = 0; j < surfaceAnimations[i].numFrames; j++ ) - { - free( surfaceAnimations[i].frames[j].triangles ); - } - free( surfaceAnimations[i].frames ); - surfaceAnimations[i].frames = 0; - } - } - - // get head surfaces - numSurfaces = GetSurfaceAnimations( surfaceAnimations, "h_", -1, -1, g_data.maxHeadFrames ); - numFrames = SurfaceOrderToFrameOrder( surfaceAnimations, objectAnimationFrames, numSurfaces ); - strcpy( outfilename, filename ); - if ( strrchr( outfilename, '/' ) ) { - *( strrchr( outfilename, '/' ) + 1 ) = 0; - } - - if ( g_data.currentLod == 0 ) { - strcat( outfilename, "head.md3" ); - } - else - { - char temp[128]; - - sprintf( temp, "head_%d.md3", g_data.currentLod ); - strcat( outfilename, temp ); - } - BuildAnimationFromOAFs( outfilename, objectAnimationFrames, numFrames, type ); - - // free memory - for ( i = 0; i < numSurfaces; i++ ) - { - if ( surfaceAnimations[i].frames ) { - for ( j = 0; j < surfaceAnimations[i].numFrames; j++ ) - { - free( surfaceAnimations[i].frames[j].triangles ); - } - free( surfaceAnimations[i].frames ); - surfaceAnimations[i].frames = 0; - } - } - } - else if ( type == TYPE_WEAPON ) { - // get the weapon surfaces - numSurfaces = GetSurfaceAnimations( surfaceAnimations, "w_", -1, -1, -1 ); - numFrames = SurfaceOrderToFrameOrder( surfaceAnimations, objectAnimationFrames, numSurfaces ); - - strcpy( outfilename, filename ); - if ( strrchr( outfilename, '.' ) ) { - *( strrchr( outfilename, '.' ) + 1 ) = 0; - } - strcat( outfilename, "md3" ); - BuildAnimationFromOAFs( outfilename, objectAnimationFrames, numFrames, type ); - - // free memory - for ( i = 0; i < numSurfaces; i++ ) - { - if ( surfaceAnimations[i].frames ) { - for ( j = 0; j < surfaceAnimations[i].numFrames; j++ ) - { - free( surfaceAnimations[i].frames[j].triangles ); - } - free( surfaceAnimations[i].frames ); - surfaceAnimations[i].frames = 0; - } - } - - // get the flash surfaces - numSurfaces = GetSurfaceAnimations( surfaceAnimations, "f_", -1, -1, -1 ); - numFrames = SurfaceOrderToFrameOrder( surfaceAnimations, objectAnimationFrames, numSurfaces ); - - strcpy( outfilename, filename ); - if ( strrchr( outfilename, '.' ) ) { - *strrchr( outfilename, '.' ) = 0; - } - strcat( outfilename, "_flash.md3" ); - BuildAnimationFromOAFs( outfilename, objectAnimationFrames, numFrames, TYPE_ITEM ); - - // free memory - for ( i = 0; i < numSurfaces; i++ ) - { - if ( surfaceAnimations[i].frames ) { - for ( j = 0; j < surfaceAnimations[i].numFrames; j++ ) - { - free( surfaceAnimations[i].frames[j].triangles ); - } - free( surfaceAnimations[i].frames ); - surfaceAnimations[i].frames = 0; - } - } - } - else if ( type == TYPE_HAND ) { - // get the hand tags - numSurfaces = GetSurfaceAnimations( surfaceAnimations, "tag_", -1, -1, -1 ); - numFrames = SurfaceOrderToFrameOrder( surfaceAnimations, objectAnimationFrames, numSurfaces ); - - strcpy( outfilename, filename ); - if ( strrchr( outfilename, '.' ) ) { - *strrchr( outfilename, '.' ) = 0; - } - strcat( outfilename, "_hand.md3" ); - BuildAnimationFromOAFs( outfilename, objectAnimationFrames, numFrames, TYPE_HAND ); - - // free memory - for ( i = 0; i < numSurfaces; i++ ) - { - if ( surfaceAnimations[i].frames ) { - for ( j = 0; j < surfaceAnimations[i].numFrames; j++ ) - { - free( surfaceAnimations[i].frames[j].triangles ); - } - free( surfaceAnimations[i].frames ); - surfaceAnimations[i].frames = 0; - } - } - } - else - { - Error( "Unknown type passed to ConvertASE()" ); - } - - g_data.currentLod = 0; - g_data.lodBias = 0; - g_data.maxHeadFrames = 0; - g_data.maxUpperFrames = 0; - g_data.lowerSkipFrameStart = 0; - g_data.lowerSkipFrameEnd = 0; - VectorCopy( vec3_origin, g_data.aseAdjust ); - - // unload ASE from memory - ASE_Free(); -} diff --git a/tools/urt/tools/quake3/q3data/oldstuff.c b/tools/urt/tools/quake3/q3data/oldstuff.c deleted file mode 100644 index 8893831..0000000 --- a/tools/urt/tools/quake3/q3data/oldstuff.c +++ /dev/null @@ -1,126 +0,0 @@ -#if 0 - -/* -** ReindexTriangle -** -** Given a triangle_t, find which indices match into the associated -** surface's base triangles. -*/ -static void ReindexTriangle( int surfno, triangle_t *pTri, int indices[3] ){ - int t, i; - md3SurfaceData_t *pSurfData = &g_data.surfData[surfno]; - int matches[3][3]; - int numMatches = 0; - - - indices[0] = -1; - indices[1] = -1; - indices[2] = -1; - - for ( i = 0; i < 3; i++ ) - { - numMatches = 0; - - matches[i][0] = -1; - matches[i][1] = -1; - matches[i][2] = -1; - - for ( t = 0; t < pSurfData->header.numVerts; t++ ) - { - if ( !VectorCompare( pTri->verts[i], pSurfData->baseVertexes[t].xyz ) ) { - continue; - } - -/* - if ( !VectorCompare( pTri->normals[i], pSurfData->baseVertexes[t].normal ) ) - continue; - if ( pTri->texcoords[i][0] != pSurfData->baseVertexes[t].st[0] ) - continue; - if ( pTri->texcoords[i][1] != pSurfData->baseVertexes[t].st[1] ) - continue; - */ - - matches[i][numMatches++] = t; - } - - if ( indices[i] == -1 ) { -// Error( "Could not ReindexTriangle, vertex not found" ); - } - } - -#if 0 - for ( t = 0; t < psets[i].numtriangles; t++ ) - { - int b; - - bTri = &g_data.surfData[i].baseTriangles[t]; - - for ( j = 0 ; j < 3 ; j++ ) - { - bVert = &bTri->v[j]; - - // get the xyz index - for ( k = 0; k < g_data.surfData[i].header.numVerts; k++ ) - { - if ( ( g_data.surfData[i].baseVertexes[k].st[0] == bVert->st[0] ) && - ( g_data.surfData[i].baseVertexes[k].st[1] == bVert->st[1] ) && - ( VectorCompare( bVert->xyz, g_data.surfData[i].baseVertexes[k].xyz ) ) && - ( VectorCompare( bVert->normal, g_data.surfData[i].baseVertexes[k].normal ) ) ) { - break; // this vertex is already in the base vertex list - } - } - - if ( k == g_data.surfData[i].header.numVerts ) { // new index - g_data.surfData[i].baseVertexes[g_data.surfData[i].header.numVerts] = *bVert; - g_data.surfData[i].header.numVerts++; - } - - bVert->index = k; - } - } -#endif -} - -const char *FindFrameFile( const char *frame ){ - int time1; - char file1[1024]; - static char retname[1024]; - char base[32]; - char suffix[32]; - const char *s; - - if ( strstr( frame, "." ) ) { - return frame; // allready in dot format - - } - // split 'run1' into 'run' and '1' - s = frame + strlen( frame ) - 1; - - while ( s != frame && *s >= '0' && *s <= '9' ) - s--; - - strcpy( suffix, s + 1 ); - strcpy( base, frame ); - base[s - frame + 1] = 0; - - // check for 'run1.tri' - sprintf( file1, "%s/%s%s.tri", g_cddir, base, suffix ); - time1 = FileTime( file1 ); - if ( time1 != -1 ) { - sprintf( retname, "%s%s.tri", base, suffix ); - return retname; - } - - // check for 'run.1' - sprintf( file1, "%s/%s.%s",g_cddir, base, suffix ); - time1 = FileTime( file1 ); - if ( time1 != -1 ) { - sprintf( retname, "%s.%s", base, suffix ); - return retname; - } - - Error( "frame %s could not be found",frame ); - return NULL; -} - -#endif diff --git a/tools/urt/tools/quake3/q3data/p3dlib.c b/tools/urt/tools/quake3/q3data/p3dlib.c deleted file mode 100644 index f251722..0000000 --- a/tools/urt/tools/quake3/q3data/p3dlib.c +++ /dev/null @@ -1,313 +0,0 @@ -#include "p3dlib.h" - -#ifdef WIN32 -#include -#endif -#include -#include -#include - -#define MAX_POLYSETS 64 - -#if defined ( __linux__ ) || defined ( __APPLE__ ) -#define _strcmpi Q_stricmp -#define filelength Q_filelength -#define strlwr strlower -#endif -typedef struct -{ - long len; - - int numPairs; - char polysetNames[MAX_POLYSETS][256]; - char shaders[MAX_POLYSETS][256]; - - char *buffer, *curpos; -} p3d_t; - -static p3d_t p3d; - -static int P3DProcess(); -static int P3DGetToken( int restOfLine ); - -static char s_token[1024]; -static int s_curpair; - -/* -** P3DLoad -** -*/ -int P3DLoad( const char *filename ){ - FILE *fp = fopen( filename, "rb" ); - - if ( !fp ) { - return 0; - } - - memset( &p3d, 0, sizeof( p3d ) ); - - p3d.len = filelength( fileno( fp ) ); - - p3d.curpos = p3d.buffer = malloc( p3d.len ); - - if ( fread( p3d.buffer, p3d.len, 1, fp ) != 1 ) { - fclose( fp ); - return 0; - } - - fclose( fp ); - - return P3DProcess(); -} - -/* -** P3DClose -** -*/ -void P3DClose(){ - if ( p3d.buffer ) { - free( p3d.buffer ); - p3d.buffer = 0; - } -} - -int CharIsTokenDelimiter( int ch ){ - if ( ch <= 32 ) { - return 1; - } - return 0; -} - -int P3DSkipToToken( const char *name ){ - while ( P3DGetToken( 0 ) ) - { - if ( !_strcmpi( s_token, name ) ) { - return 1; - } - } - - return 0; -} - -/* -** P3DGetToken -** -*/ -int P3DGetToken( int restOfLine ){ - int i = 0; - - if ( p3d.buffer == 0 ) { - return 0; - } - - if ( ( p3d.curpos - p3d.buffer ) == p3d.len ) { - return 0; - } - - // skip over crap - while ( ( ( p3d.curpos - p3d.buffer ) < p3d.len ) && - ( *p3d.curpos <= 32 ) ) - { - p3d.curpos++; - } - - while ( ( p3d.curpos - p3d.buffer ) < p3d.len ) - { - s_token[i] = *p3d.curpos; - - p3d.curpos++; - i++; - - if ( ( CharIsTokenDelimiter( s_token[i - 1] ) && !restOfLine ) || - ( ( s_token[i - 1] == '\n' ) ) ) { - s_token[i - 1] = 0; - break; - } - } - - s_token[i] = 0; - - return 1; -} - -int P3DGetNextPair( char **psetName, char **associatedShader ){ - if ( s_curpair < p3d.numPairs ) { - *psetName = p3d.polysetNames[s_curpair]; - *associatedShader = p3d.shaders[s_curpair]; - s_curpair++; - return 1; - } - - return 0; -} - -int P3DSkipToTokenInBlock( const char *name ){ - int iLevel = 0; - - while ( P3DGetToken( 0 ) ) - { - if ( !_strcmpi( s_token, "}" ) ) { - iLevel--; - } - else if ( !_strcmpi( s_token, "{" ) ) { - iLevel++; - } - - if ( !_strcmpi( s_token, name ) ) { - return 1; - } - - if ( iLevel == 0 ) { - return 0; - } - } - - return 0; -} - -/* -** P3DProcess -** -** Nothing fancy here. -*/ -int P3DProcess(){ - - s_curpair = 0; - - // first token should be a string - P3DGetToken( 1 ); // Voodoo Ascii File - - // skip to the first Obj declaration - while ( P3DGetToken( 0 ) ) - { - if ( !_strcmpi( s_token, "Obj" ) ) { - int j = 0, k = 0; - - if ( P3DSkipToToken( "Text" ) ) { - if ( P3DSkipToTokenInBlock( "TMap" ) ) { - char *p; - - if ( !P3DSkipToToken( "Path" ) ) { - return 0; - } - - if ( !P3DGetToken( 1 ) ) { - return 0; - } - - while ( s_token[j] != 0 ) - { - if ( s_token[j] == '\\' ) { - j++; - p3d.shaders[p3d.numPairs][k] = '/'; - } - else - { - p3d.shaders[p3d.numPairs][k] = s_token[j]; - } - j++; - k++; - } - p3d.shaders[p3d.numPairs][k] = 0; - - // - // strip off any explicit extensions - // - if ( ( p = strrchr( p3d.shaders[p3d.numPairs], '/' ) ) != 0 ) { - while ( *p ) - { - if ( *p == '.' ) { - *p = 0; - break; - } - p++; - } - } - - // - // skip to the end of the Object and grab its name - // - if ( !P3DSkipToToken( "Name" ) ) { - return 0; - } - - if ( P3DGetToken( 0 ) ) { - // strip off leading 'Obj_' if it exists - if ( strstr( s_token, "Obj_" ) == s_token ) { - strcpy( p3d.polysetNames[p3d.numPairs], s_token + strlen( "Obj_" ) ); - } - else{ - strcpy( p3d.polysetNames[p3d.numPairs], s_token ); - } - - // strip off trailing unused color information -// if ( strrchr( p3d.polysetNames[p3d.numPairs], '_' ) != 0 ) -// *strrchr( p3d.polysetNames[p3d.numPairs], '_' ) = 0; - - p3d.numPairs++; - } - else - { - return 0; - } - } - } - } - } - - s_curpair = 0; - - return 1; -} - -#if 0 -void SkinFromP3D( const char *file ){ - char filename[1024]; - char *psetName, *associatedShader; - - /* - ** a P3D file contains a list of polysets, each with a list of associated - ** texture names that constitute it's - ** - ** Thus: - ** - ** P3D file -> skin - ** polyset -> polyset - ** texture -> texture.SHADER becomes polyset's shader - */ - sprintf( filename, "%s/%s", g_cddir, file ); - - if ( !P3DLoad( filename ) ) { - Error( "unable to load '%s'", filename ); - } - - while ( P3DGetNextPair( &psetName, &associatedShader ) ) - { - int i; - - // find the polyset in the object that this particular pset/shader pair - // corresponds to and append the shader to it - for ( i = 0; i < g_data.model.numSurfaces; i++ ) - { - if ( !_strcmpi( g_data.surfData[i].header.name, psetName ) ) { - char *p; - - if ( strstr( associatedShader, gamedir + 1 ) ) { - p = strstr( associatedShader, gamedir + 1 ) + strlen( gamedir ) - 1; - } - else - { - p = associatedShader; - } - - strcpy( g_data.surfData[i].shaders[g_data.surfData[i].header.numShaders].name, p ); - - g_data.surfData[i].header.numShaders++; - } - } - - } - - P3DClose(); -} -#endif diff --git a/tools/urt/tools/quake3/q3data/p3dlib.h b/tools/urt/tools/quake3/q3data/p3dlib.h deleted file mode 100644 index c68101d..0000000 --- a/tools/urt/tools/quake3/q3data/p3dlib.h +++ /dev/null @@ -1,8 +0,0 @@ - -#define P3D_GET_CROSSLINE 1 -#define P3D_GET_RESTOFLINE 2 - -int P3DLoad( const char *filename ); -void P3DClose(); - -int P3DGetNextPair( char **name, char **associatedShader ); diff --git a/tools/urt/tools/quake3/q3data/polyset.c b/tools/urt/tools/quake3/q3data/polyset.c deleted file mode 100644 index 545e1f6..0000000 --- a/tools/urt/tools/quake3/q3data/polyset.c +++ /dev/null @@ -1,246 +0,0 @@ -#include -#include "q3data.h" - -polyset_t *Polyset_SplitSets( polyset_t *psets, int numpolysets, int *pNumNewPolysets, int maxTris ){ - int p, np, op; - int numNewPolysets = 0; - int numSplitPolysets = 0; - polyset_t *newpsets; - int sumTriangles = 0; - - for ( p = 0; p < numpolysets; p++ ) - { - numNewPolysets += psets[p].numtriangles / maxTris + 1; - } - - if ( numNewPolysets == numpolysets ) { - return psets; - } - - printf( "Warning: creating %d polysets from input of %d polysets\n", numNewPolysets, numpolysets ); - - newpsets = calloc( sizeof( polyset_t ) * numNewPolysets, 1 ); - - for ( np = 0, op = 0; op < numpolysets; op++ ) - { - numSplitPolysets = ( psets[op].numtriangles / ( maxTris + 1 ) ) + 1; - if ( numSplitPolysets == 1 ) { - memcpy( &newpsets[np], &psets[op], sizeof( polyset_t ) ); - np++; - } - else - { - sumTriangles = 0; - - // split this pset into multiple smaller psets - for ( p = 0; p < numSplitPolysets; p++, np++ ) - { - memcpy( &newpsets[np], &psets[op], sizeof( polyset_t ) ); - - newpsets[np].triangles = psets[op].triangles + sumTriangles; - - if ( sumTriangles + maxTris > psets[op].numtriangles ) { - newpsets[np].numtriangles = psets[op].numtriangles - sumTriangles; - } - else{ - newpsets[np].numtriangles = maxTris; - } - - sumTriangles += newpsets[np].numtriangles; - } - } - } - - *pNumNewPolysets = numNewPolysets; - - return newpsets; -} - -polyset_t *Polyset_LoadSets( const char *file, int *numpolysets, int maxTrisPerSet ){ - polyset_t *psets; - polyset_t *finalpsets; - - // - // load the frame - // - if ( strstr( file, ".3DS" ) || strstr( file, ".3ds" ) ) { - _3DS_LoadPolysets( file, &psets, numpolysets, g_verbose ); - } - else{ - Error( "TRI files no longer supported" ); - } -// TRI_LoadPolysets( file, &psets, numpolysets ); - -/* - // - // scale polysets - // - for ( i = 0; i < psets; i++ ) - { - int j; - - for ( j = 0; j < psets[i].numtriangles; j++ ) - { - } - } - */ - - // - // split polysets if necessary - // - finalpsets = Polyset_SplitSets( psets, *numpolysets, numpolysets, maxTrisPerSet ); - - return finalpsets; -} - -polyset_t *Polyset_CollapseSets( polyset_t *psets, int numpolysets ){ - int p; - int sumtriangles = 0; - - polyset_t *oldpsets = psets; - - // - // no tag checking because this is an $oldbase and thus shouldn't have any - // tags - // - for ( p = 0; p < numpolysets; p++ ) - { - sumtriangles += oldpsets[p].numtriangles; - } - - psets = calloc( 1, sizeof( polyset_t ) ); - psets[0].numtriangles = sumtriangles; - psets[0].triangles = malloc( MD3_MAX_TRIANGLES * sizeof( triangle_t ) ); - - // each call to "LoadPolysets" only allocates a single large chunk of - // triangle memory that is utilized by all the polysets loaded by - // that one call - memcpy( psets[0].triangles, oldpsets[0].triangles, sizeof( triangle_t ) * sumtriangles ); - - free( oldpsets[0].triangles ); - free( oldpsets ); - - return psets; -} - -static float SnapFloat( float x ){ - int ix; - - x *= 1.0f / MD3_XYZ_SCALE; - ix = ( int ) x; - x = ( float ) ix; - x *= MD3_XYZ_SCALE; - - return x; -} - -void Polyset_SnapSets( polyset_t *psets, int numpolysets ){ - int p; - - for ( p = 0; p < numpolysets; p++ ) - { - int t; - - for ( t = 0; t < psets[p].numtriangles; t++ ) - { - int v; - - for ( v = 0; v < 3; v++ ) - { - psets[p].triangles[t].verts[v][0] = SnapFloat( psets[p].triangles[t].verts[v][0] ); - psets[p].triangles[t].verts[v][1] = SnapFloat( psets[p].triangles[t].verts[v][1] ); - psets[p].triangles[t].verts[v][2] = SnapFloat( psets[p].triangles[t].verts[v][2] ); - } - } - } -} - -void Polyset_ComputeNormals( polyset_t *psets, int numpolysets ){ - int p; - int i, t; - int vertexIndex[MD3_MAX_TRIANGLES][3]; - vec3_t verts[MD3_MAX_VERTS]; - vec3_t normals[MD3_MAX_VERTS]; - vec3_t faceNormals[MD3_MAX_TRIANGLES]; - - // - // iterate through polysets - // - for ( p = 0; p < numpolysets; p++ ) - { - int numUniqueVertices = 0; - - assert( psets[p].numtriangles < MD3_MAX_TRIANGLES ); - - memset( vertexIndex, 0xff, sizeof( vertexIndex ) ); - memset( verts, 0, sizeof( verts ) ); - memset( normals, 0, sizeof( normals ) ); - - // - // unique vertices - // - for ( t = 0; t < psets[p].numtriangles; t++ ) - { - int j; - - for ( j = 0; j < 3; j++ ) - { - for ( i = 0; i < numUniqueVertices; i++ ) - { - if ( VectorCompare( psets[p].triangles[t].verts[j], verts[i] ) ) { - break; - } - } - if ( i == numUniqueVertices ) { - vertexIndex[t][j] = numUniqueVertices; - VectorCopy( ( psets[p].triangles[t].verts[j] ), ( verts[numUniqueVertices] ) ); - numUniqueVertices++; - } - else - { - vertexIndex[t][j] = i; - } - } - } - - // - // compute face normals - // - for ( t = 0; t < psets[p].numtriangles; t++ ) - { - vec3_t side0, side1, facenormal; - - VectorSubtract( psets[p].triangles[t].verts[0], psets[p].triangles[t].verts[1], side0 ); - VectorSubtract( psets[p].triangles[t].verts[2], psets[p].triangles[t].verts[1], side1 ); - - CrossProduct( side0, side1, facenormal ); - VectorNormalize( facenormal, faceNormals[t] ); - } - - // - // sum normals and copy them back - // - for ( i = 0; i < numUniqueVertices; i++ ) - { - for ( t = 0; t < psets[p].numtriangles; t++ ) - { - if ( vertexIndex[t][0] == i || - vertexIndex[t][1] == i || - vertexIndex[t][2] == i ) { - normals[i][0] += faceNormals[t][0]; - normals[i][1] += faceNormals[t][1]; - normals[i][2] += faceNormals[t][2]; - } - } - VectorNormalize( normals[i], normals[i] ); - } - - - for ( t = 0; t < psets[p].numtriangles; t++ ) - { - VectorCopy( normals[vertexIndex[t][0]], psets[p].triangles[t].normals[0] ); - VectorCopy( normals[vertexIndex[t][1]], psets[p].triangles[t].normals[1] ); - VectorCopy( normals[vertexIndex[t][2]], psets[p].triangles[t].normals[2] ); - } - } -} diff --git a/tools/urt/tools/quake3/q3data/q3data.c b/tools/urt/tools/quake3/q3data/q3data.c deleted file mode 100644 index fa6aa68..0000000 --- a/tools/urt/tools/quake3/q3data/q3data.c +++ /dev/null @@ -1,653 +0,0 @@ -#ifdef WIN32 -#include -#endif -#include "q3data.h" -#include "md3lib.h" - -#include "vfs.h" - -qboolean g_verbose; -qboolean g_stripify = qtrue; -qboolean g_release; // don't grab, copy output data to new tree -char g_releasedir[1024]; // c:\quake2\baseq2, etc -qboolean g_archive; // don't grab, copy source data to new tree -char g_only[256]; // if set, only grab this cd -qboolean g_skipmodel; // set true when a cd is not g_only - -// bogus externs for some TA hacks (common/ using them against q3map) -char *moddir = NULL; -// some old defined that was in cmdlib lost during merge -char writedir[1024]; - -#if defined ( __linux__ ) || defined ( __APPLE__ ) -#define strlwr strlower -#endif - -/* - ======================================================= - - PAK FILES - - ======================================================= - */ - -unsigned Com_BlockChecksum( void *buffer, int length ); - -typedef struct -{ - char name[56]; - int filepos, filelen; -} packfile_t; - -typedef struct -{ - char id[4]; - int dirofs; - int dirlen; -} packheader_t; - -packfile_t pfiles[16384]; -FILE *pakfile; -packfile_t *pf; -packheader_t pakheader; - -/* - ============== - ReleaseFile - - Filename should be gamedir reletive. - Either copies the file to the release dir, or adds it to - the pak file. - ============== - */ -void ReleaseFile( char *filename ){ - char source[1024]; - char dest[1024]; - - if ( !g_release ) { - return; - } - - sprintf( source, "%s%s", gamedir, filename ); - sprintf( dest, "%s/%s", g_releasedir, filename ); - printf( "copying to %s\n", dest ); - QCopyFile( source, dest ); - return; -} - -typedef struct -{ - // shader - // opaque - // opaque 2 - // blend - // blend 2 - char names[5][1024]; - int num; -} ShaderFiles_t; - -ShaderFiles_t s_shaderFiles; - -void FindShaderFiles( char *filename ){ - char buffer[1024]; - char stripped[1024]; - char linebuffer[1024]; - int len, i; - char *buf; - char *diffuseExtensions[] = - { - ".TGA", - ".WAL", - ".PCX", - 0 - }; - char *otherExtensions[] = - { - ".specular.TGA", - ".blend.TGA", - ".alpha.TGA", - 0 - }; - - s_shaderFiles.num = 0; - - strcpy( stripped, filename ); - if ( strrchr( stripped, '.' ) ) { - *strrchr( stripped, '.' ) = 0; - } - strcat( stripped, ".shader" ); - - if ( FileExists( stripped ) ) { - char *p; - char mapa[512], mapb[512]; - - strcpy( s_shaderFiles.names[s_shaderFiles.num], stripped ); - s_shaderFiles.num++; - - // load and parse - len = LoadFile( stripped, (void **)&buf ); - - p = buf; - - while ( p - buf < len ) - { - i = 0; - - // skip spaces - while ( *p == ' ' || *p == '\n' || *p == '\t' ) - p++; - - // grab rest of the line - while ( *p != 0 && *p != '\n' ) - { - linebuffer[i] = *p; - i++; - p++; - } - if ( *p == '\n' ) { - p++; - } - linebuffer[i] = 0; - - strlwr( linebuffer ); - - // see if the line specifies an opaque map or blendmap - if ( strstr( linebuffer, "opaquemap" ) == linebuffer || - strstr( linebuffer, "blendmap" ) == linebuffer ) { - int j; - - i = 0; - - mapa[0] = mapb[0] = 0; - - // skip past the keyword - while ( linebuffer[i] != ' ' && linebuffer[i] != '\t' && linebuffer[i] ) - i++; - // skip past spaces - while ( ( linebuffer[i] == ' ' || linebuffer[i] == '\t' ) && linebuffer[i] ) - i++; - - // grab first map name - j = 0; - while ( linebuffer[i] != ' ' && linebuffer[i] != '\t' && linebuffer[i] ) - { - mapa[j] = linebuffer[i]; - j++; - i++; - } - mapa[j] = 0; - - // skip past spaces - while ( ( linebuffer[i] == ' ' || linebuffer[i] == '\t' ) && linebuffer[i] ) - i++; - - // grab second map name - j = 0; - while ( linebuffer[i] != ' ' && linebuffer[i] != '\t' && linebuffer[i] ) - { - mapb[j] = linebuffer[i]; - j++; - i++; - } - mapb[j] = 0; - - // store map names - if ( mapa[0] != 0 && mapa[0] != '-' ) { - sprintf( s_shaderFiles.names[s_shaderFiles.num], "%s%s", gamedir, mapa ); - s_shaderFiles.num++; - } - if ( mapb[0] != 0 && mapb[0] != '-' && mapb[0] != '^' && mapb[0] != '*' ) { - sprintf( s_shaderFiles.names[s_shaderFiles.num], "%s%s", gamedir, mapb ); - s_shaderFiles.num++; - } - } - } - } - else - { - if ( strrchr( stripped, '.' ) ) { - *strrchr( stripped, '.' ) = 0; - } - - // look for diffuse maps - for ( i = 0; i < 3; i++ ) - { - strcpy( buffer, stripped ); - strcat( buffer, diffuseExtensions[i] ); - if ( FileExists( buffer ) ) { - strcpy( s_shaderFiles.names[s_shaderFiles.num], buffer ); - s_shaderFiles.num++; - break; - } - } - for ( i = 0; i < 3; i++ ) - { - strcpy( buffer, stripped ); - strcat( buffer, otherExtensions[i] ); - if ( FileExists( buffer ) ) { - strcpy( s_shaderFiles.names[s_shaderFiles.num], buffer ); - s_shaderFiles.num++; - } - } - } -} - -/* - ============== - ReleaseShader - - Copies all needed files for a shader to the release directory - ============== - */ -void ReleaseShader( char *filename ){ - char fullpath[1024]; - char dest[1024]; - char stripped[1024]; - int i; - - sprintf( fullpath, "%s%s", gamedir, filename ); - - FindShaderFiles( fullpath ); - - for ( i = 0; i < s_shaderFiles.num; i++ ) - { - strcpy( stripped, s_shaderFiles.names[i] ); - if ( strstr( stripped, gamedir ) ) { - memmove( stripped, stripped + strlen( gamedir ), strlen( stripped ) ); - } - sprintf( dest, "%s/%s", g_releasedir, stripped ); - printf( "copying to %s\n", dest ); - QCopyFile( s_shaderFiles.names[i], dest ); - } -} - -/* - =============== - Cmd_File - - This is only used to cause a file to be copied during a release - build (default.cfg, maps, etc) - =============== - */ -void Cmd_File( void ){ - GetToken( qfalse ); - ReleaseFile( token ); -} - -/* - =============== - PackDirectory_r - - =============== - */ -#ifdef _WIN32 -#include "io.h" -void PackDirectory_r( char *dir ){ - struct _finddata_t fileinfo; - int handle; - char dirstring[1024]; - char filename[1024]; - - sprintf( dirstring, "%s%s/*.*", gamedir, dir ); - - handle = _findfirst( dirstring, &fileinfo ); - if ( handle == -1 ) { - return; - } - - do - { - sprintf( filename, "%s/%s", dir, fileinfo.name ); - if ( fileinfo.attrib & _A_SUBDIR ) { // directory - if ( fileinfo.name[0] != '.' ) { // don't pak . and .. - PackDirectory_r( filename ); - } - continue; - } - // copy or pack the file - ReleaseFile( filename ); - } while ( _findnext( handle, &fileinfo ) != -1 ); - - _findclose( handle ); -} -#else - -#include -#ifndef WIN32 -#include -#else -#include -#endif - -void PackDirectory_r( char *dir ){ -#ifdef NeXT - struct direct **namelist, *ent; -#else - struct dirent **namelist, *ent; -#endif - int count; - struct stat st; - int i; - int len; - char fullname[1024]; - char dirstring[1024]; - char *name; - - sprintf( dirstring, "%s%s", gamedir, dir ); - count = scandir( dirstring, &namelist, NULL, NULL ); - - for ( i = 0 ; i < count ; i++ ) - { - ent = namelist[i]; - name = ent->d_name; - - if ( name[0] == '.' ) { - continue; - } - - sprintf( fullname, "%s/%s", dir, name ); - sprintf( dirstring, "%s%s/%s", gamedir, dir, name ); - - if ( stat( dirstring, &st ) == -1 ) { - Error( "fstating %s", pf->name ); - } - if ( st.st_mode & S_IFDIR ) { // directory - PackDirectory_r( fullname ); - continue; - } - - // copy or pack the file - ReleaseFile( fullname ); - } -} -#endif - - -/* - =============== - Cmd_Dir - - This is only used to cause a directory to be copied during a - release build (sounds, etc) - =============== - */ -void Cmd_Dir( void ){ - GetToken( qfalse ); - PackDirectory_r( token ); -} - -//======================================================================== - -#define MAX_RTEX 16384 -int numrtex; -char rtex[MAX_RTEX][64]; - -void ReleaseTexture( char *name ){ - int i; - char path[1024]; - - for ( i = 0 ; i < numrtex ; i++ ) - if ( !Q_stricmp( name, rtex[i] ) ) { - return; - } - - if ( numrtex == MAX_RTEX ) { - Error( "numrtex == MAX_RTEX" ); - } - - strcpy( rtex[i], name ); - numrtex++; - - sprintf( path, "textures/%s.wal", name ); - ReleaseFile( path ); -} - -/* - =============== - Cmd_Maps - - Only relevent for release and pak files. - Releases the .bsp files for the maps, and scans all of the files to - build a list of all textures used, which are then released. - =============== - */ -void Cmd_Maps( void ){ - char map[1024]; - - while ( TokenAvailable() ) - { - GetToken( qfalse ); - sprintf( map, "maps/%s.bsp", token ); - ReleaseFile( map ); - - if ( !g_release ) { - continue; - } - - // get all the texture references - sprintf( map, "%smaps/%s.bsp", gamedir, token ); - LoadBSPFile( map ); - } -} - - -//============================================================== - -/* - =============== - ParseScript - =============== - */ -void ParseScript( void ){ - while ( 1 ) - { - do - { // look for a line starting with a $ command - GetToken( qtrue ); - if ( endofscript ) { - return; - } - if ( token[0] == '$' ) { - break; - } - while ( TokenAvailable() ) - GetToken( qfalse ); - } while ( 1 ); - - // - // model commands - // - if ( !strcmp( token, "$modelname" ) ) { - Cmd_Modelname(); - } - else if ( !strcmp( token, "$base" ) ) { - Cmd_Base(); - } - else if ( !strcmp( token, "$exit" ) ) { - break; - } - else if ( !strcmp( token, "$3dsconvert" ) ) { - Cmd_3DSConvert(); - } - else if ( !strcmp( token, "$spritebase" ) ) { - Cmd_SpriteBase(); - } - else if ( !strcmp( token, "$cd" ) ) { - Cmd_Cd(); - } - else if ( !strcmp( token, "$origin" ) ) { - Cmd_Origin(); - } - else if ( !strcmp( token, "$scale" ) ) { - Cmd_ScaleUp(); - } - else if ( !strcmp( token, "$frame" ) ) { - Cmd_Frame(); - } - else if ( !strcmp( token, "$skin" ) ) { - Cmd_Skin(); - } - else if ( !strcmp( token, "$spriteshader" ) ) { - Cmd_SpriteShader(); - } - else if ( !strcmp( token, "$aseconvert" ) ) { - Cmd_ASEConvert( qfalse ); - } - else if ( !strcmp( token, "$aseanimconvert" ) ) { - Cmd_ASEConvert( qtrue ); - } - - // - // image commands - // - else if ( !strcmp( token, "$grab" ) ) { - Cmd_Grab(); - } - else if ( !strcmp( token, "$raw" ) ) { - Cmd_Raw(); - } - else if ( !strcmp( token, "$colormap" ) ) { - Cmd_Colormap(); - } - else if ( !strcmp( token, "$environment" ) ) { - Cmd_Environment(); - } - - // - // video - // - else if ( !strcmp( token, "$video" ) ) { - Cmd_Video(); - } - // - // misc - // - else if ( !strcmp( token, "$file" ) ) { - Cmd_File(); - } - else if ( !strcmp( token, "$dir" ) ) { - Cmd_Dir(); - } - else if ( !strcmp( token, "$maps" ) ) { - Cmd_Maps(); - } - else{ - Error( "bad command %s\n", token ); - } - } -} - -//======================================================= - -#include "version.h" - -/* - ============== - main - ============== - */ -int main( int argc, char **argv ){ - static int i; // VC4.2 compiler bug if auto... - char path[1024]; - - // using GtkRadiant's versioning next to Id's versioning - printf( "Q3Data - (c) 1999 Id Software Inc.\n" ); - printf( "GtkRadiant - v" RADIANT_VERSION " " __DATE__ "\n" ); - - ExpandWildcards( &argc, &argv ); - - for ( i = 1 ; i < argc ; i++ ) - { - if ( !strcmp( argv[i], "-archive" ) ) { - archive = qtrue; - strcpy( archivedir, argv[i + 1] ); - printf( "Archiving source to: %s\n", archivedir ); - i++; - } - else if ( !strcmp( argv[i], "-release" ) ) { - g_release = qtrue; - strcpy( g_releasedir, argv[i + 1] ); - printf( "Copy output to: %s\n", g_releasedir ); - i++; - } - else if ( !strcmp( argv[i], "-nostrips" ) ) { - g_stripify = qfalse; - printf( "Not optimizing for strips\n" ); - } - else if ( !strcmp( argv[i], "-writedir" ) ) { - strcpy( writedir, argv[i + 1] ); - printf( "Write output to: %s\n", writedir ); - i++; - } - else if ( !strcmp( argv[i], "-verbose" ) ) { - g_verbose = qtrue; - } - else if ( !strcmp( argv[i], "-dump" ) ) { - printf( "Dumping contents of: '%s'\n", argv[i + 1] ); - if ( strstr( argv[i + 1], ".md3" ) ) { - MD3_Dump( argv[i + 1] ); - } - else - { - Error( "Do not know how to dump the contents of '%s'\n", argv[i + 1] ); - } - i++; - } - else if ( !strcmp( argv[i], "-3dsconvert" ) ) { - // NOTE TTimo this is broken, tried on a sample .3ds - // what happens .. it calls the Convert3DStoMD3, - // which calls the scriptlib function in non initialized state .. and crashes - printf( "Converting %s.3DS to %s.MD3\n", argv[i + 1], argv[i + 1] ); - SetQdirFromPath( argv[i + 1] ); - vfsInitDirectory( gamedir ); - Convert3DStoMD3( argv[i + 1] ); - i++; - } - else if ( !strcmp( argv[i], "-only" ) ) { - strcpy( g_only, argv[i + 1] ); - printf( "Only grabbing %s\n", g_only ); - i++; - } - else if ( !strcmp( argv[i], "-gamedir" ) ) { - strcpy( gamedir, argv[i + 1] ); - i++; - } - else if ( argv[i][0] == '-' ) { - Error( "Unknown option \"%s\"", argv[i] ); - } - else{ - break; - } - } - - if ( i == argc ) { - Error( "usage: q3data [-archive ] [-dump ] [-release ] [-only ] [-3dsconvert ] [-verbose] [file.qdt]" ); - } - - for ( ; i < argc ; i++ ) - { - printf( "--------------- %s ---------------\n", argv[i] ); - // load the script - strcpy( path, argv[i] ); - DefaultExtension( path, ".qdt" ); - if ( !gamedir[0] ) { - SetQdirFromPath( path ); - } - // NOTE TTimo - // q3data went through a partial conversion to use the vfs - // it was never actually tested before 1.1.1 - // the code is still mostly using direct file access calls - vfsInitDirectory( gamedir ); - LoadScriptFile( ExpandArg( path ), -1 ); - - // - // parse it - // - ParseScript(); - - // write out the last model - FinishModel( TYPE_UNKNOWN ); - } - - return 0; -} diff --git a/tools/urt/tools/quake3/q3data/q3data.dsp b/tools/urt/tools/quake3/q3data/q3data.dsp deleted file mode 100644 index 88dcaf2..0000000 --- a/tools/urt/tools/quake3/q3data/q3data.dsp +++ /dev/null @@ -1,200 +0,0 @@ -# Microsoft Developer Studio Project File - Name="q3data" - Package Owner=<4> -# Microsoft Developer Studio Generated Build File, Format Version 6.00 -# ** DO NOT EDIT ** - -# TARGTYPE "Win32 (x86) Console Application" 0x0103 - -CFG=q3data - Win32 Debug -!MESSAGE This is not a valid makefile. To build this project using NMAKE, -!MESSAGE use the Export Makefile command and run -!MESSAGE -!MESSAGE NMAKE /f "q3data.mak". -!MESSAGE -!MESSAGE You can specify a configuration when running NMAKE -!MESSAGE by defining the macro CFG on the command line. For example: -!MESSAGE -!MESSAGE NMAKE /f "q3data.mak" CFG="q3data - Win32 Debug" -!MESSAGE -!MESSAGE Possible choices for configuration are: -!MESSAGE -!MESSAGE "q3data - Win32 Release" (based on "Win32 (x86) Console Application") -!MESSAGE "q3data - Win32 Debug" (based on "Win32 (x86) Console Application") -!MESSAGE - -# Begin Project -# PROP AllowPerConfigDependencies 0 -# PROP Scc_ProjName "q3data" -# PROP Scc_LocalPath ".." -CPP=cl.exe -RSC=rc.exe - -!IF "$(CFG)" == "q3data - Win32 Release" - -# PROP BASE Use_MFC 0 -# PROP BASE Use_Debug_Libraries 0 -# PROP BASE Output_Dir "Release" -# PROP BASE Intermediate_Dir "Release" -# PROP BASE Target_Dir "" -# PROP Use_MFC 0 -# PROP Use_Debug_Libraries 0 -# PROP Output_Dir "Release" -# PROP Intermediate_Dir "Release" -# PROP Ignore_Export_Lib 0 -# PROP Target_Dir "" -F90=df.exe -# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c -# ADD CPP /nologo /MD /W3 /GX /O2 /I "..\common" /I "..\..\..\..\libxml2\include" /I "..\..\..\libs" /I "..\..\..\..\gtk2-win32\include\glib-2.0" /I "..\..\..\..\gtk2-win32\lib\glib-2.0\include" /I "..\..\..\include" /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /FD /c -# SUBTRACT CPP /YX -# ADD BASE RSC /l 0x409 /d "NDEBUG" -# ADD RSC /l 0x409 /d "NDEBUG" -BSC32=bscmake.exe -# ADD BASE BSC32 /nologo -# ADD BSC32 /nologo -LINK32=link.exe -# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386 -# ADD LINK32 glib-2.0.lib l_net.lib wsock32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /stack:0xf42400 /subsystem:console /debug /machine:I386 /libpath:"..\..\..\libs\pak\release" /libpath:"..\..\..\libs\l_net\release" /libpath:"..\..\..\..\gtk2-win32\lib\\" -# SUBTRACT LINK32 /pdb:none - -!ELSEIF "$(CFG)" == "q3data - Win32 Debug" - -# PROP BASE Use_MFC 0 -# PROP BASE Use_Debug_Libraries 1 -# PROP BASE Output_Dir "Debug" -# PROP BASE Intermediate_Dir "Debug" -# PROP BASE Target_Dir "" -# PROP Use_MFC 0 -# PROP Use_Debug_Libraries 1 -# PROP Output_Dir "Debug" -# PROP Intermediate_Dir "Debug" -# PROP Ignore_Export_Lib 0 -# PROP Target_Dir "" -F90=df.exe -# ADD BASE CPP /nologo /W3 /Gm /GX /Zi /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c -# ADD CPP /nologo /MDd /W3 /Gm /ZI /Od /I "..\common" /I "..\..\..\..\libxml2\include" /I "..\..\..\libs" /I "..\..\..\..\gtk2-win32\include\glib-2.0" /I "..\..\..\..\gtk2-win32\lib\glib-2.0\include" /I "..\..\..\include" /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /FR /FD /c -# SUBTRACT CPP /YX -# ADD BASE RSC /l 0x409 /d "_DEBUG" -# ADD RSC /l 0x409 /d "_DEBUG" -BSC32=bscmake.exe -# ADD BASE BSC32 /nologo -# ADD BSC32 /nologo -LINK32=link.exe -# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept -# ADD LINK32 glib-2.0.lib l_net.lib wsock32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /stack:0xf42400 /subsystem:console /debug /machine:I386 /pdbtype:sept /libpath:"..\..\..\libs\l_net\Debug" /libpath:"..\..\..\libs\pak\Debug" /libpath:"..\..\..\..\gtk2-win32\lib\\" -# SUBTRACT LINK32 /pdb:none - -!ENDIF - -# Begin Target - -# Name "q3data - Win32 Release" -# Name "q3data - Win32 Debug" -# Begin Source File - -SOURCE=.\3dslib.c -# End Source File -# Begin Source File - -SOURCE=.\3dslib.h -# End Source File -# Begin Source File - -SOURCE=..\common\aselib.c -# End Source File -# Begin Source File - -SOURCE=..\common\aselib.h -# End Source File -# Begin Source File - -SOURCE=..\common\bspfile.c -# End Source File -# Begin Source File - -SOURCE=..\common\cmdlib.c -# End Source File -# Begin Source File - -SOURCE=.\compress.c -# End Source File -# Begin Source File - -SOURCE=..\common\imagelib.c -# End Source File -# Begin Source File - -SOURCE=.\images.c -# End Source File -# Begin Source File - -SOURCE=..\common\inout.c -# End Source File -# Begin Source File - -SOURCE=.\md3lib.c -# End Source File -# Begin Source File - -SOURCE=.\md3lib.h -# End Source File -# Begin Source File - -SOURCE=..\common\md4.c -# End Source File -# Begin Source File - -SOURCE=.\models.c -# End Source File -# Begin Source File - -SOURCE=.\p3dlib.c -# End Source File -# Begin Source File - -SOURCE=.\p3dlib.h -# End Source File -# Begin Source File - -SOURCE=.\polyset.c -# End Source File -# Begin Source File - -SOURCE=..\common\polyset.h -# End Source File -# Begin Source File - -SOURCE=.\q3data.c -# End Source File -# Begin Source File - -SOURCE=.\q3data.h -# End Source File -# Begin Source File - -SOURCE=..\common\scriplib.c -# End Source File -# Begin Source File - -SOURCE=.\stripper.c -# End Source File -# Begin Source File - -SOURCE=..\common\trilib.c -# End Source File -# Begin Source File - -SOURCE=..\common\unzip.c -# End Source File -# Begin Source File - -SOURCE=..\common\unzip.h -# End Source File -# Begin Source File - -SOURCE=..\common\vfs.c -# End Source File -# Begin Source File - -SOURCE=.\video.c -# End Source File -# End Target -# End Project diff --git a/tools/urt/tools/quake3/q3data/q3data.h b/tools/urt/tools/quake3/q3data/q3data.h deleted file mode 100644 index 2943e3a..0000000 --- a/tools/urt/tools/quake3/q3data/q3data.h +++ /dev/null @@ -1,78 +0,0 @@ -// q3data.h - - -#include -#include -#include -#include -#include - -#include "../common/cmdlib.h" -#include "scriplib.h" -#include "mathlib.h" -#include "polyset.h" -#include "trilib.h" -#include "imagelib.h" -#include "qthreads.h" -#include "l3dslib.h" -#include "bspfile.h" -#include "p3dlib.h" -#include "3dslib.h" -#include "aselib.h" -#include "md3lib.h" - -void Cmd_ASEConvert( qboolean grabAnims ); -void Cmd_3DSConvert( void ); -void Cmd_Modelname( void ); -void Cmd_SpriteBase( void ); -void Cmd_Base( void ); -void Cmd_Cd( void ); -void Cmd_Origin( void ); -void Cmd_ScaleUp( void ); -void Cmd_Frame( void ); -void Cmd_Modelname( void ); -void Cmd_SpriteShader( void ); -void Cmd_Skin( void ); -void Cmd_Skinsize( void ); -void FinishModel( int type ); - -void Cmd_Grab( void ); -void Cmd_Raw( void ); -void Cmd_Mip( void ); -void Cmd_Environment( void ); -void Cmd_Colormap( void ); - -void Cmd_File( void ); -void Cmd_Dir( void ); -void Cmd_StartWad( void ); -void Cmd_EndWad( void ); -void Cmd_Mippal( void ); -void Cmd_Mipdir( void ); - -void Cmd_Video( void ); - -void ReleaseFile( char *filename ); -void ReleaseShader( char *filename ); - -void Convert3DStoMD3( const char *filename ); - -void OrderMesh( int input[][3], int output[][3], int numTris ); - -extern byte *byteimage, *lbmpalette; -extern int byteimagewidth, byteimageheight; - -extern qboolean g_release; // don't grab, copy output data to new tree -extern char g_releasedir[1024]; // c:\quake2\baseq2, etc -extern qboolean g_archive; // don't grab, copy source data to new tree -extern qboolean do3ds; -extern char g_only[256]; // if set, only grab this cd -extern qboolean g_skipmodel; // set true when a cd is not g_only -extern qboolean g_verbose; - -extern char *trifileext; - -#define TYPE_ITEM 0 -#define TYPE_PLAYER 1 -#define TYPE_WEAPON 2 -#define TYPE_HAND 3 -#define TYPE_UNKNOWN 4 diff --git a/tools/urt/tools/quake3/q3data/q3data.vcproj b/tools/urt/tools/quake3/q3data/q3data.vcproj deleted file mode 100644 index f233006..0000000 --- a/tools/urt/tools/quake3/q3data/q3data.vcproj +++ /dev/null @@ -1,207 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/tools/urt/tools/quake3/q3data/stripper.c b/tools/urt/tools/quake3/q3data/stripper.c deleted file mode 100644 index f54e796..0000000 --- a/tools/urt/tools/quake3/q3data/stripper.c +++ /dev/null @@ -1,274 +0,0 @@ -#include -#include -#include - -static int s_used[8192]; // same as MD3_MAX_TRIANGLES - -/* -** FindNextTriangleInStrip -** -** Given a surface and triangle this tries to find the next triangle -** in the strip that would continue the strip. The next triangle in -** the strip should have the same winding as this triangle. -*/ -static int FindNextTriangleInStripOrFan( int mesh[][3], int tri, int orientation, int numTris, int odd ){ - int t; - int sum = 0; - int currentTri[3]; - int side; - int a, b, c; - int refa, refb; - - currentTri[0] = mesh[tri][( 0 + orientation ) % 3]; - currentTri[1] = mesh[tri][( 1 + orientation ) % 3]; - currentTri[2] = mesh[tri][( 2 + orientation ) % 3]; - - if ( odd ) { - refa = currentTri[1]; - refb = currentTri[2]; - } - else - { - refa = currentTri[2]; - refb = currentTri[0]; - } - - // go through all triangles and look for sides that match - // this triangle's - for ( t = 0; t < numTris; t++ ) - { - // don't check against self or against previously used triangles - if ( t == tri ) { - continue; - } - if ( s_used[t] ) { - continue; - } - - // check all three sides of the candidate triangle - for ( side = 0; side < 3; side++ ) - { - // check only the second (abutting) side - if ( ( refa == mesh[t][( side + 1 ) % 3] ) && - ( refb == mesh[t][side] ) ) { - - a = mesh[t][0]; - b = mesh[t][1]; - c = mesh[t][2]; - - // rotate the candidate triangle to align it properly in the strip - if ( side == 1 ) { - mesh[t][0] = b; - mesh[t][1] = c; - mesh[t][2] = a; - } - else if ( side == 2 ) { - mesh[t][0] = c; - mesh[t][1] = a; - mesh[t][2] = b; - } - - return t; - } -/* - else - { - Error( "fans not implemented yet" ); - - // check only the third (abutting) side - if ( ( currentTri[2] == pSurf->baseTriangles[t].v[side].index ) && - ( currentTri[0] == pSurf->baseTriangles[t].v[(side+1)%3].index ) ) - { - return t; - } - } - */ - } - } - - return -1; -} - -/* -** StripLength -*/ -static int StripLength( int mesh[][3], int strip[][3], int tri, int orientation, int numInputTris, int fillNo ){ - int stripIndex = 0; - int next; - - int odd = 1; - - strip[stripIndex][0] = mesh[tri][( 0 + orientation ) % 3]; - strip[stripIndex][1] = mesh[tri][( 1 + orientation ) % 3]; - strip[stripIndex][2] = mesh[tri][( 2 + orientation ) % 3]; - s_used[tri] = fillNo; - stripIndex++; - - next = tri; - - while ( ( next = FindNextTriangleInStripOrFan( mesh, next, orientation, numInputTris, odd ) ) != -1 ) - { - s_used[next] = fillNo; - odd = !odd; - strip[stripIndex][0] = mesh[next][0]; - strip[stripIndex][1] = mesh[next][1]; - strip[stripIndex][2] = mesh[next][2]; - stripIndex++; - - // all iterations after first need to be with an unrotated reference triangle - orientation = 0; - } - - return stripIndex; -} - -/* -** BuildOptimizedList -** -** Attempts to build the longest strip/fan possible. Does not adhere -** to pure strip or fan, will intermix between the two so long as some -** type of connectivity can be maintained. -*/ -#define MAX_ORIENTATIONS 3 -#define MAX_MATCHED_SIDES 4 -#define MAX_SEED_TRIANGLES 16 - -static int BuildOptimizedList( int mesh[][3], int strip[][3], int numInputTris ){ - int t; - int stripLen = 0; - int startTri = -1; - int bestTri = -1, bestLength = 0, bestOrientation = -1; - int matchedSides = 0; - int orientation = 0; - int seedTriangles[MAX_MATCHED_SIDES][MAX_SEED_TRIANGLES]; - int seedLengths[MAX_ORIENTATIONS][MAX_MATCHED_SIDES][MAX_SEED_TRIANGLES]; - int numSeeds[MAX_MATCHED_SIDES] = { 0, 0, 0 }; - int i; - - // build a ranked list of candidate seed triangles based on - // number of offshoot strips. Precedence goes to orphans, - // then corners, then edges, and interiors. - memset( seedTriangles, 0xff, sizeof( seedTriangles ) ); - memset( seedLengths, 0xff, sizeof( seedLengths ) ); - - for ( i = 0; i < MAX_MATCHED_SIDES; i++ ) - { - // find the triangle with lowest number of child strips - for ( t = 0; t < numInputTris; t++ ) - { - int orientation; - int n; - - if ( s_used[t] ) { - continue; - } - - // try the candidate triangle in three different orientations - matchedSides = 0; - for ( orientation = 0; orientation < 3; orientation++ ) - { - if ( ( n = FindNextTriangleInStripOrFan( mesh, t, orientation, numInputTris, 1 ) ) != -1 ) { - matchedSides++; - } - } - - if ( matchedSides == i ) { - seedTriangles[i][numSeeds[i]] = t; - numSeeds[i]++; - if ( numSeeds[i] == MAX_SEED_TRIANGLES ) { - break; - } - } - } - } - - // we have a list of potential seed triangles, so we now go through each - // potential candidate and look to see which produces the longest strip - // and select our startTri based on this - for ( i = 0; i < MAX_MATCHED_SIDES; i++ ) - { - int j; - - for ( j = 0; j < numSeeds[i]; j++ ) - { - for ( orientation = 0; orientation < 3; orientation++ ) - { - int k; - - seedLengths[orientation][i][j] = StripLength( mesh, strip, seedTriangles[i][j], orientation, numInputTris, 2 ); - - if ( seedLengths[orientation][i][j] > bestLength ) { - bestTri = seedTriangles[i][j]; - bestLength = seedLengths[orientation][i][j]; - bestOrientation = orientation; - } - - for ( k = 0; k < numInputTris; k++ ) - { - if ( s_used[k] == 2 ) { - s_used[k] = 0; - } - } - } - } - - if ( bestTri != -1 ) { - break; - } - } - - // build the strip for real - if ( bestTri != -1 ) { - stripLen = StripLength( mesh, strip, bestTri, bestOrientation, numInputTris, 1 ); - } - - return stripLen; -} - -/* -** OrderMesh -** -** Given an input mesh and an output mesh, this routine will reorder -** the triangles within the mesh into strips/fans. -*/ -void OrderMesh( int input[][3], int output[][3], int numTris ){ - int i; - int sumStrippedTriangles = 0; - int strippedTriangles; - int totalStrips = 0; - int strip[8192][3]; // could dump directly into 'output', but - // this helps with debugging - - memset( s_used, 0, sizeof( s_used ) ); - -#if 0 - FILE *fp = fopen( "strip.txt", "wt" ); - - for ( i = 0; i < numTris; i++ ) - { - fprintf( fp, "%4d: %3d %3d %3d\n", i, input[i][0], input[i][1], input[i][2] ); - } - fclose( fp ); -#endif - - // while there are still triangles that are not part of a strip - while ( sumStrippedTriangles < numTris ) - { - // build a strip - strippedTriangles = BuildOptimizedList( input, strip, numTris ); - - for ( i = 0; i < strippedTriangles; i++ ) - { - output[sumStrippedTriangles + i][0] = strip[i][0]; - output[sumStrippedTriangles + i][1] = strip[i][1]; - output[sumStrippedTriangles + i][2] = strip[i][2]; - } - - sumStrippedTriangles += strippedTriangles; - totalStrips++; - } - - printf( "Triangles on surface: %d\n", sumStrippedTriangles ); - printf( "Total strips from surface: %d\n", totalStrips ); - printf( "Average strip length: %f\n", ( float ) sumStrippedTriangles / totalStrips ); -} diff --git a/tools/urt/tools/quake3/q3data/video.c b/tools/urt/tools/quake3/q3data/video.c deleted file mode 100644 index 7b84127..0000000 --- a/tools/urt/tools/quake3/q3data/video.c +++ /dev/null @@ -1,1106 +0,0 @@ -#include -#include "q3data.h" - -static int s_resample_width = 256; -static int s_resample_height = 256; - -#define OUTPUT_TGAS 1 - -#define UNCOMPRESSED 0 -#define BTC_COMPRESSION 1 - -static int s_compression_method = BTC_COMPRESSION; - -static const char *CIN_EXTENSION = "cn2"; -static const int CIN_SIGNATURE = ( 'C' << 24 ) | ( 'I' << 16 ) | ( 'N' << 8 ) | ( '2' ); - -static byte *s_soundtrack; -static char s_base[32]; -static char s_output_base[32]; - -/* - =============================================================================== - - WAV loading - - =============================================================================== - */ - -typedef struct -{ - int rate; - int width; - int channels; - int loopstart; - int samples; - int dataofs; // chunk starts this many bytes from file start -} wavinfo_t; - - -byte *data_p; -byte *iff_end; -byte *last_chunk; -byte *iff_data; -int iff_chunk_len; - - -static int s_samplecounts[0x10000]; -static wavinfo_t s_wavinfo; - -short GetLittleShort( void ){ - short val = 0; - val = *data_p; - val = val + ( *( data_p + 1 ) << 8 ); - data_p += 2; - return val; -} - -int GetLittleLong( void ){ - int val = 0; - val = *data_p; - val = val + ( *( data_p + 1 ) << 8 ); - val = val + ( *( data_p + 2 ) << 16 ); - val = val + ( *( data_p + 3 ) << 24 ); - data_p += 4; - return val; -} - -void FindNextChunk( char *name ){ - while ( 1 ) - { - data_p = last_chunk; - - if ( data_p >= iff_end ) { // didn't find the chunk - data_p = NULL; - return; - } - - data_p += 4; - iff_chunk_len = GetLittleLong(); - if ( iff_chunk_len < 0 ) { - data_p = NULL; - return; - } -// if (iff_chunk_len > 1024*1024) -// Sys_Error ("FindNextChunk: %i length is past the 1 meg sanity limit", iff_chunk_len); - data_p -= 8; - last_chunk = data_p + 8 + ( ( iff_chunk_len + 1 ) & ~1 ); - if ( !strncmp( data_p, name, 4 ) ) { - return; - } - } -} - -void FindChunk( char *name ){ - last_chunk = iff_data; - FindNextChunk( name ); -} - - -void DumpChunks( void ){ - char str[5]; - - str[4] = 0; - data_p = iff_data; - do - { - memcpy( str, data_p, 4 ); - data_p += 4; - iff_chunk_len = GetLittleLong(); - printf( "0x%x : %s (%d)\n", (int)( data_p - 4 ), str, iff_chunk_len ); - data_p += ( iff_chunk_len + 1 ) & ~1; - } while ( data_p < iff_end ); -} - -/* - ============ - GetWavinfo - ============ - */ -wavinfo_t GetWavinfo( char *name, byte *wav, int wavlength ){ - wavinfo_t info; - int i; - int format; - int samples; - - memset( &info, 0, sizeof( info ) ); - - if ( !wav ) { - return info; - } - - iff_data = wav; - iff_end = wav + wavlength; - -// find "RIFF" chunk - FindChunk( "RIFF" ); - if ( !( data_p && !strncmp( data_p + 8, "WAVE", 4 ) ) ) { - printf( "Missing RIFF/WAVE chunks\n" ); - return info; - } - -// get "fmt " chunk - iff_data = data_p + 12; -// DumpChunks (); - - FindChunk( "fmt " ); - if ( !data_p ) { - printf( "Missing fmt chunk\n" ); - return info; - } - data_p += 8; - format = GetLittleShort(); - if ( format != 1 ) { - printf( "Microsoft PCM format only\n" ); - return info; - } - - info.channels = GetLittleShort(); - info.rate = GetLittleLong(); - data_p += 4 + 2; - info.width = GetLittleShort() / 8; - -// get cue chunk - FindChunk( "cue " ); - if ( data_p ) { - data_p += 32; - info.loopstart = GetLittleLong(); -// Com_Printf("loopstart=%d\n", sfx->loopstart); - - // if the next chunk is a LIST chunk, look for a cue length marker - FindNextChunk( "LIST" ); - if ( data_p ) { - if ( !strncmp( data_p + 28, "mark", 4 ) ) { // this is not a proper parse, but it works with cooledit... - data_p += 24; - i = GetLittleLong(); // samples in loop - info.samples = info.loopstart + i; - } - } - } - else{ - info.loopstart = -1; - } - -// find data chunk - FindChunk( "data" ); - if ( !data_p ) { - printf( "Missing data chunk\n" ); - return info; - } - - data_p += 4; - samples = GetLittleLong(); - - if ( info.samples ) { - if ( samples < info.samples ) { - Error( "Sound %s has a bad loop length", name ); - } - } - else{ - info.samples = samples; - } - - info.dataofs = data_p - wav; - - return info; -} - -//===================================================================== - -/* - ============== - LoadSoundtrack - ============== - */ -void LoadSoundtrack( void ){ - char name[1024]; - FILE *f; - int len; - int i, val, j; - - s_soundtrack = NULL; - sprintf( name, "%svideo/%s/%s.wav", gamedir, s_base, s_base ); - printf( "WAV: %s\n", name ); - f = fopen( name, "rb" ); - if ( !f ) { - printf( "no soundtrack for %s\n", s_base ); - return; - } - len = Q_filelength( f ); - s_soundtrack = malloc( len ); - fread( s_soundtrack, 1, len, f ); - fclose( f ); - - s_wavinfo = GetWavinfo( name, s_soundtrack, len ); - - // count samples for compression - memset( s_samplecounts, 0, sizeof( s_samplecounts ) ); - - j = s_wavinfo.samples / 2; - for ( i = 0 ; i < j ; i++ ) - { - val = ( (unsigned short *)( s_soundtrack + s_wavinfo.dataofs ) )[i]; - s_samplecounts[val]++; - } - val = 0; - for ( i = 0 ; i < 0x10000 ; i++ ) - if ( s_samplecounts[i] ) { - val++; - } - - printf( "%i unique sample values\n", val ); -} - -/* - ================== - WriteSound - ================== - */ -void WriteSound( FILE *output, int frame ){ - int start, end; - int count; - int empty = 0; - int i; - int sample; - int width; - - width = s_wavinfo.width * s_wavinfo.channels; - - start = frame * s_wavinfo.rate / 14; - end = ( frame + 1 ) * s_wavinfo.rate / 14; - count = end - start; - - for ( i = 0 ; i < count ; i++ ) - { - sample = start + i; - if ( sample > s_wavinfo.samples || !s_soundtrack ) { - fwrite( &empty, 1, width, output ); - } - else{ - fwrite( s_soundtrack + s_wavinfo.dataofs + sample * width, 1, width,output ); - } - } -} - -//========================================================================== - -static float s_resampleXRatio; -static float s_resampleYRatio; - -static void BoxFilterHorizontalElements( unsigned char *dst, unsigned char *src, float s0, float s1 ){ - float w; - float rSum = 0, gSum = 0, bSum = 0; - float x = s0; - float sumWeight = 0; - - for ( x = s0; x < s1; x++, src += 4 ) - { - if ( x == s0 ) { - w = ( int ) ( s0 + 1 ) - x; - } - else if ( x + 1 >= s1 ) { - w = s1 - ( int ) x; - } - else - { - w = 1.0f; - } - - rSum += src[0] * w; - gSum += src[1] * w; - bSum += src[2] * w; - sumWeight += w; - } - - rSum /= sumWeight; - gSum /= sumWeight; - bSum /= sumWeight; - - dst[0] = ( unsigned char ) ( rSum + 0.5 ); - dst[1] = ( unsigned char ) ( gSum + 0.5 ); - dst[2] = ( unsigned char ) ( bSum + 0.5 ); -} - -static void BoxFilterVerticalElements( unsigned char *dst, // destination of the filter process - unsigned char *src, // source pixels - int srcStep, // stride of the source pixels - float s0, float s1 ){ - float w; - float rSum = 0, gSum = 0, bSum = 0; - float y = s0; - float sumWeight = 0; - - for ( y = s0; y < ( int ) ( s1 + 1 ) ; y++, src += srcStep ) - { - if ( y == s0 ) { - w = ( int ) ( s0 + 1 ) - y; - } - else if ( y + 1 >= s1 ) { - w = s1 - ( int ) y; - } - else - { - w = 1.0f; - } - - rSum += src[0] * w; - gSum += src[1] * w; - bSum += src[2] * w; - sumWeight += w; - } - - rSum /= sumWeight; - gSum /= sumWeight; - bSum /= sumWeight; - - dst[0] = ( unsigned char ) ( rSum + 0.5 ); - dst[1] = ( unsigned char ) ( gSum + 0.5 ); - dst[2] = ( unsigned char ) ( bSum + 0.5 ); - dst[3] = 0xff; - -} - -static void BoxFilterRow( unsigned char *dstStart, cblock_t *in, int dstRow, int rowWidth ){ - int i; - unsigned char *indata = ( unsigned char * ) in->data; - - indata += 4 * dstRow * in->width; - - for ( i = 0; i < rowWidth; i++ ) - { - float c0 = i * s_resampleXRatio; - float c1 = ( i + 1 ) * s_resampleXRatio; - - BoxFilterHorizontalElements( &dstStart[i * 4], &indata[( ( int ) c0 ) * 4], c0, c1 ); - } -} - -static void BoxFilterColumn( unsigned char *dstStart, unsigned char *srcStart, int dstCol, int dstRowWidth, int dstColHeight, int srcRowWidthInPels ){ - float c0, c1; - int i; - - for ( i = 0; i < dstColHeight; i++ ) - { - c0 = i * s_resampleYRatio; - c1 = ( i + 1 ) * s_resampleYRatio; - - BoxFilterVerticalElements( &dstStart[i * 4 * dstRowWidth], &srcStart[(int)c0 * srcRowWidthInPels * 4], srcRowWidthInPels * 4, c0, c1 ); - } -} - -#define DROP_SAMPLE 0 -#define BOX_FILTER 1 - -static void ResampleFrame( cblock_t *in, unsigned char *out, int method, int outWidth, int outHeight ){ - int row, column; - unsigned char *indata = ( unsigned char * ) in->data; - - s_resampleXRatio = in->width / ( float ) outWidth; - s_resampleYRatio = in->height / ( float ) outHeight; - - if ( method == DROP_SAMPLE ) { - for ( row = 0; row < outHeight; row++ ) - { - int r = ( int ) ( row * s_resampleYRatio ); - - for ( column = 0; column < outWidth; column++ ) - { - int c = ( int ) ( column * s_resampleXRatio ); - - out[( row * outWidth + column ) * 4 + 0] = indata[( r * in->width + c ) * 4 + 0]; - out[( row * outWidth + column ) * 4 + 1] = indata[( r * in->width + c ) * 4 + 1]; - out[( row * outWidth + column ) * 4 + 2] = indata[( r * in->width + c ) * 4 + 2]; - out[( row * outWidth + column ) * 4 + 3] = 0xff; - } - } - } - else if ( method == BOX_FILTER ) { - unsigned char intermediate[1024 * 1024 * 4]; - - assert( in->height <= 1024 ); - assert( in->width <= 1024 ); - - // - // filter our M x N source image into a RESAMPLE_WIDTH x N horizontally filtered image - // - for ( row = 0; row < in->height; row++ ) - { - BoxFilterRow( &intermediate[row * 4 * outWidth], in, row, outWidth ); - } - - // - // filter our RESAMPLE_WIDTH x N horizontally filtered image into a RESAMPLE_WIDTH x RESAMPLE_HEIGHT filtered image - // - for ( column = 0; column < outWidth; column++ ) - { - BoxFilterColumn( &out[column * 4], &intermediate[column * 4], column, outWidth, outHeight, s_resample_width ); - } - } -} - -static float BTCDistanceSquared( float a[3], float b[3] ){ - return ( b[0] - a[0] ) * ( b[0] - a[0] ) + - ( b[1] - a[1] ) * ( b[1] - a[1] ) + - ( b[2] - a[2] ) * ( b[2] - a[2] ); -} - -static void BTCFindEndpoints( float inBlock[4][4][3], unsigned int endPoints[2][2] ){ - float longestDistance = -1; - - int bX, bY; - - // - // find the two points farthest from each other - // - for ( bY = 0; bY < 4; bY++ ) - { - for ( bX = 0; bX < 4; bX++ ) - { - int cX, cY; - float d; - - // - // check the rest of the current row - // - for ( cX = bX + 1; cX < 4; cX++ ) - { - if ( ( d = BTCDistanceSquared( inBlock[bY][bX], inBlock[bY][cX] ) ) > longestDistance ) { - longestDistance = d; - endPoints[0][0] = bX; - endPoints[0][1] = bY; - endPoints[1][0] = cX; - endPoints[1][1] = bY; - } - } - - // - // check remaining rows and columns - // - for ( cY = bY + 1; cY < 4; cY++ ) - { - for ( cX = 0; cX < 4; cX++ ) - { - if ( ( d = BTCDistanceSquared( inBlock[bY][bX], inBlock[cY][cX] ) ) > longestDistance ) { - longestDistance = d; - endPoints[0][0] = bX; - endPoints[0][1] = bY; - endPoints[1][0] = cX; - endPoints[1][1] = cY; - } - } - } - } - } -} - -static float BTCQuantizeBlock( float inBlock[4][4][3], unsigned long endPoints[2][2], int btcQuantizedBlock[4][4], float bestError ){ - int i; - int blockY, blockX; - float dR, dG, dB; - float R, G, B; - float error = 0; - float colorLine[4][3]; - - // - // build the color line - // - dR = inBlock[endPoints[1][1]][endPoints[1][0]][0] - - inBlock[endPoints[0][1]][endPoints[0][0]][0]; - dG = inBlock[endPoints[1][1]][endPoints[1][0]][1] - - inBlock[endPoints[0][1]][endPoints[0][0]][1]; - dB = inBlock[endPoints[1][1]][endPoints[1][0]][2] - - inBlock[endPoints[0][1]][endPoints[0][0]][2]; - - dR *= 0.33f; - dG *= 0.33f; - dB *= 0.33f; - - R = inBlock[endPoints[0][1]][endPoints[0][0]][0]; - G = inBlock[endPoints[0][1]][endPoints[0][0]][1]; - B = inBlock[endPoints[0][1]][endPoints[0][0]][2]; - - for ( i = 0; i < 4; i++ ) - { - colorLine[i][0] = R; - colorLine[i][1] = G; - colorLine[i][2] = B; - - R += dR; - G += dG; - B += dB; - } - - // - // quantize each pixel into the appropriate range - // - for ( blockY = 0; blockY < 4; blockY++ ) - { - for ( blockX = 0; blockX < 4; blockX++ ) - { - float distance = 10000000000; - int shortest = -1; - - for ( i = 0; i < 4; i++ ) - { - float d; - - if ( ( d = BTCDistanceSquared( inBlock[blockY][blockX], colorLine[i] ) ) < distance ) { - distance = d; - shortest = i; - } - } - - error += distance; - - // - // if bestError is not -1 then that means this is a speculative quantization - // - if ( bestError != -1 ) { - if ( error > bestError ) { - return error; - } - } - - btcQuantizedBlock[blockY][blockX] = shortest; - } - } - - return error; -} - -/* -** float BTCCompressBlock -*/ -static float BTCCompressBlock( float inBlock[4][4][3], unsigned long out[2] ){ - int i; - int btcQuantizedBlock[4][4]; // values should be [0..3] - unsigned long encodedEndPoints, encodedBitmap; - unsigned int endPoints[2][2]; // endPoints[0] = color start, endPoints[1] = color end - int blockY, blockX; - float error = 0; - float bestError = 10000000000; - unsigned int bestEndPoints[2][2]; - -#if 0 - // - // find the "ideal" end points for the color vector - // - BTCFindEndpoints( inBlock, endPoints ); - error = BTCQuantizeBlock( inBlock, endPoints, btcQuantizedBlock ); - memcpy( bestEndPoints, endPoints, sizeof( bestEndPoints ) ); -#else - for ( blockY = 0; blockY < 4; blockY++ ) - { - for ( blockX = 0; blockX < 4; blockX++ ) - { - int x2, y2; - - for ( y2 = 0; y2 < 4; y2++ ) - { - for ( x2 = 0; x2 < 4; x2++ ) - { - if ( ( x2 == blockX ) && ( y2 == blockY ) ) { - continue; - } - - endPoints[0][0] = blockX; - endPoints[0][1] = blockY; - endPoints[1][0] = x2; - endPoints[1][1] = y2; - - error = BTCQuantizeBlock( inBlock, endPoints, btcQuantizedBlock, -1 ); //bestError ); - - if ( error < bestError ) { - bestError = error; - memcpy( bestEndPoints, endPoints, sizeof( bestEndPoints ) ); - } - } - } - } - } - - error = BTCQuantizeBlock( inBlock, bestEndPoints, btcQuantizedBlock, -1.0f ); -#endif - - // - // encode the results - // - encodedBitmap = 0; - for ( blockY = 0; blockY < 4; blockY++ ) - { - for ( blockX = 0; blockX < 4; blockX++ ) - { - int shift = ( blockX + blockY * 4 ) * 2; - encodedBitmap |= btcQuantizedBlock[blockY][blockX] << shift; - } - } - - // - // encode endpoints - // - encodedEndPoints = 0; - for ( i = 0; i < 2; i++ ) - { - int iR, iG, iB; - - iR = ( ( int ) inBlock[bestEndPoints[i][1]][bestEndPoints[i][0]][0] ); - if ( iR > 255 ) { - iR = 255; - } - else if ( iR < 0 ) { - iR = 0; - } - iR >>= 3; - - iG = ( ( int ) inBlock[bestEndPoints[i][1]][bestEndPoints[i][0]][1] ); - if ( iG > 255 ) { - iG = 255; - } - else if ( iG < 0 ) { - iG = 0; - } - iG >>= 2; - - iB = ( ( int ) inBlock[bestEndPoints[i][1]][bestEndPoints[i][0]][2] ); - if ( iB > 255 ) { - iB = 255; - } - else if ( iB < 0 ) { - iB = 0; - } - iB >>= 3; - - - encodedEndPoints |= ( ( ( iR << 11 ) | ( iG << 5 ) | ( iB ) ) << ( i * 16 ) ); - } - - // - // store - // - out[0] = encodedBitmap; - out[1] = encodedEndPoints; - - return error; -} - -/* -** void BTCDecompressFrame -*/ -static void BTCDecompressFrame( unsigned long *src, unsigned char *dst ){ - int x, y; - int iR, iG, iB; - int dstX, dstY; - float colorStart[3], colorEnd[3]; - unsigned char colorRampABGR[4][4]; - unsigned encoded; - - memset( colorRampABGR, 0xff, sizeof( colorRampABGR ) ); - - for ( y = 0; y < s_resample_height / 4; y++ ) - { - for ( x = 0; x < s_resample_width / 4; x++ ) - { - unsigned colorStartPacked = src[( y * s_resample_width / 4 + x ) * 2 + 1] & 0xffff; - unsigned colorEndPacked = src[( y * s_resample_width / 4 + x ) * 2 + 1] >> 16; - - // - // grab the end points - // 0 = color start - // 1 = color end - // - iR = ( ( colorStartPacked >> 11 ) & ( ( 1 << 5 ) - 1 ) ); - iR = ( iR << 3 ) | ( iR >> 2 ); - iG = ( ( colorStartPacked >> 5 ) & ( ( 1 << 6 ) - 1 ) ); - iG = ( iG << 2 ) | ( iG >> 4 ); - iB = ( ( colorStartPacked ) & ( ( 1 << 5 ) - 1 ) ); - iB = ( iB << 3 ) | ( iB >> 2 ); - - colorStart[0] = iR; - colorStart[1] = iG; - colorStart[2] = iB; - colorRampABGR[0][0] = iR; - colorRampABGR[0][1] = iG; - colorRampABGR[0][2] = iB; - - iR = ( ( colorEndPacked >> 11 ) & ( ( 1 << 5 ) - 1 ) ); - iR = ( iR << 3 ) | ( iR >> 2 ); - iG = ( ( colorEndPacked >> 5 ) & ( ( 1 << 6 ) - 1 ) ); - iG = ( iG << 2 ) | ( iG >> 4 ); - iB = ( colorEndPacked & ( ( 1 << 5 ) - 1 ) ); - iB = ( iB << 3 ) | ( iB >> 2 ); - - colorEnd[0] = iR; - colorEnd[1] = iG; - colorEnd[2] = iB; - colorRampABGR[3][0] = iR; - colorRampABGR[3][1] = iG; - colorRampABGR[3][2] = iB; - - // - // compute this block's color ramp - // FIXME: This needs to be reversed on big-endian machines - // - - colorRampABGR[1][0] = colorStart[0] * 0.66f + colorEnd[0] * 0.33f; - colorRampABGR[1][1] = colorStart[1] * 0.66f + colorEnd[1] * 0.33f; - colorRampABGR[1][2] = colorStart[2] * 0.66f + colorEnd[2] * 0.33f; - - colorRampABGR[2][0] = colorStart[0] * 0.33f + colorEnd[0] * 0.66f; - colorRampABGR[2][1] = colorStart[1] * 0.33f + colorEnd[1] * 0.66f; - colorRampABGR[2][2] = colorStart[2] * 0.33f + colorEnd[2] * 0.66f; - - // - // decode the color data - // information is encoded in 2-bit pixels, with low order bits corresponding - // to upper left pixels. These 2-bit values are indexed into the block's - // computer color ramp. - // - encoded = src[( y * s_resample_width / 4 + x ) * 2 + 0]; - - for ( dstY = 0; dstY < 4; dstY++ ) - { - for ( dstX = 0; dstX < 4; dstX++ ) - { - memcpy( &dst[( y * 4 + dstY ) * s_resample_width * 4 + x * 4 * 4 + dstX * 4], colorRampABGR[encoded & 3], sizeof( colorRampABGR[0] ) ); - encoded >>= 2; - } - } - } - } -} - -/* -** BTCCompressFrame -** -** Perform a BTC compression using a 2-bit encoding at each pixel. This -** compression method is performed by decomposing the incoming image into -** a sequence of 4x4 blocks. At each block two color values are computed -** that define the endpoints of a vector in color space that represent -** the two colors "farthest apart". -*/ -static float BTCCompressFrame( unsigned char *src, unsigned long *dst ){ - int x, y; - int bX, bY; - float btcBlock[4][4][3]; - - float error = 0; - - for ( y = 0; y < s_resample_height / 4; y++ ) - { - for ( x = 0; x < s_resample_width / 4; x++ ) - { - // - // fill in the BTC block with raw values - // - for ( bY = 0; bY < 4; bY++ ) - { - for ( bX = 0; bX < 4; bX++ ) - { - btcBlock[bY][bX][0] = src[( y * 4 + bY ) * s_resample_width * 4 + ( x * 4 + bX ) * 4 + 0]; - btcBlock[bY][bX][1] = src[( y * 4 + bY ) * s_resample_width * 4 + ( x * 4 + bX ) * 4 + 1]; - btcBlock[bY][bX][2] = src[( y * 4 + bY ) * s_resample_width * 4 + ( x * 4 + bX ) * 4 + 2]; - } - } - - error += BTCCompressBlock( btcBlock, &dst[( y * s_resample_width / 4 + x ) * 2] ); - } - } - - return error / ( ( s_resample_width / 4 ) * ( s_resample_height / 4 ) ); -} - -/* - =================== - LoadFrame - =================== - */ -cblock_t LoadFrame( char *base, int frame, int digits, byte **palette ){ - int ten3, ten2, ten1, ten0; - cblock_t in; - int width, height; - char name[1024]; - FILE *f; - - in.data = NULL; - in.count = -1; - - ten3 = frame / 1000; - ten2 = ( frame - ten3 * 1000 ) / 100; - ten1 = ( frame - ten3 * 1000 - ten2 * 100 ) / 10; - ten0 = frame % 10; - - if ( digits == 4 ) { - sprintf( name, "%svideo/%s/%s%i%i%i%i.tga", gamedir, base, base, ten3, ten2, ten1, ten0 ); - } - else{ - sprintf( name, "%svideo/%s/%s%i%i%i.tga", gamedir, base, base, ten2, ten1, ten0 ); - } - - f = fopen( name, "rb" ); - if ( !f ) { - in.data = NULL; - return in; - } - fclose( f ); - - printf( "%s", name ); - LoadTGA( name, ( unsigned char ** ) &in.data, &width, &height ); - if ( palette ) { - *palette = 0; - } -// Load256Image (name, &in.data, palette, &width, &height); - in.count = width * height; - in.width = width; - in.height = height; -// FIXME: map 0 and 255! - -#if 0 - // rle compress - rle = RLE( in ); - free( in.data ); - - return rle; -#endif - - return in; -} - -/* - =============== - Cmd_Video - - video - =============== - */ -void Cmd_Video( void ){ - float sumError = 0, error = 0, maxError = 0; - char savename[1024]; - char name[1024]; - FILE *output; - int startframe, frame; - int width, height; - int i; - int digits; - int minutes; - float fseconds; - int remSeconds; - cblock_t in; - unsigned char *resampled; - unsigned long *compressed; - clock_t start, stop; - - GetToken( qfalse ); - strcpy( s_base, token ); - if ( g_release ) { -// sprintf (savename, "video/%s.cin", token); -// ReleaseFile (savename); - return; - } - - GetToken( qfalse ); - strcpy( s_output_base, token ); - - GetToken( qfalse ); - digits = atoi( token ); - - GetToken( qfalse ); - - if ( !strcmp( token, "btc" ) ) { - s_compression_method = BTC_COMPRESSION; - printf( "Compression: BTC\n" ); - } - else if ( !strcmp( token, "uc" ) ) { - s_compression_method = UNCOMPRESSED; - printf( "Compression: none\n" ); - } - else - { - Error( "Uknown compression method '%s'\n", token ); - } - - GetToken( qfalse ); - s_resample_width = atoi( token ); - - GetToken( qfalse ); - s_resample_height = atoi( token ); - - resampled = malloc( sizeof( unsigned char ) * 4 * s_resample_width * s_resample_height ); - compressed = malloc( sizeof( long ) * 2 * ( s_resample_width / 4 ) * ( s_resample_height / 4 ) ); - - printf( "Resample width: %d\n", s_resample_width ); - printf( "Resample height: %d\n", s_resample_height ); - - // optionally skip frames - if ( TokenAvailable() ) { - GetToken( qfalse ); - startframe = atoi( token ); - } - else{ - startframe = 0; - } - - sprintf( savename, "%svideo/%s.%s", writedir, s_output_base, CIN_EXTENSION ); - - // load the entire sound wav file if present - LoadSoundtrack(); - - if ( digits == 4 ) { - sprintf( name, "%svideo/%s/%s0000.tga", gamedir, s_base, s_base ); - } - else{ - sprintf( name, "%svideo/%s/%s000.tga", gamedir, s_base, s_base ); - } - - printf( "%s\n", name ); - LoadTGA( name, NULL, &width, &height ); - - output = fopen( savename, "wb" ); - if ( !output ) { - Error( "Can't open %s", savename ); - } - - // write header info - i = LittleLong( CIN_SIGNATURE ); - fwrite( &i, 4, 1, output ); - i = LittleLong( s_resample_width ); - fwrite( &i, 4, 1, output ); - i = LittleLong( s_resample_height ); - fwrite( &i, 4, 1, output ); - i = LittleLong( s_wavinfo.rate ); - fwrite( &i, 4, 1, output ); - i = LittleLong( s_wavinfo.width ); - fwrite( &i, 4, 1, output ); - i = LittleLong( s_wavinfo.channels ); - fwrite( &i, 4, 1, output ); - i = LittleLong( s_compression_method ); - fwrite( &i, 4, 1, output ); - - start = clock(); - - // perform compression on a per frame basis - for ( frame = startframe ; ; frame++ ) - { - printf( "%02d: ", frame ); - in = LoadFrame( s_base, frame, digits, 0 ); - if ( !in.data ) { - break; - } - - ResampleFrame( &in, ( unsigned char * ) resampled, BOX_FILTER, s_resample_width, s_resample_height ); - - if ( s_compression_method == UNCOMPRESSED ) { - printf( "\n" ); - fwrite( resampled, 1, sizeof( unsigned char ) * s_resample_width * s_resample_height * 4, output ); - -#if OUTPUT_TGAS - { - int x, y; - char buffer[1000]; - - for ( y = 0; y < s_resample_height / 2; y++ ) - { - for ( x = 0; x < s_resample_width; x++ ) - { - unsigned char tmp[4]; - - tmp[0] = resampled[( s_resample_height - 1 - y ) * s_resample_width * 4 + x * 4 + 0]; - tmp[1] = resampled[( s_resample_height - 1 - y ) * s_resample_width * 4 + x * 4 + 1]; - tmp[2] = resampled[( s_resample_height - 1 - y ) * s_resample_width * 4 + x * 4 + 2]; - tmp[3] = resampled[( s_resample_height - 1 - y ) * s_resample_width * 4 + x * 4 + 3]; - - resampled[( s_resample_height - 1 - y ) * s_resample_width * 4 + x * 4 + 0] = resampled[y * s_resample_width * 4 + x * 4 + 0]; - resampled[( s_resample_height - 1 - y ) * s_resample_width * 4 + x * 4 + 1] = resampled[y * s_resample_width * 4 + x * 4 + 1]; - resampled[( s_resample_height - 1 - y ) * s_resample_width * 4 + x * 4 + 2] = resampled[y * s_resample_width * 4 + x * 4 + 2]; - resampled[( s_resample_height - 1 - y ) * s_resample_width * 4 + x * 4 + 3] = resampled[y * s_resample_width * 4 + x * 4 + 3]; - - resampled[y * s_resample_width * 4 + x * 4 + 0] = tmp[0]; - resampled[y * s_resample_width * 4 + x * 4 + 1] = tmp[1]; - resampled[y * s_resample_width * 4 + x * 4 + 2] = tmp[2]; - resampled[y * s_resample_width * 4 + x * 4 + 3] = tmp[3]; - } - } - - sprintf( buffer, "%svideo/%s/uc%04d.tga", gamedir, s_base, frame ); - WriteTGA( buffer, resampled, s_resample_width, s_resample_height ); - } -#endif - } - else if ( s_compression_method == BTC_COMPRESSION ) { - error = BTCCompressFrame( resampled, compressed ); - - sumError += error; - - if ( error > maxError ) { - maxError = error; - } - - printf( " (error = %f)\n", error ); - fwrite( compressed, 1, 2 * sizeof( long ) * ( s_resample_width / 4 ) * ( s_resample_height / 4 ), output ); - -#if OUTPUT_TGAS - { - int x, y; - unsigned char *uncompressed; - char buffer[1000]; - - uncompressed = malloc( sizeof( unsigned char ) * 4 * s_resample_width * s_resample_height ); - BTCDecompressFrame( compressed, uncompressed ); - - for ( y = 0; y < s_resample_height / 2; y++ ) - { - for ( x = 0; x < s_resample_width; x++ ) - { - unsigned char tmp[4]; - - tmp[0] = uncompressed[( s_resample_height - 1 - y ) * s_resample_width * 4 + x * 4 + 0]; - tmp[1] = uncompressed[( s_resample_height - 1 - y ) * s_resample_width * 4 + x * 4 + 1]; - tmp[2] = uncompressed[( s_resample_height - 1 - y ) * s_resample_width * 4 + x * 4 + 2]; - tmp[3] = uncompressed[( s_resample_height - 1 - y ) * s_resample_width * 4 + x * 4 + 3]; - - uncompressed[( s_resample_height - 1 - y ) * s_resample_width * 4 + x * 4 + 0] = uncompressed[y * s_resample_width * 4 + x * 4 + 0]; - uncompressed[( s_resample_height - 1 - y ) * s_resample_width * 4 + x * 4 + 1] = uncompressed[y * s_resample_width * 4 + x * 4 + 1]; - uncompressed[( s_resample_height - 1 - y ) * s_resample_width * 4 + x * 4 + 2] = uncompressed[y * s_resample_width * 4 + x * 4 + 2]; - uncompressed[( s_resample_height - 1 - y ) * s_resample_width * 4 + x * 4 + 3] = uncompressed[y * s_resample_width * 4 + x * 4 + 3]; - - uncompressed[y * s_resample_width * 4 + x * 4 + 0] = tmp[0]; - uncompressed[y * s_resample_width * 4 + x * 4 + 1] = tmp[1]; - uncompressed[y * s_resample_width * 4 + x * 4 + 2] = tmp[2]; - uncompressed[y * s_resample_width * 4 + x * 4 + 3] = tmp[3]; - } - } - - - sprintf( buffer, "%svideo/%s/btc%04d.tga", gamedir, s_base, frame ); - WriteTGA( buffer, uncompressed, s_resample_width, s_resample_height ); - - free( uncompressed ); - } -#endif - } - - WriteSound( output, frame ); - - free( in.data ); - } - stop = clock(); - - printf( "\n" ); - - printf( "Total size: %i\n", ftell( output ) ); - printf( "Average error: %f\n", sumError / ( frame - startframe ) ); - printf( "Max error: %f\n", maxError ); - - fseconds = ( stop - start ) / 1000.0f; - minutes = fseconds / 60; - remSeconds = fseconds - minutes * 60; - - printf( "Total time: %d s (%d m %d s)\n", ( int ) fseconds, minutes, remSeconds ); - printf( "Time/frame: %.2f seconds\n", fseconds / ( frame - startframe ) ); - - fclose( output ); - - if ( s_soundtrack ) { - free( s_soundtrack ); - s_soundtrack = 0; - } -} diff --git a/tools/urt/tools/quake3/q3map2/image.c b/tools/urt/tools/quake3/q3map2/image.c index 2cb769a..781da39 100644 --- a/tools/urt/tools/quake3/q3map2/image.c +++ b/tools/urt/tools/quake3/q3map2/image.c @@ -386,7 +386,7 @@ image_t *ImageLoad( const char *filename ){ strcat( name, ".tga" ); size = vfsLoadFile( (const char*) name, (void**) &buffer, 0 ); if ( size > 0 ) { - LoadTGABuffer( buffer, &image->pixels, &image->width, &image->height ); + LoadTGABuffer( buffer, buffer + size, &image->pixels, &image->width, &image->height ); } else { diff --git a/tools/urt/tools/quake3/q3map2/lightmaps_ydnar.c b/tools/urt/tools/quake3/q3map2/lightmaps_ydnar.c index e8a1d20..ea276d2 100644 --- a/tools/urt/tools/quake3/q3map2/lightmaps_ydnar.c +++ b/tools/urt/tools/quake3/q3map2/lightmaps_ydnar.c @@ -230,7 +230,7 @@ int ImportLightmapsMain( int argc, char **argv ){ /* parse file into an image */ pixels = NULL; - LoadTGABuffer( buffer, &pixels, &width, &height ); + LoadTGABuffer( buffer, buffer + len, &pixels, &width, &height ); free( buffer ); /* sanity check it */ diff --git a/tools/urt/tools/quake3/q3map2/q3map2.h b/tools/urt/tools/quake3/q3map2/q3map2.h index ba81ef3..5ff29c8 100644 --- a/tools/urt/tools/quake3/q3map2/q3map2.h +++ b/tools/urt/tools/quake3/q3map2/q3map2.h @@ -79,7 +79,6 @@ #include "inout.h" #include "vfs.h" #include "png.h" -#include "radiant_jpeglib.h" #include